@crewx/sdk 0.9.0-rc.23 → 0.9.0-rc.231
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-install/dependencies.d.ts +30 -0
- package/dist/app-install/errors.d.ts +9 -0
- package/dist/app-install/index.d.ts +9 -0
- package/dist/app-install/index.js +7 -0
- package/dist/app-install/process.d.ts +33 -0
- package/dist/app-install/runtime-env.d.ts +2 -0
- package/dist/app-install/verify.d.ts +10 -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 +13 -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 +9 -3
- package/dist/conversation/to-template-messages.d.ts +12 -2
- package/dist/conversation/types.d.ts +94 -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-install/index.js +7 -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 +1450 -224
- package/dist/esm/node/index.js +2 -0
- package/dist/esm/plugins/index.js +604 -219
- package/dist/esm/process/index.js +1 -0
- package/dist/esm/publish/index.js +2 -0
- package/dist/esm/repository/index.js +863 -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 +108 -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 +84 -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 +175 -20
- package/dist/index.js +1450 -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/0058_thread_branches.sql +37 -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/0058_snapshot.json +7227 -0
- package/dist/migrations/meta/_journal.json +336 -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 +604 -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 +23 -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/claude-task-events.d.ts +48 -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 +63 -6
- package/dist/repository/index.js +863 -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 +87 -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-branch.repository.d.ts +106 -0
- 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 +440 -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 +24 -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-branches.d.ts +424 -0
- 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/claude-background-task.d.ts +30 -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 +3325 -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 +221 -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 +97 -3
- package/templates/agents/default.yaml +319 -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
|
@@ -1,19 +1,179 @@
|
|
|
1
|
-
import*as
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import*as Oe from'path';import Oe__default,{join,dirname,resolve}from'path';import {fileURLToPath}from'url';import*as Au from'fs';import {existsSync,mkdirSync,writeFileSync,appendFileSync,lstatSync,readFileSync,statSync,realpathSync}from'fs';import*as Va from'os';import Va__default,{homedir,tmpdir}from'os';import {createHash,randomBytes,randomUUID}from'crypto';import {sqliteTable,text,integer,index,check,primaryKey,real,uniqueIndex,unique,foreignKey}from'drizzle-orm/sqlite-core';import {sql,and,eq,inArray,or,isNull,ne,desc,lt,asc,like,gte,isNotNull,notLike,getTableColumns}from'drizzle-orm';import {spawnSync,spawn,execFile}from'child_process';import'string_decoder';import {mkdtemp,open,rm}from'fs/promises';var kp=Object.defineProperty;var An=(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 C=(t,e)=>()=>(t&&(e=t(t=0)),e);var yp=(t,e)=>{for(var n in e)kp(t,n,{get:e[n],enumerable:true});};var Ep,Rp,R,g=C(()=>{Ep=()=>fileURLToPath(import.meta.url),Rp=()=>Oe__default.dirname(Ep()),R=Rp();});var f,Ot=C(()=>{g();f=class extends Error{code;cause;constructor(e,n,r){super(n),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};});function Ka(t){if(t===":memory:")return t;let e=resolve(t),n=e,r=[];for(;!existsSync(n);){let s=dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=realpathSync(n);for(let s of r)o=join(o,s);return resolve(o)}function Pp(t,e){let n=Ka(t),r=Ka(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function sn(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&Lp.some(e=>Pp(t,join(Va__default.homedir(),".crewx",e))))throw new Error(`${Dp}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var Dp,Lp,ke,vt=C(()=>{g();Dp="[crewx] Refusing to open the real CrewX database from a test process";Lp=["crewx.db","logs.db"];ke=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||join(Va__default.homedir(),".crewx","crewx.db");return sn(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};});function U(t,e={}){let n=sn(t),r=An("better-sqlite3"),{drizzle:o}=An("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 = ${$p}`),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,c=[])=>s.prepare(i).run(...c),close:()=>s.close()}}var $p,Bt=C(()=>{g();vt();$p=32*1024*1024;});function On(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Up(t,e){if(e>0||!On(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(Hp))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function Bp(t,e,n){if(!On(t,"__drizzle_migrations")||!On(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(Oe__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let c=qp[i.tag];if(!c)continue;let d=Oe__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let u=readFileSync(d,"utf-8"),l=createHash("sha256").update(u).digest("hex");if(o.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),_=new Set(p.map(h=>h.name));for(let[h,m]of Object.entries(c))_.has(h)||(t.run(`ALTER TABLE tasks ADD COLUMN ${h} ${m}`),_.add(h));}}function Qa(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 Za(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function Fp(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(s=>s.name===n)}function Wp(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function no(t,e){return e.kind==="add-column"?Fp(t,e.table,e.column):Wp(t,e.name)}function ed(t,e,n){let r=t;for(let o of Za(e)){let s=Qa(o);s?.kind==="add-column"&&no(r,s)||s?.kind==="create-index"&&no(r,s)||s?.kind==="drop-index"&&!no(r,s)||r.run(n.raw(o));}}function Gp(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(Oe__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let c=Oe__default.join(e,`${i.tag}.sql`);if(!existsSync(c))continue;let d=readFileSync(c,"utf-8"),u=createHash("sha256").update(d).digest("hex");if(o.has(u))continue;let p=Za(d).map(Qa);if(p.some(h=>!h))continue;let _=p;_.some(h=>h.kind==="add-column")&&_.some(h=>no(t,h))&&(t.transaction(h=>{ed(h,d,n),h.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 jp(t,e){let{sql:n}=An("drizzle-orm"),r=JSON.parse(readFileSync(Oe__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 c=r.entries.find(u=>u.tag===i);if(!c)throw new Error(`Missing release/App compatibility migration: ${i}`);let d=readFileSync(Oe__default.join(e,`${i}.sql`),"utf-8");return {entry:c,content:d,hash:createHash("sha256").update(d).digest("hex")}});t.transaction(i=>{let c=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(d=>d.hash));if(c.has(s[0].hash))for(let d of s.slice(1))c.has(d.hash)||(ed(i,d.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${d.hash}, ${d.entry.when})`),c.add(d.hash),console.error(`[crewx] Replayed release/App migration ${d.entry.tag} safely.`));},{behavior:"immediate"});}function Vp(t,e,n,r){let s=JSON.parse(readFileSync(Oe__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===zp);if(!s)return;let i=Oe__default.join(e,`${s.tag}.sql`);if(!existsSync(i))return;let c=createHash("sha256").update(readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c))return;if(!On(t,"tasks"))return {hash:c,affectedRows:0};let d=t.all("PRAGMA table_info(tasks)"),u=new Set(d.map(p=>p.name));if(!u.has("stop_requested_at")||!u.has("stop_requested_epoch"))return {hash:c,affectedRows:0};let l=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:c,affectedRows:l?.count??0}}function Xp(t,e,n,r){let s=JSON.parse(readFileSync(Oe__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===Kp);if(!s)return;let i=Oe__default.join(e,`${s.tag}.sql`);if(!existsSync(i))return;let c=createHash("sha256").update(readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c))return;if(!On(t,"threads"))return {hash:c,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(p=>p.name==="created_by_task_id"))return {hash:c,markedPointers:0};let u=On(t,Ya)?`AND NOT EXISTS (
|
|
7
|
+
SELECT 1
|
|
8
|
+
FROM ${Ya} AS marked
|
|
9
|
+
WHERE marked.thread_id = current.id
|
|
10
|
+
AND marked.created_by_task_id = current.created_by_task_id
|
|
11
|
+
)`:"",l=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 = '${Jp}'
|
|
19
|
+
)
|
|
20
|
+
${u}`);return {hash:c,markedPointers:l?.count??0}}function Yp(t){let{migrate:e}=An("drizzle-orm/better-sqlite3/migrator"),{sql:n}=An("drizzle-orm"),r=[Oe__default.join(R,"../migrations"),Oe__default.join(R,"migrations"),Oe__default.join(R,"../../../../drizzle/migrations"),Oe__default.join(process.cwd(),"drizzle/migrations")],o=r.find(p=>existsSync(Oe__default.join(p,"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),Up(t,i),s?.cnt&&(jp(t,o),Gp(t,o,n),Bp(t,o,n));let c=Vp(t,o,n,!!s?.cnt),d=Xp(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let p=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${p} (${l} migration${l>1?"s":""} applied).`);}c&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c.hash)&&console.error(`[crewx] Task stop-marker cleanup (${c.affectedRows} success/failed row(s) affected).`),d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===d.hash)&&console.error(`[crewx] Thread creator pointer migration (${d.markedPointers} pointer(s) marked unverified).`);}function Le(t,e){Xa.has(e)||(Yp(t),Xa.add(e));}var Xa,Hp,qp,zp,Kp,Jp,Ya,Ft=C(()=>{g();Xa=new Set,Hp={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"};qp={"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"}};zp="0027_task_stop_scope_cleanup",Kp="0033_thread_creator_boundary_guard",Jp="trg_threads_creator_late_fill_guard",Ya="thread_creator_unverified";});var le,ro=C(()=>{g();le=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),starred:integer("starred").notNull().default(0)});});var a,hT,n_,pe,vn=C(()=>{g();a=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),actor_kind:text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:text("actor_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),pid_started_at:text("pid_started_at"),heartbeat_at:text("heartbeat_at"),stop_requested_at:text("stop_requested_at"),stop_requested_epoch:integer("stop_requested_epoch"),rendered_prompt:text("rendered_prompt"),security_key:text("security_key"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),cwd:text("cwd"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0),rating:text("rating",{enum:["up","down"]}),rated_at:text("rated_at"),workflow_run_id:text("workflow_run_id"),schedule_id:text("schedule_id")},t=>({log_storage_check:check("tasks_log_storage_ck",sql`${t.log_storage} IN ('blob', 'events')`),rating_check:check("tasks_rating_ck",sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:index("idx_tasks_status").on(t.status),idx_tasks_started_at:index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(sql`${t.rating} IS NOT NULL`)})),{security_key:hT,...n_}=getTableColumns(a),pe=n_;});var bt,od=C(()=>{g();vn();bt=sqliteTable("task_provider_inputs",{task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),run_epoch:integer("run_epoch").notNull(),input:text("input").notNull(),key_wrap_skipped:integer("key_wrap_skipped").notNull().default(0),recorded_at:text("recorded_at").notNull()},t=>({pk:primaryKey({columns:[t.task_id,t.run_epoch]})}));});var mt,id=C(()=>{g();vn();mt=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},t=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var c_,u_,y,bn=C(()=>{g();ro();c_="json_extract(metadata, '$.threadTitle.state')",u_="json_extract(metadata, '$.threadTitle.priority')",y=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>le.id,{onDelete:"set null"}),created_by_kind:text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:text("created_by_id"),created_by_task_id:text("created_by_task_id"),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(t.workspace_id,sql.raw(c_)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(u_))}));});var cd=C(()=>{g();sqliteTable("thread_creator_unverified",{thread_id:text("thread_id").notNull(),created_by_task_id:text("created_by_task_id").notNull()},t=>({pk:primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var g_,ld=C(()=>{g();vn();g_=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>g_.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},t=>({idx_spans_task_id:index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var pd=C(()=>{g();vn();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},t=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(t.timestamp)}));});var fd=C(()=>{g();bn();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:unique().on(t.thread_id,t.seq)}));});var z,kt,hd=C(()=>{g();bn();z=sqliteTable("thread_branches",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),parent_thread_id:text("parent_thread_id").notNull().references(()=>y.id),child_thread_id:text("child_thread_id").notNull().unique().references(()=>y.id,{onDelete:"cascade"}),branch_point_task_id:text("branch_point_task_id").notNull(),branch_answer_no:integer("branch_answer_no").notNull(),first_task_id:text("first_task_id").notNull(),parent_title:text("parent_title").notNull(),actor_id:text("actor_id").notNull(),request_id:text("request_id").notNull(),payload_hash:text("payload_hash").notNull(),snapshot_version:integer("snapshot_version").notNull(),carry_json:text("carry_json").notNull(),carried_turns:integer("carried_turns").notNull(),carried_chars:integer("carried_chars").notNull(),carried_truncated:integer("carried_truncated").notNull().default(0),status:text("status",{enum:["active","undone"]}).notNull().default("active"),created_at:text("created_at").notNull(),undone_at:text("undone_at")},t=>({idx_thread_branches_parent_point:index("idx_thread_branches_parent_point").on(t.parent_thread_id,t.branch_point_task_id),uniq_thread_branches_request:unique("uniq_thread_branches_workspace_actor_request").on(t.workspace_id,t.actor_id,t.request_id),thread_branches_status_ck:check("thread_branches_status_ck",sql`${t.status} IN ('active', 'undone')`),thread_branches_carried_truncated_ck:check("thread_branches_carried_truncated_ck",sql`${t.carried_truncated} IN (0, 1)`)})),kt=sqliteTable("thread_branch_sources",{branch_id:text("branch_id").primaryKey().references(()=>z.id,{onDelete:"cascade"}),source_json:text("source_json").notNull(),bytes:integer("bytes").notNull()},t=>({thread_branch_sources_bytes_ck:check("thread_branch_sources_bytes_ck",sql`${t.bytes} >= 0 AND ${t.bytes} <= 524288`)}));});var kd=C(()=>{g();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},t=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(t.partition_key)}));});var yd=C(()=>{g();sqliteTable("request_log_daily",{day:text("day").notNull(),scope:text("scope").notNull(),ok:integer("ok").notNull(),client:integer("client").notNull(),server:integer("server").notNull(),p50_ms:integer("p50_ms"),p95_ms:integer("p95_ms"),computed_at:text("computed_at").notNull()},t=>({pk:primaryKey({columns:[t.day,t.scope]})}));});var Ed=C(()=>{g();sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var Rd=C(()=>{g();sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},t=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var Id=C(()=>{g();sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},t=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(t.workspace_id,sql`${t.created_at} DESC`)})),sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},t=>({pk:primaryKey({columns:[t.notification_id,t.user_id]})}));});var Nd=C(()=>{g();sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var Od=C(()=>{g();sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),app_id:text("app_id"),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),opened_by_json:text("opened_by_json"),agent_open_request_json:text("agent_open_request_json"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({idCheck:check("ui_instances_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${t.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:check("ui_instances_app_id_ck",sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${t.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:check("ui_instances_opened_by_json_ck",sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:check("ui_instances_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(sql`${t.status} = 'active'`)}));});var bd=C(()=>{g();sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),definition_id:text("definition_id"),definition_version:integer("definition_version"),definition_hash:text("definition_hash"),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},t=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${t.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${t.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${t.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",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:uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var Cd=C(()=>{g();sqliteTable("ui_instance_repins",{instance_id:text("instance_id").notNull(),from_version:integer("from_version").notNull(),from_hash:text("from_hash").notNull(),to_version:integer("to_version").notNull(),to_hash:text("to_hash").notNull(),from_revision:integer("from_revision").notNull(),to_revision:integer("to_revision"),status:text("status").notNull(),code:text("code"),attempts:integer("attempts").notNull().default(1),first_at:integer("first_at").notNull(),last_at:integer("last_at").notNull()},t=>({pk:primaryKey({columns:[t.instance_id,t.to_hash],name:"ui_instance_repins_pk"}),instanceIdCheck:check("ui_instance_repins_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 5 AND 128 AND ${t.instance_id} GLOB 'uic_*'`),fromVersionCheck:check("ui_instance_repins_from_version_ck",sql`${t.from_version} >= 1`),toVersionCheck:check("ui_instance_repins_to_version_ck",sql`${t.to_version} >= 1`),fromHashCheck:check("ui_instance_repins_from_hash_ck",sql`length(${t.from_hash}) = 64 AND ${t.from_hash} NOT GLOB '*[^0-9a-f]*'`),toHashCheck:check("ui_instance_repins_to_hash_ck",sql`length(${t.to_hash}) = 64 AND ${t.to_hash} NOT GLOB '*[^0-9a-f]*'`),fromRevisionCheck:check("ui_instance_repins_from_revision_ck",sql`${t.from_revision} >= 0`),toRevisionCheck:check("ui_instance_repins_to_revision_ck",sql`${t.to_revision} IS NULL OR ${t.to_revision} >= 0`),statusCheck:check("ui_instance_repins_status_ck",sql`${t.status} IN ('applied', 'deferred', 'failed')`),attemptsCheck:check("ui_instance_repins_attempts_ck",sql`${t.attempts} >= 1`),datesCheck:check("ui_instance_repins_dates_ck",sql`${t.first_at} >= 0 AND ${t.last_at} >= ${t.first_at}`),resultCheck:check("ui_instance_repins_result_ck",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 Dd=C(()=>{g();sqliteTable("ui_definition_archive",{definition_hash:text("definition_hash").primaryKey().notNull(),definition_json:text("definition_json").notNull(),created_at:integer("created_at").notNull()},t=>({definitionHashCheck:check("ui_definition_archive_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:check("ui_definition_archive_definition_json_ck",sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:check("ui_definition_archive_created_at_ck",sql`${t.created_at} >= 0`)}));});var Ld,Md=C(()=>{g();Ld=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},t=>({idCheck:check("projects_id_ck",sql`${t.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${t.stage_index} >= 1`)})),sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>Ld.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idCheck:check("project_criteria_id_ck",sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>Ld.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},t=>({idCheck:check("project_events_id_ck",sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var Cs,xs,M,Ds=C(()=>{g();Cs=["THREAD_STATE","THREAD_PRIORITY"],xs=["gray","blue","violet","green","amber","orange","red","pink"],M=sqliteTable("common_codes",{code_group:text("code_group").notNull(),code:text("code").notNull(),code_name:text("code_name"),color:text("color").notNull().default("gray"),sort_order:integer("sort_order").notNull(),workspace_id:text("workspace_id"),is_builtin:integer("is_builtin").notNull().default(0),is_archived:integer("is_archived").notNull().default(0),metadata:text("metadata"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({pk:primaryKey({columns:[t.code_group,t.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${t.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var $d,Hd,Ud,qd,Bd,Y,K,F,Fd=C(()=>{g();bn();$d=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Hd=["user","agent","system"],Ud=["auto","manual"],qd=["decision","judgment","issue","result","pivot"],Bd=["queued","running","completed","failed"],Y=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},t=>({typeCheck:check("thread_events_type_ck",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:check("thread_events_actor_type_ck",sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),K=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),request_id:text("request_id").notNull(),status:text("status").notNull(),detector_version:text("detector_version").notNull(),requested_at:text("requested_at").notNull(),started_at:text("started_at"),completed_at:text("completed_at"),error_code:text("error_code"),previous_auto_count:integer("previous_auto_count"),new_auto_count:integer("new_auto_count")},t=>({statusCheck:check("thread_highlight_runs_status_ck",sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:check("thread_highlight_runs_counts_ck",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:uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),F=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},t=>({sourceCheck:check("thread_highlights_source_ck",sql`${t.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",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:index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(sql`${t.source} = 'auto'`)}));});var Gd=C(()=>{g();sqliteTable("storage_metadata",{source_kind:text("source_kind").notNull(),source_id:text("source_id").notNull(),utc_ts:text("utc_ts"),bytes:integer("bytes").notNull()},t=>({pk:primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteTable("storage_metadata_state",{unit:text("unit").primaryKey().notNull(),cursor_rowid:integer("cursor_rowid").notNull().default(0),end_rowid:integer("end_rowid"),complete:integer("complete").notNull().default(0),updated_at:text("updated_at").notNull()});});var Ge,jd=C(()=>{g();Ge=sqliteTable("agent_send_history",{workspace_id:text("workspace_id").notNull(),actor_id:text("actor_id").notNull(),agent_id:text("agent_id").notNull(),last_accepted_at:text("last_accepted_at").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var Jd,Vd=C(()=>{g();bn();ro();sqliteTable("sidebar_states",{workspace_id:text("workspace_id").primaryKey().references(()=>le.id,{onDelete:"cascade"}),revision:integer("revision").notNull().default(0),rail_collapsed:integer("rail_collapsed").notNull().default(0),seeded_at:text("seeded_at").notNull()},t=>({railCollapsedCheck:check("sidebar_states_rail_collapsed_ck",sql`${t.rail_collapsed} IN (0, 1)`)})),Jd=sqliteTable("sidebar_groups",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull().references(()=>le.id,{onDelete:"cascade"}),name:text("name").notNull(),color:text("color").notNull(),collapsed:integer("collapsed").notNull().default(0),position:integer("position").notNull()},t=>({colorCheck:check("sidebar_groups_color_ck",sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue', 'green', 'lime', 'yellow', 'coral', 'pink', 'indigo', 'sand', 'gray')`),collapsedCheck:check("sidebar_groups_collapsed_ck",sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteTable("sidebar_tabs",{workspace_id:text("workspace_id").notNull().references(()=>le.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>Jd.id,{onDelete:"set null"}),position:integer("position").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteTable("sidebar_closed_tabs",{id:integer("id").primaryKey({autoIncrement:true}),workspace_id:text("workspace_id").notNull().references(()=>le.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),group_id:text("group_id").references(()=>Jd.id,{onDelete:"set null"}),position:integer("position").notNull(),closed_at:text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteTable("thread_reads",{workspace_id:text("workspace_id").notNull().references(()=>le.id,{onDelete:"cascade"}),thread_id:text("thread_id").notNull().references(()=>y.id,{onDelete:"cascade"}),read_through_at:text("read_through_at").notNull()},t=>({pk:primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var Xd=C(()=>{g();sqliteTable("schedule_runs",{id:text("id").primaryKey(),schedule_id:text("schedule_id").notNull(),workspace_id:text("workspace_id").notNull(),mode:text("mode").notNull(),trigger:text("trigger").notNull(),occurrence_key:text("occurrence_key"),task_id:text("task_id"),app_id:text("app_id"),schedule_name:text("schedule_name"),builtin_id:text("builtin_id"),command:text("command"),high_frequency:integer("high_frequency").notNull().default(0),status:text("status").notNull(),error_code:text("error_code"),exit_code:integer("exit_code"),signal:text("signal"),started_at:text("started_at").notNull(),finished_at:text("finished_at"),duration_ms:integer("duration_ms"),pid:integer("pid"),host_pid:integer("host_pid"),output_tail:text("output_tail"),output_bytes:integer("output_bytes"),output_truncated:integer("output_truncated").notNull().default(0)},t=>({idx_schedule_runs_workspace_started:index("idx_schedule_runs_workspace_started").on(t.workspace_id,sql`${t.started_at} DESC`),idx_schedule_runs_schedule_started:index("idx_schedule_runs_schedule_started").on(t.schedule_id,sql`${t.started_at} DESC`),idx_schedule_runs_task_id:index("idx_schedule_runs_task_id").on(t.task_id),idx_schedule_runs_running:index("idx_schedule_runs_running").on(t.workspace_id,t.started_at).where(sql`${t.status} = 'running'`)}));});var Yd=C(()=>{g();sqliteTable("run_column_backfill",{name:text("name").primaryKey(),cursor:integer("cursor"),anchor_id:text("anchor_id"),completed_at:text("completed_at")});});var Qd=C(()=>{g();sqliteTable("doc_sync_connect_requests",{request_id:text("request_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),app_id:text("app_id").notNull(),ref:text("ref").notNull(),sent_hash:text("sent_hash").notNull(),created_at:integer("created_at").notNull()},t=>({requestIdCheck:check("doc_sync_connect_requests_request_id_ck",sql`length(${t.request_id}) = 36`),accountKeyCheck:check("doc_sync_connect_requests_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("doc_sync_connect_requests_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:check("doc_sync_connect_requests_app_id_ck",sql`length(${t.app_id}) BETWEEN 1 AND 128`),refCheck:check("doc_sync_connect_requests_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),sentHashCheck:check("doc_sync_connect_requests_sent_hash_ck",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:check("doc_sync_connect_requests_created_at_ck",sql`${t.created_at} >= 0`),connectUnique:uniqueIndex("doc_sync_connect_requests_connect_uq").on(t.account_key,t.workspace_id,t.app_id,t.ref)}));});var Zd=C(()=>{g();sqliteTable("doc_sync_links",{doc_id:text("doc_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),app_id:text("app_id").notNull(),root_segments:text("root_segments").notNull(),ref:text("ref").notNull(),cloud_ref:text("cloud_ref").notNull(),connection_kind:text("connection_kind").$type().notNull().default("document"),app_grant_id:text("app_grant_id"),app_grant_generation:integer("app_grant_generation"),app_scope_version:text("app_scope_version"),origin:text("origin").notNull().default("own"),sync_state:text("sync_state").notNull().default("ok"),end_reason:text("end_reason"),file_state:text("file_state").notNull().default("present"),synced_revision:integer("synced_revision").notNull(),synced_hash:text("synced_hash").notNull(),synced_at:integer("synced_at").notNull(),file_dev_ino:text("file_dev_ino"),conflict_revision:integer("conflict_revision"),conflict_hash:text("conflict_hash"),conflict_at:integer("conflict_at"),remote_revision:integer("remote_revision"),remote_checked_at:integer("remote_checked_at"),published_revision:integer("published_revision"),bundle_sha256:text("bundle_sha256"),missing_since:integer("missing_since"),connected_at:integer("connected_at").notNull(),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({docIdCheck:check("doc_sync_links_doc_id_ck",sql`length(${t.doc_id}) BETWEEN 1 AND 128`),accountKeyCheck:check("doc_sync_links_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("doc_sync_links_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:check("doc_sync_links_app_id_ck",sql`length(${t.app_id}) BETWEEN 1 AND 128`),rootSegmentsCheck:check("doc_sync_links_root_segments_ck",sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),refCheck:check("doc_sync_links_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),cloudRefCheck:check("doc_sync_links_cloud_ref_ck",sql`length(${t.cloud_ref}) BETWEEN 1 AND 256`),originCheck:check("doc_sync_links_origin_ck",sql`${t.origin} IN ('own', 'received')`),syncStateCheck:check("doc_sync_links_sync_state_ck",sql`${t.sync_state} IN ('ok', 'conflict', 'ended')`),endReasonCheck:check("doc_sync_links_end_reason_ck",sql`${t.end_reason} IS NULL OR ${t.end_reason} IN ('disconnected', 'cloud_deleted')`),endedMatchesReasonCheck:check("doc_sync_links_ended_reason_ck",sql`(${t.sync_state} = 'ended') = (${t.end_reason} IS NOT NULL)`),fileStateCheck:check("doc_sync_links_file_state_ck",sql`${t.file_state} IN ('present', 'missing', 'root_unavailable')`),syncedRevisionCheck:check("doc_sync_links_synced_revision_ck",sql`${t.synced_revision} >= 0`),syncedHashCheck:check("doc_sync_links_synced_hash_ck",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:check("doc_sync_links_connected_at_ck",sql`${t.connected_at} >= 0`),createdAtCheck:check("doc_sync_links_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("doc_sync_links_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),liveRefUnique:uniqueIndex("doc_sync_links_live_ref_uq").on(t.workspace_id,t.app_id,t.ref).where(sql`${t.sync_state} <> 'ended'`),accountStateIdx:index("doc_sync_links_account_state_idx").on(t.account_key,t.sync_state),workspaceAppIdx:index("doc_sync_links_workspace_app_idx").on(t.workspace_id,t.app_id),connectionKindAccountIdx:index("doc_sync_links_connection_account_idx").on(t.account_key,t.connection_kind,t.app_id)}));});var ec=C(()=>{g();sqliteTable("doc_create_dispatches",{dispatch_id:text("dispatch_id").primaryKey().notNull(),request_id:text("request_id").notNull(),account_key:text("account_key").notNull(),source:text("source").$type().notNull(),dispatched_at:integer("dispatched_at").notNull()},t=>({dispatchIdCheck:check("doc_create_dispatches_id_ck",sql`length(${t.dispatch_id}) BETWEEN 1 AND 128`),requestIdCheck:check("doc_create_dispatches_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),accountKeyCheck:check("doc_create_dispatches_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),sourceCheck:check("doc_create_dispatches_source_ck",sql`${t.source} IN ('human', 'app_create', 'app_reattach')`),timestampCheck:check("doc_create_dispatches_time_ck",sql`${t.dispatched_at} >= 0`),accountDispatchedIndex:index("doc_create_dispatches_account_time_idx").on(t.account_key,t.dispatched_at)}));});var Pn,lf,tc=C(()=>{g();Pn=sqliteTable("app_sync_bindings",{binding_id:text("binding_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),app_id:text("app_id").notNull(),root_segments:text("root_segments").notNull(),grant_id:text("grant_id"),grant_generation:integer("grant_generation"),scope_version:text("scope_version"),status:text("status").notNull().default("local_only"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({bindingIdCheck:check("app_sync_bindings_binding_id_ck",sql`length(${t.binding_id}) BETWEEN 1 AND 128`),accountKeyCheck:check("app_sync_bindings_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("app_sync_bindings_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:check("app_sync_bindings_app_id_ck",sql`${t.app_id} = 'workout-log'`),rootSegmentsCheck:check("app_sync_bindings_root_segments_ck",sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),grantGenerationCheck:check("app_sync_bindings_generation_ck",sql`${t.grant_generation} IS NULL OR ${t.grant_generation} >= 1`),statusCheck:check("app_sync_bindings_status_ck",sql`${t.status} IN ('local_only', 'consent_required', 'checking', 'syncing', 'synced', 'partial', 'offline', 'revoked', 'unavailable', 'stopping')`),timestampsCheck:check("app_sync_bindings_timestamps_ck",sql`${t.updated_at} >= ${t.created_at}`),ownerAppUnique:uniqueIndex("app_sync_bindings_owner_app_uq").on(t.account_key,t.app_id)})),sqliteTable("app_sync_creation_jobs",{job_id:text("job_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),ref:text("ref").notNull(),request_id:text("request_id").notNull(),fingerprint:text("fingerprint").notNull(),operation_kind:text("operation_kind").$type().notNull().default("create"),document_id:text("document_id"),status:text("status").notNull().default("waiting"),attempts:integer("attempts").notNull().default(0),next_attempt_at:integer("next_attempt_at").notNull().default(0),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({jobIdCheck:check("app_sync_creation_jobs_job_id_ck",sql`length(${t.job_id}) BETWEEN 1 AND 128`),accountKeyCheck:check("app_sync_creation_jobs_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),generationCheck:check("app_sync_creation_jobs_generation_ck",sql`${t.grant_generation} >= 1`),refCheck:check("app_sync_creation_jobs_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),documentIdCheck:check("app_sync_creation_jobs_document_id_ck",sql`${t.document_id} IS NULL OR length(${t.document_id}) BETWEEN 1 AND 128`),operationKindCheck:check("app_sync_creation_jobs_operation_kind_ck",sql`${t.operation_kind} IN ('create', 'reattach')`),reattachDocumentCheck:check("app_sync_creation_jobs_reattach_document_ck",sql`${t.operation_kind} != 'reattach' OR ${t.document_id} IS NOT NULL`),fingerprintCheck:check("app_sync_creation_jobs_fingerprint_ck",sql`length(${t.fingerprint}) = 71 AND substr(${t.fingerprint}, 1, 7) = 'sha256:' AND substr(${t.fingerprint}, 8) NOT GLOB '*[^0-9a-f]*'`),statusCheck:check("app_sync_creation_jobs_status_ck",sql`${t.status} IN ('waiting', 'processing', 'completed', 'failed', 'conflict', 'blocked', 'invalidated', 'deleted')`),attemptsCheck:check("app_sync_creation_jobs_attempts_ck",sql`${t.attempts} >= 0`),timestampsCheck:check("app_sync_creation_jobs_timestamps_ck",sql`${t.updated_at} >= ${t.created_at}`),bindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[Pn.binding_id]}).onDelete("cascade"),requestIdUnique:uniqueIndex("app_sync_creation_jobs_request_id_uq").on(t.request_id),activeFingerprintUnique: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(sql`${t.status} IN ('waiting', 'processing')`),runnableIndex:index("app_sync_creation_jobs_runnable_idx").on(t.binding_id,t.status,t.next_attempt_at),accountIndex:index("app_sync_creation_jobs_account_idx").on(t.account_key,t.status)})),sqliteTable("app_sync_results",{binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),ref:text("ref").notNull(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),source_fingerprint:text("source_fingerprint"),synced_fingerprint:text("synced_fingerprint"),document_id:text("document_id"),status:text("status").notNull(),error_code:text("error_code"),next_attempt_at:integer("next_attempt_at").notNull().default(0),attempts:integer("attempts").notNull().default(0),updated_at:integer("updated_at").notNull()},t=>({resultAccountCheck:check("app_sync_results_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resultRefCheck:check("app_sync_results_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),resultGenerationCheck:check("app_sync_results_generation_ck",sql`${t.grant_generation} >= 1`),resultStatusCheck:check("app_sync_results_status_ck",sql`${t.status} IN ('waiting', 'processing', 'synced', 'failed', 'conflict', 'blocked', 'excluded', 'deleted')`),resultAttemptsCheck:check("app_sync_results_attempts_ck",sql`${t.attempts} >= 0`),resultBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[Pn.binding_id]}).onDelete("cascade"),resultIdentityUnique:uniqueIndex("app_sync_results_binding_ref_uq").on(t.binding_id,t.ref),resultAccountIndex:index("app_sync_results_account_status_idx").on(t.account_key,t.status)})),sqliteTable("app_sync_control_requests",{request_id:text("request_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),app_id:text("app_id").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),kind:text("kind").notNull(),state:text("state").notNull().default("pending"),grant_id:text("grant_id"),generation:integer("generation"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull(),resolved_at:integer("resolved_at"),resolution:text("resolution"),resolution_id:text("resolution_id")},t=>({requestIdCheck:check("app_sync_control_requests_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),requestAccountCheck:check("app_sync_control_requests_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),requestAppCheck:check("app_sync_control_requests_app_id_ck",sql`${t.app_id} = 'workout-log'`),requestWorkspaceCheck:check("app_sync_control_requests_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),rootFingerprintCheck:check("app_sync_control_requests_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),requestKindCheck:check("app_sync_control_requests_kind_ck",sql`${t.kind} IN ('connect', 'revoke')`),requestStateCheck:check("app_sync_control_requests_state_ck",sql`${t.state} IN ('pending', 'unknown', 'confirmed', 'failed')`),revokeGrantCheck:check("app_sync_control_requests_revoke_grant_ck",sql`${t.kind} != 'revoke' OR (${t.grant_id} IS NOT NULL AND ${t.generation} >= 1)`),requestResolutionCheck:check("app_sync_control_requests_resolution_ck",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:check("app_sync_control_requests_generation_ck",sql`${t.generation} IS NULL OR ${t.generation} >= 1`),timestampsCheck:check("app_sync_control_requests_timestamps_ck",sql`${t.updated_at} >= ${t.created_at}`),bindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[Pn.binding_id]}).onDelete("cascade"),unresolvedPerBinding:uniqueIndex("app_sync_control_requests_one_pending_uq").on(t.binding_id).where(sql`${t.state} IN ('pending', 'unknown')`),accountLookup:index("app_sync_control_requests_account_idx").on(t.account_key,t.app_id,t.state)})),sqliteTable("app_sync_deleted_refs",{account_key:text("account_key").notNull(),app_id:text("app_id").notNull(),ref_sha256:text("ref_sha256").notNull(),created_at:integer("created_at").notNull()},t=>({deletedAccountCheck:check("app_sync_deleted_refs_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),deletedAppCheck:check("app_sync_deleted_refs_app_id_ck",sql`${t.app_id} = 'workout-log'`),deletedHashCheck:check("app_sync_deleted_refs_hash_ck",sql`length(${t.ref_sha256}) = 64 AND ${t.ref_sha256} NOT GLOB '*[^0-9a-f]*'`),deletedIdentityUnique:uniqueIndex("app_sync_deleted_refs_identity_uq").on(t.account_key,t.app_id,t.ref_sha256)})),sqliteTable("app_sync_discovery_checkpoints",{binding_id:text("binding_id").primaryKey().notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),scope_version:text("scope_version").notNull(),last_cycle_started_at:integer("last_cycle_started_at"),cycle_started_at:integer("cycle_started_at"),docs_cursor:text("docs_cursor"),docs_complete:integer("docs_complete").notNull().default(0),deleted_cursor:text("deleted_cursor"),deleted_complete:integer("deleted_complete").notNull().default(0),updated_at:integer("updated_at").notNull()},t=>({checkpointAccountCheck:check("app_sync_discovery_checkpoints_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),checkpointRootCheck:check("app_sync_discovery_checkpoints_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),checkpointGenerationCheck:check("app_sync_discovery_checkpoints_generation_ck",sql`${t.grant_generation} >= 1`),checkpointScopeCheck:check("app_sync_discovery_checkpoints_scope_ck",sql`${t.scope_version} = 'workout-log.records.v1'`),checkpointDocsCompleteCheck:check("app_sync_discovery_checkpoints_docs_complete_ck",sql`${t.docs_complete} IN (0, 1)`),checkpointDeletedCompleteCheck:check("app_sync_discovery_checkpoints_deleted_complete_ck",sql`${t.deleted_complete} IN (0, 1)`),checkpointTimeCheck:check("app_sync_discovery_checkpoints_time_ck",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:foreignKey({columns:[t.binding_id],foreignColumns:[Pn.binding_id]}).onDelete("cascade"),checkpointAccountIndex:index("app_sync_discovery_checkpoints_account_idx").on(t.account_key,t.grant_id,t.grant_generation)})),sqliteTable("app_sync_pending_discoveries",{binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),ref:text("ref").notNull(),doc_id:text("doc_id").notNull(),listed_revision:integer("listed_revision").notNull(),listed_fingerprint:text("listed_fingerprint").notNull(),app_grant_generation:integer("app_grant_generation").notNull(),needs_reattach:integer("needs_reattach").notNull().default(0),needs_reconcile:integer("needs_reconcile").notNull().default(0),status:text("status").notNull().default("waiting"),error_code:text("error_code"),attempts:integer("attempts").notNull().default(0),updated_at:integer("updated_at").notNull()},t=>({pendingAccountCheck:check("app_sync_pending_discoveries_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),pendingRefCheck:check("app_sync_pending_discoveries_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),pendingDocCheck:check("app_sync_pending_discoveries_doc_id_ck",sql`length(${t.doc_id}) BETWEEN 1 AND 128`),pendingRevisionCheck:check("app_sync_pending_discoveries_revision_ck",sql`${t.listed_revision} >= 0`),pendingFingerprintCheck:check("app_sync_pending_discoveries_fingerprint_ck",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:check("app_sync_pending_discoveries_generation_ck",sql`${t.grant_generation} >= 1 AND ${t.app_grant_generation} >= 1`),pendingFlagsCheck:check("app_sync_pending_discoveries_flags_ck",sql`${t.needs_reattach} IN (0, 1) AND ${t.needs_reconcile} IN (0, 1)`),pendingStatusCheck:check("app_sync_pending_discoveries_status_ck",sql`${t.status} IN ('waiting', 'processing', 'failed', 'invalidated')`),pendingAttemptsCheck:check("app_sync_pending_discoveries_attempts_ck",sql`${t.attempts} >= 0 AND ${t.updated_at} >= 0`),pendingBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[Pn.binding_id]}).onDelete("cascade"),pendingIdentityUnique:uniqueIndex("app_sync_pending_discoveries_identity_uq").on(t.binding_id,t.grant_id,t.grant_generation,t.ref),pendingRunnableIdx:index("app_sync_pending_discoveries_runnable_idx").on(t.binding_id,t.grant_id,t.grant_generation,t.status,t.ref)})),lf=sqliteTable("app_sync_conflicts",{conflict_id:text("conflict_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),grant_id:text("grant_id").notNull(),grant_generation:integer("grant_generation").notNull(),scope_version:text("scope_version").notNull(),ref:text("ref").notNull(),doc_id:text("doc_id").notNull(),local_version:text("local_version").notNull(),local_fingerprint:text("local_fingerprint").notNull(),baseline_revision:integer("baseline_revision"),baseline_fingerprint:text("baseline_fingerprint"),remote_revision:integer("remote_revision").notNull(),remote_fingerprint:text("remote_fingerprint").notNull(),needs_reattach:integer("needs_reattach").notNull().default(0),vault_handle:text("vault_handle"),preservation_status:text("preservation_status").notNull().default("pending"),state:text("state").notNull().default("open"),superseded_by:text("superseded_by"),resolution_request_id:text("resolution_request_id"),resolution_choice:text("resolution_choice"),cleanup_pending:integer("cleanup_pending").notNull().default(0),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({conflictIdCheck:check("app_sync_conflicts_id_ck",sql`length(${t.conflict_id}) BETWEEN 1 AND 128`),conflictAccountCheck:check("app_sync_conflicts_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),conflictRootCheck:check("app_sync_conflicts_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),conflictGenerationCheck:check("app_sync_conflicts_generation_ck",sql`${t.grant_generation} >= 1`),conflictScopeCheck:check("app_sync_conflicts_scope_ck",sql`${t.scope_version} = 'workout-log.records.v1'`),conflictRefCheck:check("app_sync_conflicts_ref_ck",sql`length(${t.ref}) BETWEEN 1 AND 256`),conflictDocCheck:check("app_sync_conflicts_doc_id_ck",sql`length(${t.doc_id}) BETWEEN 1 AND 128`),conflictLocalVersionCheck:check("app_sync_conflicts_local_version_ck",sql`length(${t.local_version}) BETWEEN 1 AND 256 AND instr(${t.local_version}, '/') = 0 AND instr(${t.local_version}, char(92)) = 0`),conflictLocalFingerprintCheck:check("app_sync_conflicts_local_fingerprint_ck",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:check("app_sync_conflicts_baseline_ck",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:check("app_sync_conflicts_remote_ck",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:check("app_sync_conflicts_flags_ck",sql`${t.needs_reattach} IN (0, 1) AND ${t.cleanup_pending} IN (0, 1)`),conflictHandleCheck:check("app_sync_conflicts_handle_ck",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:check("app_sync_conflicts_preservation_ck",sql`${t.preservation_status} IN ('pending', 'ready', 'failed')`),conflictStateCheck:check("app_sync_conflicts_state_ck",sql`${t.state} IN ('open', 'resolving', 'superseded', 'resolved', 'kept_both', 'purging')`),conflictArchiveLifecycleCheck:check("app_sync_conflicts_archive_lifecycle_ck",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:check("app_sync_conflicts_superseded_ck",sql`${t.state} != 'superseded' OR ${t.superseded_by} IS NOT NULL`),conflictResolutionCheck:check("app_sync_conflicts_resolution_ck",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:check("app_sync_conflicts_time_ck",sql`${t.updated_at} >= ${t.created_at}`),conflictBindingFk:foreignKey({columns:[t.binding_id],foreignColumns:[Pn.binding_id]}).onDelete("cascade"),conflictIdentityUnique: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:index("app_sync_conflicts_lookup_idx").on(t.account_key,t.binding_id,t.state,t.updated_at)})),sqliteTable("app_sync_conflict_resolutions",{request_id:text("request_id").primaryKey().notNull(),conflict_id:text("conflict_id").notNull(),account_key:text("account_key").notNull(),human_identity:text("human_identity").notNull(),choice:text("choice").notNull(),expected_local_version:text("expected_local_version").notNull(),expected_remote_revision:integer("expected_remote_revision").notNull(),expected_remote_fingerprint:text("expected_remote_fingerprint").notNull(),state:text("state").notNull().default("pending"),error_code:text("error_code"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({resolutionRequestIdCheck:check("app_sync_conflict_resolutions_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),resolutionAccountCheck:check("app_sync_conflict_resolutions_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),resolutionIdentityCheck:check("app_sync_conflict_resolutions_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),resolutionChoiceCheck:check("app_sync_conflict_resolutions_choice_ck",sql`${t.choice} IN ('keep_local', 'use_cloud', 'keep_both')`),resolutionLocalVersionCheck:check("app_sync_conflict_resolutions_local_version_ck",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:check("app_sync_conflict_resolutions_remote_ck",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:check("app_sync_conflict_resolutions_state_ck",sql`${t.state} IN ('pending', 'unknown', 'resolved', 'stale', 'failed')`),resolutionTimeCheck:check("app_sync_conflict_resolutions_time_ck",sql`${t.updated_at} >= ${t.created_at}`),resolutionConflictFk:foreignKey({columns:[t.conflict_id],foreignColumns:[lf.conflict_id]}).onDelete("cascade"),resolutionConflictIdx:index("app_sync_conflict_resolutions_conflict_idx").on(t.conflict_id,t.created_at),resolutionActiveUnique:uniqueIndex("app_sync_conflict_resolutions_one_active_uq").on(t.conflict_id).where(sql`${t.state} IN ('pending', 'unknown')`)})),sqliteTable("app_sync_account_data_purges",{request_id:text("request_id").primaryKey().notNull(),binding_id:text("binding_id").notNull(),account_key:text("account_key").notNull(),workspace_id:text("workspace_id").notNull(),root_fingerprint:text("root_fingerprint").notNull(),human_identity:text("human_identity").notNull(),state:text("state").notNull().default("pending"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({purgeRequestIdCheck:check("app_sync_account_data_purges_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),purgeAccountCheck:check("app_sync_account_data_purges_account_key_ck",sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),purgeWorkspaceCheck:check("app_sync_account_data_purges_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),purgeRootCheck:check("app_sync_account_data_purges_root_fingerprint_ck",sql`length(${t.root_fingerprint}) = 64 AND ${t.root_fingerprint} NOT GLOB '*[^0-9a-f]*'`),purgeHumanIdentityCheck:check("app_sync_account_data_purges_human_identity_ck",sql`length(${t.human_identity}) = 64 AND ${t.human_identity} NOT GLOB '*[^0-9a-f]*'`),purgeStateCheck:check("app_sync_account_data_purges_state_ck",sql`${t.state} IN ('pending', 'complete')`),purgeTimeCheck:check("app_sync_account_data_purges_time_ck",sql`${t.updated_at} >= ${t.created_at}`),purgeAccountIndex:index("app_sync_account_data_purges_account_idx").on(t.account_key,t.state,t.updated_at)}));});var nc=C(()=>{g();sqliteTable("route_states",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),config_revision:text("config_revision").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),updated_at:text("updated_at").notNull()},t=>({pk_route_state_workspace:primaryKey({columns:[t.workspace_key,t.route_id]})})),sqliteTable("route_sticky_bindings",{workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),thread_id:text("thread_id").notNull(),candidate_id:text("candidate_id").notNull(),updated_at:text("updated_at").notNull()},t=>({uniq_route_sticky_thread:uniqueIndex("uniq_route_sticky_thread").on(t.workspace_key,t.route_id,t.thread_id),idx_route_sticky_candidate:index("idx_route_sticky_candidate").on(t.workspace_key,t.route_id,t.candidate_id)})),sqliteTable("route_decisions",{id:text("id").primaryKey(),workspace_key:text("workspace_key").notNull().default("legacy"),route_id:text("route_id").notNull(),task_id:text("task_id").notNull(),config_revision:text("config_revision").notNull(),candidate_id:text("candidate_id").notNull(),provider:text("provider").notNull(),model:text("model").notNull(),reason:text("reason").notNull(),eligible_ids:text("eligible_ids").notNull(),blocked_causes:text("blocked_causes").notNull(),link_errors:text("link_errors").notNull(),created_at:text("created_at").notNull()},t=>({uniq_route_task_decision:uniqueIndex("uniq_route_task_decision").on(t.workspace_key,t.route_id,t.task_id),idx_route_decisions_workspace_created:index("idx_route_decisions_workspace_created").on(t.workspace_key,t.route_id,t.created_at)})),sqliteTable("route_quota_observations",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),model:text("model"),status:text("status",{enum:["ok","blocked"]}).notNull(),source:text("source").notNull(),reset_at:text("reset_at"),observed_at:text("observed_at").notNull()},t=>({uniq_route_quota_observation:uniqueIndex("uniq_route_quota_observation").on(t.provider,t.account_ref,t.model,t.source),idx_route_quota_observations_reset:index("idx_route_quota_observations_reset").on(t.reset_at)}));});var jt=C(()=>{g();ro();vn();od();id();bn();cd();ld();pd();fd();hd();kd();yd();Ed();Rd();Id();Nd();Od();bd();Cd();Dd();Md();Ds();Fd();Gd();jd();Vd();Xd();Yd();Qd();Zd();ec();tc();nc();});function yr(t){return typeof t=="string"&&zt.includes(t)}function rc(t){if(!t||!t.includes("workflow"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let o=n.workflow;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let s=o.exec_id;if(typeof s=="string"&&s!=="")return s}return null}var zt,mo=C(()=>{g();zt=["workflow_card","workflow_ui_instance","workflow_run"];});var Ln,Fs,oc,Ws=C(()=>{g();Ln={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5-5":{input:4,cachedInput:.2,output:20},"claude-opus-5-5-medium":{input:4,cachedInput:.2,output:20},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5-5":{input:2,cachedInput:.1,output:10},"claude-sonnet-5-5-medium":{input:2,cachedInput:.1,output:10},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-5-5":{input:.1,cachedInput:.01,output:.5},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-6.1-sol":{input:2,cachedInput:.1,output:10},"gpt-6.1-terra":{input:1,cachedInput:.05,output:5},"gpt-6-sol":{input:2,cachedInput:.2,output:10},"gpt-6-luna":{input:.1,cachedInput:.01,output:.5},"gpt-5.6-sol":{input:4,cachedInput:.4,output:20},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.3-flash":{input:.15,cachedInput:.03,output:.5},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"deepseek-v4.1-flash":{input:.3,cachedInput:.006,output:1.2},"qwen3.8-flash":{input:.164,cachedInput:.018,output:.514},"minimax-m3":{input:.3,cachedInput:.06,output:1.2},"kimi-k2.7-code":{input:.95,cachedInput:.19,output:4},"gemini-3.8-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-4-argon":{input:4,cachedInput:.2,output:20},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.7":{input:2,cachedInput:.5,output:6},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},Fs=new Set(["gpt-5.3-codex-spark","claude-opus-4-6-thinking","gpt-oss-120b","glm-5.3-flash-free","deepseek-v4.1-flash-free"]),oc=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-opus-4-6","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7","claude-opus-4-7[1m]","claude-opus-4-8","claude-opus-4-8[1m]","claude-opus-5","claude-opus-5-5","claude-opus-5-5-medium","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","claude-sonnet-5-5-medium","deepseek-v4.1-flash","deepseek-v4.1-flash-free","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","gemini-3.8-flash","gemini-4-argon","glm-5.1","glm-5.2","glm-5.3-flash","glm-5.3-flash-free","gpt-4.1","gpt-4o","gpt-5-mini","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-6-luna","gpt-6-sol","gpt-6.1-sol","gpt-6.1-terra","gpt-oss-120b","grok-4.5","grok-4.6","grok-4.7","kimi-k2.7-code","minimax-m3","qwen3.8-flash"]);});function Gs(t){let e=t.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let n=e.lastIndexOf("/");return n>=0&&(e=e.slice(n+1)),e=e.replace(/-\d{8}$/,""),e}function gf(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Tr;let e=Gs(t),n=ff[e];if(n)return ko[n]??Ln[n]??Tr;if(ko[e])return ko[e];if(Ln[e])return Ln[e];if(Fs.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Tr;if(oc.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Tr;let r={...Ln,...ko};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Tr}function hf(t,e,n,r=0,o){let s=gf(n),i=Math.min(r,t),d=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,l=e*s.output/1e6;return d+u+l}function sc(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:hf(e??0,n??0,o,r??0)}var ff,Tr,ko,yo=C(()=>{g();Ws();Ws();ff={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},Tr={input:0,cachedInput:0,output:0},ko={};});function cc(t){if(!t||!t.includes("schedule_id"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.trigger;if(typeof r!="string"||!mf.includes(r))return null;let o=n.schedule_id;return typeof o=="string"&&o!==""?o:null}var mf,uc=C(()=>{g();mf=["cron","cron_manual"];});function zs(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function lc(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function To(t){return Number.isSafeInteger(t)&&t>0}function Rf(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function Sf(t,e,n){let r=n==="win32"?t.toLowerCase():t,o=n==="win32"?e.toLowerCase():e;if(!o.trim())return false;if(o==="agy"){let s=Rf(t).split(/[\\/]/).pop()??"",i=n==="win32"?s.toLowerCase():s;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(o)}function If(t,e,n){return e.some(r=>Sf(t,r,n))}function Af(t,e){try{let n=spawnSync(t,e,{encoding:"utf8",timeout:js,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:zs(n)}}}function Nf(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:zs(u)});return}let o="",s="",i=false,c,d=setTimeout(()=>{try{r.kill();}catch{}c({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${js}ms`)});},js);c=u=>{i||(i=true,clearTimeout(d),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{o+=String(u);}),r.stderr?.on("data",u=>{s+=String(u);}),r.once("error",u=>{c({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{c({status:u,stdout:o,stderr:s});});})}async function Ks(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Nf(t,e)}function Of(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function vf(){return new Promise(t=>{setImmediate(t);})}function Kt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return lc(n)==="ESRCH"?"not_found":lc(n)==="EPERM"?"alive":"unknown"}}function bf(t,e){let n=Kt(-t,e),r=Kt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function _c(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??wf),i=Date.now()+o,c,d=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(l=>{c=setTimeout(l,o);});u.then(()=>{d=true;});try{for(await vf();;){let l=bf(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([u,Of(Math.min(s,p))]);}}finally{c!==void 0&&clearTimeout(c);}}async function pc(t,e,n,r,o){let s=await _c(t,e,o.hardConfirmMs??Ef,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function fc(t,e,n={}){if(!To(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],i;try{i=await Ks(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let c=i.stdout.trim();return c?If(c,e,r)?"owned":"not_owned":"not_found"}function Pf(t){let e=Cf.exec(t.trim());if(!e)return;let[,n="0",r="0",o="0",s="0"]=e;return ((Number(n)*24+Number(r))*60+Number(o))*60+Number(s)}function Lf(t){let e=t.trim(),n=Df.exec(e);if(n){let[,o,s,i,c,d,u,l,p]=n;return Date.UTC(Number(o),Number(s)-1,Number(i),Number(c),Number(d),Number(u),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function gc(t,e){return e==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(t),"-o","pgid=","-o","etime=","-o","stat="]}}function hc(t,e,n){if(t.error)return {status:"unknown"};let r=t.stdout.trim();if(!r)return t.status===0||t.status===1?{status:"not_found"}:{status:"unknown"};if(t.status!==0)return {status:"unknown"};if(e==="win32"){let i=Lf(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let o=xf.exec(r),s=o?Pf(o[2]):void 0;return !o||s===void 0?{status:"unknown"}:o[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-s*1e3,groupId:Number(o[1])}}function mc(t,e={}){if(!To(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=gc(t,n),s=e.runCommand??Af,i;try{i=s(r,o);}catch{return {status:"unknown"}}return hc(i,n,Date.now())}async function kc(t,e={}){if(!To(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:o}=gc(t,n),s;try{s=await Ks(r,o,e);}catch{return {status:"unknown"}}return hc(s,n,Date.now())}async function Vt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=_=>({status:"failed",pid:t,method:r,error:_});if(!To(t))return o("Invalid process ID");let s=e.kill??process.kill,i=Kt(t,s);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let _;try{_=await Ks("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){_={status:null,stdout:"",stderr:"",error:zs(m)};}let h=Kt(t,s);return h==="not_found"?_.status===0&&!_.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let c,d=e.signal??"SIGKILL";try{s(-t,d);}catch(_){c=_;}if(d==="SIGKILL")return pc(t,s,c,r,e);if(await _c(t,s,e.graceMs??Tf,e)==="not_found")return c?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{s(-t,"SIGKILL");}catch(_){l=_;}let p=await pc(t,s,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?c?p:{status:"terminated",pid:t,method:r}:o(p.error??"Process termination failed")}var js,Jt,Tf,wf,Ef,wo,Cf,xf,Df,Eo=C(()=>{g();js=3e3,Jt="SIGINT",Tf=2e3,wf=25,Ef=100;wo=3e3,Cf=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,xf=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,Df=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function Rc(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function wc(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>Rc(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Sc(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Ec(t){return {taskId:t.id,source:Sc(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Bf(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var Ro,Ic=C(()=>{g();vt();Bt();Ft();Ot();jt();Ro=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?sn(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new f("NOT_FOUND","Database not found");let r=U(n);if(e)try{Le(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>Rc(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new f("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let c=this.requireStateRowInTransaction(i,e),d=Sc(c);if(d==="blob"){let _=wc(e,c.logs);if(i.update(a).set({logs:JSON.stringify([..._,...r]),log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:c.last_log_seq}}let u=c.last_log_seq+1,l=c.last_log_seq+r.length;if(i.insert(mt).values(r.map((_,h)=>({task_id:e,seq:u+h,timestamp:_.timestamp,level:_.level,message:_.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:c.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Ec(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Bf(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=Ec(s);if(i.source==="blob"){let l=wc(e,s.logs).map((p,_)=>({...p,seq:_+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let c=o.select({seq:mt.seq,timestamp:mt.timestamp,level:mt.level,message:mt.message}).from(mt).where(eq(mt.task_id,e)).orderBy(n===void 0?asc(mt.seq):desc(mt.seq)),u=(n===void 0?c.all():c.limit(n).all()).map(({seq:l,timestamp:p,level:_,message:h})=>({seq:l,timestamp:p,level:_,message:h}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var zf,So,Nc=C(()=>{g();vt();Bt();Ft();Ot();jt();zf=50,So=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=`${e.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let e=this.resolveDbPath(),n=U(e);try{return Le(n.db,e),n}catch(r){throw n.close(),r}}recordAccepted(e){if(e.actorKind!=="human"||!e.workspaceId||!e.actorId||!e.agentId)return false;let n;try{n=this.openHandle();let r=e.acceptedAt??new Date().toISOString();return n.db.insert(Ge).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[Ge.workspace_id,Ge.actor_id,Ge.agent_id],set:{last_accepted_at:sql`MAX(${Ge.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(e,n){let r;try{return r=this.openHandle(),r.db.select({agentId:Ge.agent_id,lastAcceptedAt:Ge.last_accepted_at}).from(Ge).where(and(eq(Ge.workspace_id,e),eq(Ge.actor_id,n))).orderBy(desc(Ge.last_accepted_at),asc(Ge.agent_id)).limit(zf).all()}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});var Oc=C(()=>{g();});var Kf,G,Xt=C(()=>{g();Kf=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=Kf.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 hn,Js=C(()=>{g();Xt();hn=class extends G{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Io(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 ${xe}]`),e=Vf(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${xe}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,xe),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,xe),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,xe),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,xe),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,xe),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,xe),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,xe),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,xe),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,xe),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${xe}${r}${xe}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${xe}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,vc),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,vc),e=e.replace(/[\r\n]{3,}/g,`
|
|
46
|
+
|
|
47
|
+
`).trim(),Jf(e,1024)||void 0}function Jf(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 Vf(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=Xf(t,s),c=i>=0?i:t.indexOf(`
|
|
48
|
+
`,s)>=0?t.indexOf(`
|
|
49
|
+
`,s):t.length;n+=t.slice(r,o.index),n+=`[HTTP BODY ${xe}]`,r=c;}return n+t.slice(r)}function Xf(t,e){let n=t[e];if(n==='"'||n==="'")return Yf(t,e,n);if(n!=="{"&&n!=="[")return -1;let r=[],o,s=false;for(let i=e;i<t.length;i+=1){let c=t[i];if(o){s?s=false:c==="\\"?s=true:c===o&&(o=void 0);continue}if(c==='"'||c==="'"){o=c;continue}if(c==="{"||c==="["){r.push(c);continue}if(c!=="}"&&c!=="]")continue;let d=r.pop();if(c==="}"&&d!=="{"||c==="]"&&d!=="[")return -1;if(r.length===0)return i+1}return -1}function Yf(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 xe,vc,Vs=C(()=>{g();xe="[REDACTED]",vc="[PATH]";});function Ys(t){if(!Ao(t)||t.type!=="item.started"||!Cc(t)||!bc(t))return false;let e=t.item;return !Ao(e)||!Cc(e)||!bc(e)||!Xs(e.id)?false:e.type==="web_search"?e.query===""&&Ao(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=>Ao(n)&&Xs(n.path)&&Xs(n.kind)):false}function Ao(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Xs(t){return typeof t=="string"&&t.trim().length>0}function bc(t){return !xc(t,"status")||t.status==="in_progress"}function Cc(t){for(let e of ["error","errors","isError","is_error"])if(xc(t,e))return false;return true}var Qs=C(()=>{g();});function Mn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $n(t){return typeof t=="string"&&t.trim().length>0}function Zs(t){return typeof t=="string"?t.trim().length>0:Mn(t)?$n(t.code)||$n(t.message)||$n(t.error)||$n(t.reason):false}function Er(t){let e;try{e=JSON.parse(t);}catch{return}if(Mn(e))switch(e.event){case "init":return Mn(e.init)?{kind:"init",envelope:e,init:e.init}:void 0;case "step_update":{if(!Mn(e.step_update))return;let n=e.step_update;return !$n(n.conversation_id)||!Number.isSafeInteger(n.step_index)||n.state!=="ACTIVE"&&n.state!=="DONE"&&!(n.state==="ERROR"&&n.step_type==="tool")||!$n(n.step_type)?void 0:{kind:"step_update",envelope:e,step:n}}case "result":return Mn(e.result)?{kind:"result",envelope:e,result:e.result}:void 0;case "AGY_ERROR":{let n=Zs(e)?e:e.error;return Zs(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"||Zs(e.error)||Mn(e.usage))?{kind:"legacy_result",envelope:e,result:e}:void 0}}function Dc(t){return Er(t)!==void 0}function Rr(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.trim())continue;let r=Er(n);r&&e.push(r);}return e}var ei=C(()=>{g();});function Qf(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?ig[e]:void 0;return s?s(r,o):o?Object.values(Lc).some(i=>i(r,o)):false}function Rt(t,e){let n=t.split(`
|
|
50
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>Qf(r,e))}function $e(t){return typeof t=="object"&&t!==null}function Pc(t,e){if(e==="assistant"||e==="user"){let n=t.message;return $e(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||$e(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?$e(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function Zf(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Pc(t,e)}function eg(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||$e(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 $e(n)&&typeof n.type=="string"}return false}function tg(t,e){if(e==="step_start"||e==="step_finish")return typeof t.stepID=="string"||typeof t.sessionID=="string"||$e(t.part);if(e==="text"||e==="tool_use")return $e(t.part);if(e==="error"){let n=t.error;return $e(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function ng(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||$e(t.part)||e==="result"&&typeof t.result=="string")}function rg(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?$e(t.data):e==="result"?typeof t.result=="string":false}function og(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 sg(t,e){return e==="available_commands"?$e(t.tools)||$e(t.commands):e==="usage"?$e(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||$e(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var Lc,ig,Hn=C(()=>{g();Qs();ei();Lc={claude:Pc,codex:eg,opencode:tg,copilot:rg,gemini:og},ig={...Lc,claude:Zf,opencode:ng,grok:sg,antigravity:t=>Dc(JSON.stringify(t))};});function St(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function It(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 Un=C(()=>{g();});function cg(t){let e=ug(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>pg(s.value)),r=lg(e);return {result:n.length===1&&n[0].index===r?_g(n[0].line.value):null,resultPreview:hg(e,n),hasReservedLine:n.length>0}}function st(t,e){let n=cg(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function ug(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 lg(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function pg(t){return t.trimStart().startsWith(ag)}function _g(t){let e=t.trim();if(!e.startsWith(Mc)||!e.endsWith("]]"))return null;let n=e.slice(Mc.length,-2);if(!n)return null;try{return fg(JSON.parse(n))}catch{return null}}function fg(t){return gg(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function gg(t){if(!mg(t)||Object.keys(t).some(r=>!dg.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?$c(t.taskId)&&$c(t.agentId):t.isError===true}function hg(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 $c(t){return typeof t=="string"&&t.trim().length>0}function mg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Mc,ag,dg,qn=C(()=>{g();Mc="[[crewx:delegation-result ",ag="[[crewx:delegation-result",dg=new Set(["schema","taskId","agentId","isError"]);});function it(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 Bn=C(()=>{g();});var Hc,No,ti,Oo=C(()=>{g();Hc=["none","minimal","low","medium","high","xhigh","max","ultra"],No={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"]},ti={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(ti).map(([t,e])=>[t,e.models]));});function ni(t){return yg[t]??t}function wg(t){return Tg.get(t)??t}function ri(t){if(!t)return {};let e=Rg.get(t);return e?{...e}:{model:t}}function oi(t,e){return t==="antigravity"||t==="cli/antigravity"?ri(e):e===void 0?{}:{model:wg(e)}}var kg,yg,Tg,Eg,Rg,Sr=C(()=>{g();kg=[{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]"}],yg={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Tg=new Map(kg.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Eg=[{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"}],Rg=new Map(Eg.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Ig(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Pt(t){return Ir(t).models}function Ir(t){let e=Sg[t],n=ti[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??Ig()}function Fn(t,e){let n=Ir(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=oi(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function si(t){return Ir(t).modelOverrides}function Uc(){return Pt("claude")}function qc(){return Pt("codex")}function Bc(){return Pt("copilot")}function Fc(){return Pt("antigravity")}var Sg,Yt=C(()=>{g();Oo();yo();Sr();Sg={};});function Wc(t){return Og[t]??t}var Og,Gc=C(()=>{g();Yt();Sr();Og={auto:"default"};});function vo(t,e){return (No[t]??[]).includes(e)}function Qt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return vg.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function jc(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 zc(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 Kc(t){return !t||!vo("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Jc(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Wc(t);return e.has(n)?["--permission-mode",n]:[]}function Vc(t){return t?vo("claude",t)?["--effort",t]:[]:[]}function Xc(t){return t==="default"?[]:t&&bg.has(t)?["--permission-mode",t]:[]}function Yc(t){return t===true?["--always-approve"]:[]}function Qc(t,e=n=>console.warn(n)){return t===void 0?[]:t==="workspace"||t==="read-only"||t==="off"?["--sandbox",t]:(e(`[grok] Invalid sandbox value ${JSON.stringify(t)}; using workspace.`),["--sandbox","workspace"])}function Zc(t){return t?vo("grok",t)?["--effort",t]:[]:[]}function eu(t){if(!t)return [];switch(ni(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function tu(t){return t?vo("antigravity",t)?["--effort",t]:[]:[]}var vg,bg,Ar=C(()=>{g();Gc();Sr();Oo();vg=new Set(Hc);bg=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function Cg(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 xg(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,c="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:c??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:d}}function Dg(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 nu(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 c=i.message,d=c?.id,u=c?.usage;if(typeof d!="string"||!u)continue;let l=Number(u.input_tokens??0),p=Number(u.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let _=c?.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 Wn(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=Dg(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=Cg(o)??xg(o);i&&(e=i);}catch{}return n||(e??void 0)}var Nr=C(()=>{g();});function at(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 mn=C(()=>{g();});var bo,ru=C(()=>{g();bo=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function su(t){return t==="all"?[...ou,...Pg]:ou}function iu(t){return su(t).map(e=>`Bash(${e} *)`)}function au(t){return su(t).map(e=>`command(${e})`)}var ou,Pg,ii=C(()=>{g();ou=["crewx memory","crewx search","crewx doc","crewx notify"],Pg=["crewx q","crewx query","crewx x","crewx execute","crewx cron","crewx wbs","crewx wi","crewx workflow","crewx app","crewx skill"];});function du(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 cu(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 Gn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function fu(t){let e=Gn(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=qg(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(Bg(n))return `Claude rate limit: ${n}`}}function $g(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=Gn(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 Hg(t){let e=Gn(t);if(e?.type!=="rate_limit_event")return;let n=Gn(Gn(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=uu(n.five_hour),o=uu(n.seven_day);if(!(!r&&!o))return {...r?{five_hour:r}:{},...o?{seven_day:o}:{}}}function uu(t){let e=Gn(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function lu(t){if(t?.is_error===true)return Io(t.result)}function Ug(t){let e=fu(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 qg(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
7
59
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
`)
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
60
|
+
`):""}function Bg(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function _u(t){return t.replace(/\s+/g," ").trim()}function Fg(t,e){let n=t?.description;if(typeof n!="string")return;let r=_u(n);if(!r||r===_u(e))return;if(r.length<=pu)return r;let o=r.slice(0,pu-1);return /[\uD800-\uDBFF]$/.test(o)&&(o=o.slice(0,-1)),`${o}\u2026`}function Wg(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=it(s);if(r==="Bash"&&St(i))return It(t,i,o);let c=Fg(s,i);return {timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i,...c?{toolTitle:c}:{}}}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(c=>c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
|
|
61
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...st(i,r)}}return null}var Lg,Mg,Co,pu,ai=C(()=>{g();Js();Xt();Vs();Hn();Un();qn();Bn();Ar();Yt();Nr();mn();ru();ii();Lg=new Set(["tool_progress"]),Mg="cli/claude";Co={command:"claude",meta:{displayName:"Claude",models:Uc(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Qt(e.model),s=e.effort??o,i=Jc(e.mode),c=Vc(s),d=r?["--model",r]:[],u=e.mode==="bypassPermissions"?[]:["--allowedTools",...iu(e.builtinAllow)],l=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let _=[...e.additionalArgs];return _.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...l,...i,...c,...d,...u,..._],stdinMessage:t,env:bo}:{args:["--output-format","stream-json","--verbose",...l,...i,...c,...d,...u,..._],stdinMessage:t,env:bo}}return {args:["-p","--output-format","stream-json","--verbose",...l,...i,...c,...d,...u],stdinMessage:t,env:bo}},extractText(t){let e=cu(t);if(e?.is_error===true){let o=Co.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(lu(e)??`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,Mg,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=du(t);if(n)return n;let r=t.trim();return Rt(r,"claude")?"":r},extractPartialText(t){return du(t)},extractFailure(t){try{let e=JSON.parse(t),n=fu(e);if(n)return new hn(n)}catch{}return null},interpretExit(t,e,n){let r=$g(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=lu(cu(n??""));return o?new G(o,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return Hg(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,c=o.modelUsage,d=c?Object.keys(c)[0]??null:null;return {usage:i,model:d}}}catch{}let n=nu(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=at(n,e??new Date().toISOString()),s=Ug(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];if(r!=="assistant"&&r!=="user")return [];let c=n.message?.content;if(!Array.isArray(c))return [];let d=[];for(let u of c){let l=Wg(o,u);l&&d.push(l);}return d},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Lg.has(r):!1}catch{return false}}};pu=200;});function gu(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 Gg,di,ci=C(()=>{g();Hn();Nr();Un();Bn();qn();Yt();Oo();mn();Gg=new Set(["interactive","plan","autopilot"]);di={command:"copilot",meta:{displayName:"Copilot",models:Bc()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&Gg.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(No.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=gu(t);if(e)return e;let n=t.trim();return Rt(n,"copilot")?"":n},extractPartialText(t){return gu(t)},parseResultMeta(t){let e=Wn(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=at(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let c=String(o.toolName||""),d=o.arguments,u=it(d);return (c==="bash"||c==="Bash")&&St(u)?[It(s,u,i)]:[{timestamp:s,type:"tool_use",toolName:c,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let c=o.error;if(c)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...st(String(c.message||""),true)}];let d=o.result,u=String(d?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...st(u,false)}]}if(r==="assistant.message"){let c=String(o.content||"");return c?[{timestamp:s,type:"text",content:c}]:[]}return []}};});function Kg(t){let e=[],n=0,r=false,o=false,s=0;for(let c=0;c<t.length;c++){let d=t[c];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let u=t.slice(s,c+1).trim();u&&e.push(u),s=c+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function Jg(t){return t[0]==="exec"?t.slice(1):t}function hu(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 Zt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ku(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Zt(t.error)}function yu(t){let e=Zt(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 Vg(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Zt(n)&&ku(n))return yu(n)}}function mu(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 d=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,u=o.get(s)??[];return u.push(d),o.set(s,u),d}let i=o.get(s),c=i?.pop();return i?.length||o.delete(s),c}function Xg(t,e,n){let r=e.type;if(r==="command_execution"){let o=String(e.command||"");return St(o)?[It(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:it(e.arguments),...n?{toolUseId:n}:{}}]:[]}function Yg(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=Qg(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",...st(o,s),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let o=Zt(e.result)?e.result:void 0,i=(Array.isArray(o?.content)?o.content:[]).filter(d=>Zt(d)&&d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
|
|
65
|
+
`),c=typeof e.error=="string"?e.error:Zt(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||c,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=it(s);return o==="Bash"&&St(i)?It(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",...st(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&&!(Zt(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(c=>String(c.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 Qg(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=it(o);return r==="Bash"&&St(s)?It(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var jg,zg,ui,li=C(()=>{g();Xt();Hn();Nr();Un();Bn();Qs();qn();Ar();Yt();mn();jg=new Set(["turn.started","turn.completed","item.updated"]),zg="cli/codex";ui={command:"codex",meta:{displayName:"Codex",models:qc(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Qt(e.model),s=e.effort??o,i=e.resumeSessionId?zc(e.mode):jc(e.mode),c=Kc(s),d=r?["-m",r]:[],u=Jg(e.additionalArgs??[]),p=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...i,...c,...d,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...i,...c,...d,...u],stdinMessage:t}},extractText(t){let e=Vg(t);if(e)throw new G(e,zg);let n=hu(t);if(n)return n;let r=t.trim();return Rt(r,"codex")?"":r},extractPartialText(t){return hu(t)},parseResultMeta(t){let e=Wn(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=Kg(t),s.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,c]of s.entries()){let d;try{d=JSON.parse(c);}catch{continue}if(!Zt(d))continue;let u=d.type;if(!u)continue;let l=at(d,r);if(ku(d)){let _=yu(d);o.push({timestamp:l,type:"error",content:_,errorMessage:_});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Ys(d))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(u==="item.started"){o.push(...Xg(l,p,mu(p,u,n,i)));continue}if(u==="item.completed"){let _=Yg(l,p,mu(p,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?jg.has(r):!1}catch{return false}}};});function Ye(t,e=240){if(typeof t!="string")return;let n=t.split(/\r?\n/).map(r=>r.trim()).find(r=>r&&!/^at\s+/.test(r));if(n)return n.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").replace(/(^|[\s"'(=])((?:[A-Za-z]:[\\/]|\/)(?:[^\s"'`()\[\]{}]+[\\/])*[^\s"'`()\[\]{}]+)/g,"$1[path]").slice(0,e).trim()}function Or(t){let e=Ye(t);if(e)return Ye(e.replace(/^Upstream request failed:\s*/i,""),200)}var Tu=C(()=>{g();});var wu=C(()=>{g();});function eh(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 th(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),Eu),n.unref();try{execFile("chcp.com",[],{encoding:"ascii",timeout:Eu,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(eh(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function nh(){return process.platform!=="win32"?Promise.resolve(null):(xo||(xo=th(),xo.then(t=>{},()=>{})),xo)}function rh(){process.platform==="win32"&&nh();}var Eu,xo,Su=C(()=>{g();Eu=1e3;rh();});function sh(t,e){let n={};for(let[r,o]of Object.entries(t))o!==void 0&&(e.includes(r)||(n[r]=o));return n}function pi(t){return sh(t,oh)}var oh,_i=C(()=>{g();oh=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];});function Do(){if(process.env.CREWX_HOME){let t=Oe.resolve(process.env.CREWX_HOME);try{return Au.realpathSync(t)}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return t;throw e}}return process.platform!=="win32"&&process.env.XDG_CONFIG_HOME?Oe.join(process.env.XDG_CONFIG_HOME,"crewx"):Oe.join(Va.homedir(),".crewx")}var Nu=C(()=>{g();});function br(t=Do()){let e=join(t,"opencode-xdg");return {XDG_DATA_HOME:join(e,"data"),XDG_STATE_HOME:join(e,"state")}}function Cr(t=Do()){return join(br(t).XDG_DATA_HOME,"opencode")}async function ch(){return (await import('better-sqlite3')).default}function uh(t){return join(t,"opencode.db")}function lh(t){let e=t??process.env.XDG_DATA_HOME??join(homedir(),".local","share");return join(resolve(e),"opencode","opencode.db")}function vu(t,e){return !!t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)}function ph(t){let e;try{e=typeof t=="string"?JSON.parse(t):t;}catch{return false}if(!e||typeof e!="object"||Array.isArray(e))return false;let n=e;return n.type==="key"&&typeof n.key=="string"&&!("refresh"in n)&&!("refresh_token"in n)&&!("expires"in n)&&!("expires_at"in n)&&!("expires_in"in n)}function _h(t,e){if(!existsSync(e))return [];let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),vu(n,"credential")?n.prepare(`
|
|
66
|
+
SELECT id, integration_id, label, value, connector_id, method_id, active, time_created, time_updated
|
|
67
|
+
FROM credential
|
|
68
|
+
`).all().filter(o=>o.integration_id!==null&&ph(o.value)):[]}catch{return []}finally{n?.close();}}function Ou(t,e){if(!existsSync(e))return false;let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),vu(n,"credential")}catch{return false}finally{n?.close();}}function fh(t){return new Promise((e,n)=>{execFile("opencode",["auth","list","--standalone"],{timeout:15e3,maxBuffer:1024*1024,encoding:"utf8",env:{...pi(process.env),...t}},r=>{r?n(r):e();});})}function gh(t,e,n){let r=new t(e,{fileMustExist:true});try{let o=r.prepare(`
|
|
69
|
+
INSERT INTO credential (
|
|
70
|
+
id, integration_id, label, value, connector_id, method_id, active, time_created, time_updated
|
|
71
|
+
) VALUES (
|
|
72
|
+
@id, @integration_id, @label, @value, @connector_id, @method_id, @active, @time_created, @time_updated
|
|
73
|
+
)
|
|
74
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
75
|
+
integration_id = excluded.integration_id,
|
|
76
|
+
label = excluded.label,
|
|
77
|
+
value = excluded.value,
|
|
78
|
+
connector_id = excluded.connector_id,
|
|
79
|
+
method_id = excluded.method_id,
|
|
80
|
+
active = excluded.active,
|
|
81
|
+
time_created = excluded.time_created,
|
|
82
|
+
time_updated = excluded.time_updated
|
|
83
|
+
`);r.transaction(i=>{for(let c of i)o.run(c);})(n);}finally{r.close();}}function hh(t){if(!t)return [];let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="-s"||r==="--session"){let o=t[n+1],s=o!==void 0&&!o.startsWith("-");e.push({sessionId:s?o:void 0}),s&&(n+=1);continue}(r.startsWith("--session=")||r.startsWith("-s="))&&e.push({sessionId:r.slice(r.indexOf("=")+1)||void 0});}return e}function mh(t){if(!t)return;let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="-s"||r==="--session"){t[n+1]!==void 0&&!t[n+1].startsWith("-")&&(n+=1);continue}r.startsWith("--session=")||r.startsWith("-s=")||e.push(r);}return e}function Po(t){let e=mh(t.additionalArgs);return {...t,...e===void 0?{}:{additionalArgs:e},resumeSessionId:void 0}}function kh(t,e){try{return !!t.prepare("SELECT id FROM session_v2 WHERE id = ?").get(e)}catch(n){if(n instanceof Error&&/no such table: session_v2/i.test(n.message))return false;throw n}}function yh(t,e,n){let r=new t(e,{readonly:true,fileMustExist:true});try{return kh(r,n)}finally{r.close();}}async function gi(t,e={}){let n;try{n=await(e.loadSqlite??ch)();}catch{throw new G("OpenCode isolation requires the optional better-sqlite3 dependency. Install it and retry.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}let r=e.crewxHome??Do(),o=br(r),s=Cr(r),i=uh(s),c=lh(e.userDataHome),d=_h(n,c);if(d.length>0){if(!Ou(n,i))try{await(e.initializeDatabase??fh)(o);}catch{throw new G("Could not initialize the isolated OpenCode credential database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}if(!Ou(n,i))throw new G("The isolated OpenCode credential database is unavailable.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"});try{gh(n,i,d);}catch{throw new G("Could not copy API-key credentials into the isolated OpenCode database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}let u=hh(t.additionalArgs),l=u.map(_=>_.sessionId),p=u.length>0?l[l.length-1]:t.resumeSessionId;if(!p)return u.length>0?Po(t):t;if(l.some(_=>_!==p)||!existsSync(i))return Po(t);try{return yh(n,i,p)?{...t,resumeSessionId:p}:Po(t)}catch{throw new G("Could not read the isolated OpenCode session database safely.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}var hi=C(()=>{g();Xt();_i();Nu();});function yn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function mi(){let t;try{let n=(await import('better-sqlite3')).default,r=join(Cr(),"opencode.db");t=new n(r,{readonly:!0,fileMustExist:!0});let o=t.prepare("SELECT value FROM kv WHERE key = ?").get("models-dev:v2:catalog");if(!o||typeof o.value!="string")throw new Error("OpenCode model catalog row is unavailable");let s=JSON.parse(o.value);if(!yn(s))throw new Error("OpenCode model catalog shape is unavailable");let i=typeof s.body=="string"?JSON.parse(s.body):s.body;if(!yn(i))throw new Error("OpenCode model catalog body shape is unavailable");let c=new Map;for(let[d,u]of Object.entries(i)){if(!d||!yn(u)||!yn(u.models))throw new Error("OpenCode model provider shape is unavailable");for(let[l,p]of Object.entries(u.models)){if(!l||!yn(p))throw new Error("OpenCode model shape is unavailable");let _=p.capabilities;if(_===void 0)continue;if(!yn(_))throw new Error("OpenCode model capability shape is unavailable");let h=_.reasoning;if(h===void 0)continue;if(!yn(h))throw new Error("OpenCode reasoning capability shape is unavailable");let m=h.effort;(m===void 0||Array.isArray(m)&&m.every(k=>typeof k=="string"))&&c.set(`${d}/${l}`,Array.isArray(m)?m:[]);}}return c}catch{return console.debug("[opencode] could not read private model effort catalog; omitting effort choices"),new Map}finally{try{t?.close();}catch{}}}var bu=C(()=>{g();yi();wu();Su();_i();hi();Yt();});function Ah(t){return t?Ih[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Qe(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Nh(){let t;try{t=Cr();}catch{return mi().catch(()=>new Map)}let e=Date.now();if(Cu===t&&Lo&&Lo.expiresAt>e)return Lo.result;Cu=t;let n=mi().catch(()=>new Map);return Lo={expiresAt:e+Sh,result:n},n}async function Oh(t){let e=await gi(t),n=t.additionalArgs??[],r=Qe(n,"--model")||Qe(n,"-m");if(!t.model||!t.effort||r)return e;let o=(await Nh()).get(t.model);return !o||o.includes(t.effort)?e:(console.debug("[opencode] requested effort is not listed for this model; using OpenCode default"),{...e,effort:void 0})}function Mu(t){let e=[],n=0,r=false,o=false,s=0;for(let c=0;c<t.length;c++){let d=t[c];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let u=t.slice(s,c+1).trim();u&&e.push(u),s=c+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $u(t){let e=ce(t.part)?t.part:void 0;return t.type==="reasoning"||e?.type==="reasoning"}function vh(t){let e=ce(t.part)?t.part:void 0;return (typeof e?.text=="string"?e.text:typeof t.text=="string"?t.text:void 0)?.trim()||void 0}function bh(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let i=JSON.parse(o);ce(i)?e.push(i):n=!0;continue}catch{}let s=Mu(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let c=JSON.parse(i);ce(c)?e.push(c):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Ei(t){let e=ce(t.error)?t.error:void 0,n=e&&ce(e.data)?e.data:void 0,r=Hu(e),o=Ye(e?.name),s=Ye(n?.message)??Ye(e?.message)??Ti(r)??Ye(t.message)??Ye(t.errorMessage)??Ye(t.error),i=Ye(t.ref),c=o&&s&&o!==s?`${o}: ${s}`:o??s??Lu;return (i?`${c} (ref: ${i})`:c).slice(0,Eh)}function xu(t){let e=ce(t.error)?t.error:void 0,n=typeof e?.type=="string"?e.type:void 0,r=typeof e?.status=="number"?e.status:Number(e?.status),o=Ei(t),s=Hu(e),i=s&&ce(s.error)?s.error:void 0,c=typeof i?.type=="string"?i.type:void 0,d=[o,Ti(s)].filter(Boolean).join(`
|
|
84
|
+
`);if(r===402||Ch(d))return new G(`OpenCode subscription is required: ${o}`,je,{code:"SUBSCRIPTION_REQUIRED",kind:"config",providerReason:Or(o)});if(r===403&&(c==="RegionError"||c==="FreeTierError"))return new G(`OpenCode account settings are required: ${o}`,je,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:"access",providerReason:Or(o)});if(n==="provider.auth"||r===401||r===403)return new G(`OpenCode authentication is required: ${o}`,je,{code:"AUTH_REQUIRED",kind:"config"});if(r===410||c==="ModelDeprecated")return new G(`OpenCode model has been retired: ${o}`,je,{code:"MODEL_RETIRED",kind:"config",replacementModel:xh(s,e,t),providerReason:Or(o)});if(n==="provider.free-limit"||r===429){let u=Dh(e);return new G(`OpenCode rate limit reached: ${o}`,je,{code:"RATE_LIMITED",kind:"transient",...u===void 0?{}:{retryAfterMs:u}})}if(n==="provider.no-route")return new G(`OpenCode model or variant unavailable: ${o}`,je,{code:"MODEL_UNAVAILABLE",kind:"config"});if(n==="provider.invalid-request"&&r===400){let u=[o,Ti(s)].filter(h=>h!==void 0),l=u.find(h=>/requires global regions/i.test(h)),p=u.find(h=>/trains on request data/i.test(h)),_=l?"region":p?"training_consent":void 0;if(_)return new G(`OpenCode account settings are required: ${o}`,je,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:_,providerReason:Or(l??p)})}return new G(`OpenCode error: ${o}`,je,{code:"PROVIDER_CRASHED",kind:"transient"})}function Hu(t){let n=(t&&ce(t.response)?t.response:void 0)?.body;if(ce(n))return n;if(typeof n=="string")try{let r=JSON.parse(n);return ce(r)?r:void 0}catch{return}}function Ti(t){let e=t&&ce(t.error)?t.error:void 0;return Ye(e?.message)??Ye(t?.message)}function Ch(t){return /insufficient\s+(?:balance|account funds)|credit\s+limit\s+exceeded|payment\s+required|account invoice is overdue|billing_error|please add or update your payment method|(?:GLM Coding Plan|enterprise) package has expired|your current subscription plan does not yet include access to/i.test(t)}function xh(t,e,n){let r=t&&ce(t.metadata)?t.metadata:void 0,o=typeof r?.replacement=="string"?r.replacement.trim():void 0;if(!o)return;let s=[r?.model,e?.model,n.model,n.modelID].find(d=>typeof d=="string"&&d.trim().length>0)?.trim(),i=s&&s.includes("/")?s.slice(0,s.indexOf("/")):"opencode-go",c=o.includes("/")?o:`${i}/${o}`;return /^[A-Za-z0-9._/-]{1,128}$/.test(c)?c:void 0}function Dh(t){let e=t?.retryAfterMs;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;let r=(t&&ce(t.response)?t.response:void 0)?.body,o=typeof r=="string"?Ph(r):ce(r)?r:void 0;if(o){let s=wi(o);if(s)return Du(s.value,s.key==="retryafterms")}if(typeof r=="string"){let s=r.match(/retry[-_]after(?:\s*[:=]\s*|\s+)["']?([^"'\s,;}]+)/i);if(s?.[1])return Du(s[1],false)}}function Ph(t){try{let e=JSON.parse(t);return ce(e)?e:void 0}catch{return}}function wi(t){if(Array.isArray(t)){for(let e of t){let n=wi(e);if(n)return n}return}if(ce(t)){for(let[e,n]of Object.entries(t)){let r=e.toLowerCase().replace(/[-_]/g,"");if(r==="retryafterms"||r==="retryafter")return {value:n,key:r}}for(let e of Object.values(t)){let n=wi(e);if(n)return n}}}function Du(t,e){if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return e?t:Math.round(t*1e3);if(typeof t!="string"||!t.trim())return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return e?n:Math.round(n*1e3);if(e)return;let r=Date.parse(t);return Number.isFinite(r)?Math.max(0,r-Date.now()):void 0}function Pu(t){let e=bh(t),n=[],r=null,o=0,s=[],i=[],c,d=false;for(let u of e.events){if($u(u))continue;let l=typeof u.type=="string"?u.type:void 0;if(l){if(l==="text"){let p=ce(u.part)?u.part:void 0,_=typeof p?.text=="string"?p.text:void 0;_?.trim()&&n.push(_.trim());continue}if(l==="result"){typeof u.result=="string"&&(r=u.result);continue}if(l==="tool_use"){o++;continue}if(l==="error"){s.push(u),i.push(Ei(u));continue}if(l==="step_finish"){d=true;let p=ce(u.part)?u.part:void 0;c=typeof p?.reason=="string"?p.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorEvents:s,errorMessages:i,terminalReason:c,hasTerminal:d}}function Uu(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Lh(){return new G("OpenCode returned no assistant output.",je,{code:"EMPTY_OUTPUT",kind:"transient"})}function Mh(){return new G("OpenCode emitted malformed JSON output.",je,{code:"PROVIDER_CRASHED",kind:"transient"})}function $h(t,e){switch(Uu(t)){case "length":return new G("OpenCode stopped because the context window was exceeded.",je,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new G("OpenCode stopped because the content filter blocked the response.",je,{code:"UNKNOWN",kind:"permanent"});case "error":return new G(`${Lu} while generating a response.`,je,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var wh,je,Lu,Eh,Rh,Sh,Cu,Lo,Ih,Ri,Si=C(()=>{g();Xt();Tu();Nr();Bn();mn();bu();hi();wh=new Set(["step_start","step_finish"]),je="cli/opencode",Lu="OpenCode provider error",Eh=240,Rh="Follow the instructions provided on standard input.",Sh=3e5,Ih={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Ri={command:"opencode",prepare:Oh,meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Qe(o,"--format")||o.push("--format","json"),Qe(o,"--thinking")||o.push("--thinking"),!Qe(o,"--standalone")&&!Qe(o,"--server")&&o.push("--standalone"),e.resumeSessionId&&!Qe(o,"-s")&&!Qe(o,"--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=Ah(e.mode);Qe(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!Qe(o,"--auto")&&o.push("--auto");let c=Qe(o,"--model")||Qe(o,"-m");if(e.model&&!c){let d=e.effort?`${e.model}#${e.effort}`:e.model;o.push("--model",d);}else e.effort&&!e.model&&!c&&console.debug("[opencode] ignoring effort because no model is configured");return o.push(Rh),{args:o,stdinMessage:t,env:br()}},extractText(t){let e=Pu(t),n=e.errorEvents[0];if(n)throw xu(n);let r=$h(e.terminalReason??"");if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0)return o;if(e.resultText?.trim())return e.resultText;if(e.malformed)throw Mh();let s=Uu(e.terminalReason);if(e.hasTerminal&&s==="tool-calls"&&e.toolUseCount>0)return "";throw Lh()},interpretExit(t,e,n=""){if(t===0)return null;let o=Pu(n).errorEvents[0];return o?xu(o):null},parseResultMeta(t){let e=Wn(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=new Map,i;try{JSON.parse(t),i=[t];}catch{i=Mu(t),i.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let c of i){let d;try{d=JSON.parse(c);}catch{continue}let u=at(d,r),l=d.type;if($u(d)){let p=vh(d);if(!p)continue;let _=ce(d.part)?d.part:void 0,h=typeof _?.id=="string"?_.id:typeof d.id=="string"?d.id:void 0,m=p;if(h){let k=`opencode.reasoning:${h}`,w=n?.state.get(k),x=typeof w=="string"?w:s.get(h);if(typeof x=="string"&&(x===p||x.startsWith(p))||typeof x=="string"&&p.startsWith(x)&&(m=p.slice(x.length).trim(),!m))continue;s.set(h,p),n?.state.set(k,p);}o.push({timestamp:u,type:"thinking",content:m});continue}if(l){if(l==="text"){let _=d.part?.text;_&&o.push({timestamp:u,type:"text",content:_});continue}if(l==="tool_use"){let p=d.part;if(!p)continue;let _=String(p.tool||""),h=String(p.callID||p.id||""),m=p.state,k=String(m?.status||""),w=m?.input,x=it(w);if(o.push({timestamp:u,type:"tool_use",toolName:_,toolUseId:h,toolInput:x}),k==="completed"&&m?.output!==void 0){let T=m.output,L=typeof T=="string"?T:JSON.stringify(T);o.push({timestamp:u,type:"tool_result",toolUseId:h,resultPreview:L,isError:false});}else k==="error"&&o.push({timestamp:u,type:"tool_result",toolUseId:h,resultPreview:String(m?.error||"tool error"),isError:true});continue}if(l==="error"){let p=Ei(d);o.push({timestamp:u,type:"error",content:p,errorMessage:p});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?wh.has(r):!1}catch{return false}}};});var qu=C(()=>{g();});function jn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Fh(t,e){return t&&Bu.has(t)||jn(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"&&Bu.has(o)})}function Wh(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 Gh(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(!qh.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function Ze(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function jh(t,e){if(!(t?Uh.has(t)||Pt(Ii).some(s=>s.id===t):false)||!t)return e;let r=Fn(Ii,t),o=si(Ii)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function Lt(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function Oi(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 vi(t){return t.step.step_index}function de(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Io(e)?.slice(0,500).trim()||void 0}function zh(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&Bh.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 Kh(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 Gu(t){let e=Ze(t)?t:void 0,n=e&&Ze(e.error)?e.error:void 0,r=e?de(e.code)??de(e.error_code)??de(n?.code)??de(n?.error_code):void 0,o=typeof t=="string"?de(t):e?de(e.message)??de(e.error)??de(e.reason)??de(n?.message)??de(n?.error)??de(n?.reason):void 0,s=zh(r,o),i=e?Lt(e.retry_after_ms)??Lt(e.retryAfterMs)??Lt(n?.retry_after_ms)??Lt(n?.retryAfterMs):void 0;return {code:s,kind:Kh(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function $o(t){let e=Gu(t);return new G(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function bi(t){return new G(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function Jh(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=Ni))throw new G(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${Ni} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function Ai(){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 Ho(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function Uo(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 Vh(t){let e=Uo(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||Ho(e.event)?.status!=="SUCCESS"||Mo(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=Oi(o),i=vi(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"||!Ze(o.usage)||Lt(o.usage.input_tokens)===void 0||Lt(o.usage.output_tokens)===void 0)return false;return true}function Xh(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function Yh(t,e){return Ze(t)&&Ze(e)?{...e,...t}:Ze(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&Ze(e)?{...e,message:t}:t??e}function Qh(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let i of e){let c=Ze(i)?i:void 0,d=typeof i=="string"?de(i):de(c?.display_name)??de(c?.action);d&&!n.includes(d)&&n.length<5&&n.push(d.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("Could not run because of permissions.","cli/antigravity",{code:"UNKNOWN",kind:"permanent",providerReason:s})}function Mo(t){let e=Uo(t);if(!e)return;if(e.event.kind==="agy_error")return $o(e.event.error);let n=Ho(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return Qh(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return bi("Antigravity returned a result with an unsupported status.");let r=n.error,o=Yh(r==null||r===""?n:r,Xh(t,e.index));return $o(o)}function ju(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function Zh(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function em(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function zu(t){let e=ju(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function tm(t){let e=Ze(t)?t:void 0,n=e&&Ze(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=(de(e?.type)??de(e?.code)??de(e?.error_type)??de(n?.type)??de(n?.code)??de(n?.error_type)??de(r)??"TOOL_ERROR").slice(0,60),s=Gu(t).message.slice(0,250);return zu({type:o,message:s})??"Antigravity reported a tool error."}function Fu(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function Wu(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var Ii,Uh,qh,Bu,Ni,Bh,Ci,xi=C(()=>{g();Xt();qu();Vs();Sr();Yt();Ar();ei();ii();Ii="antigravity",Uh=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),qh=new Set(["--conversation","--resume","--continue"]),Bu=new Set(["bypassPermissions","agent-full-access","yolo"]),Ni=18e4,Bh=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"]);Ci={command:"agy",maxInitialInputBytes:Ni,meta:{displayName:"Antigravity",models:Fc(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=Er(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){Jh(t);let{model:r,effort:o}=Qt(e.model),s=ri(r),i=s.model,c=e.effort??o??s.effort,d=jh(i,c),u=e.additionalArgs??[],l=Gh(Wh(u,new Set(["--input-format","--output-format"]))),p=i&&!jn(u,"--model")?["--model",i]:[],_=jn(u,"--effort")?[]:tu(d),h=jn(u,"--mode")||jn(u,"--dangerously-skip-permissions")?[]:eu(e.mode),m=Fh(e.mode,u)||jn(u,"--settings")?[]:["--settings",JSON.stringify({permissions:{allow:au(e.builtinAllow)}})],k=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...p,..._,...h,...k,...m,...l],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
|
|
85
|
+
`,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=Rr(t),n=Uo(e)?.event,r=Mo(e);if(r)throw r;let o=n?Ho(n):void 0;if(o){if(o.status!=="SUCCESS")throw bi("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw bi("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw Ai();return o.response}if(e.length>0)throw Ai();let s=t.trim();if(!s)throw Ai();return s},extractPartialText(t){let e=Rr(t),n=Uo(e)?.event;if(!n||n.kind==="agy_error")return;let r=Ho(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=Rr(n??""),o=Mo(r);return o||(t!==0&&e.trim()?$o(e):null)},parseResultMeta(t){let e=Rr(t),n=0,r=0,o=0,s=0,i=new Set;for(let d of e){if(d.kind!=="step_update"||d.step.state!=="DONE"||!Ze(d.step.usage))continue;let u=Oi(d),l=vi(d);if(!u||!Number.isSafeInteger(l))continue;let p=JSON.stringify([u,l]);if(i.has(p))continue;let _=d.step.usage,h=Lt(_.input_tokens),m=Lt(_.output_tokens);if(h===void 0||m===void 0)continue;i.add(p);let k=Lt(_.cache_read_tokens)??0;n+=h+k,r+=m,o+=k,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:Vh(e)},model:null}},parseEvent(t,e,n){let r=Er(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [Wu(o,$o(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let h=Mo([r]);return h?[Wu(o,h)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=Oi(r)??"unknown",c=vi(r),d=`${i}:${c}`;if((s.state==="DONE"||s.state==="ERROR")&&Fu(n,`antigravity:terminal:${d}`))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=Ze(s.tool_info)?s.tool_info:void 0,l=em(s,u);if(!l)return [];let p=Zh(s);if(s.state==="ACTIVE"){if(Fu(n,`antigravity:active:${d}`))return [];let h=ju(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:l,toolUseId:p,...h===void 0?{}:{toolInput:h}}]}let _=s.state==="ERROR"?tm(u?.error):zu(u?.output);return [{timestamp:o,type:"tool_result",toolName:l,toolUseId:p,..._===void 0?{}:{resultPreview:_},...s.state==="ERROR"?{isError:true}:{}}]}};});var Ku=C(()=>{g();Un();Bn();qn();mn();});function zn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Kn(t){return zn(t)?t:void 0}function He(t){return typeof t=="string"?t:void 0}function wn(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function um(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let c=t[i];if(n===-1){(c==="{"||c==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(c==="\\"&&o){s=true;continue}if(c==='"'){o=!o;continue}o||(c==="{"||c==="["?r+=1:(c==="}"||c==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function xr(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return zn(n)?[n]:[]}catch{return um(e).flatMap(n=>{try{let r=JSON.parse(n);return zn(r)?[r]:[]}catch{return []}})}}function el(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Tn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Tn).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
86
|
+
`):void 0}if(zn(t)){if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(t.type==="text"&&typeof t.data=="string")return t.data;for(let e of ["content","FileContent","rawOutput"]){let n=Tn(t[e]);if(n!==void 0)return n}}}function lm(t){let e=i=>Array.isArray(i)&&i.every(c=>Number.isInteger(c)&&c>=0&&c<=255),n=i=>typeof i=="string"&&i.trim().length>0?i:void 0,r=i=>new TextDecoder("utf-8",{fatal:false}).decode(Uint8Array.from(i)),o=i=>{let c=JSON.stringify(i,(d,u)=>e(u)?`<bytes:${u.length}>`:u);return c===void 0?String(i):c},s=t.rawOutput;if(s!=null){let i=Kn(s);if(!i)return n(Tn(s))??o(s);let c;if(e(i.output)&&i.output.length>0&&(c=n(r(i.output))),!c&&e(i.stdout)&&i.stdout.length>0&&(c=n(r(i.stdout))),!c){let l=Kn(i.Result);c=n(i.output)??n(l?.output)??n(Tn(s));}let d=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(d!==void 0)if(c){let l=c.endsWith(`
|
|
87
|
+
`)||c.endsWith("\r")?"":`
|
|
88
|
+
`;c=`${c}${l}${d}`;}else c=n(d);if(c)return c;let u=n(i.summary)??n(Tn(t.content))??n(i.output_for_prompt);return u!==void 0?u:o(s)}if(t.content!==null&&t.content!==void 0)return Tn(t.content)??o(t.content);if(t.result!==null&&t.result!==void 0)return Tn(t.result)??o(t.result)}function tl(t){let e=Kn(t.error),n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0].find(r=>typeof r=="string"&&r.trim().length>0);return n?nl(n):"Grok CLI reported an error."}function nl(t){return (t.replace(cm,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Qu(t){return dm.test(t)}function pm(t){let e=Kn(t.modelUsage);return e?Object.keys(e)[0]??null:null}function _m(t){let e=Kn(t.usage);if(!e)return null;let n=wn(e.cache_read_input_tokens);return {inputTokens:wn(e.input_tokens)+n,cachedInputTokens:n,outputTokens:wn(e.output_tokens),costUsd:wn(t.total_cost_usd)}}function fm(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
89
|
+
`).flatMap(xr)){if(i.type!=="usage")continue;let c=Kn(i.usage);if(!c)continue;let d=He(i.signature);if(d&&d.length>0){let l=`signature:${d}`;if(s.has(l))continue;s.add(l);}let u=wn(c.cache_read_input_tokens);e+=wn(c.input_tokens)+u,n+=u,r+=wn(c.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function gm(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,Vu)){if(!zn(s))continue;let i=He(s.content)?.trim();if(!i)continue;let c=He(s.status)?.trim(),d=He(s.priority)?.trim(),u=[c?`status=${c}`:void 0,d?`priority=${d}`:void 0].filter(p=>!!p),l=u.length>0?` (${u.join(", ")})`:"";n.push(`- ${i}${l}`);}if(n.length===0)return [];e.entries.length>Vu&&n.push(Yu);let r=n.join(`
|
|
90
|
+
`),o=r.length>Xu?`${r.slice(0,Xu-1)}${Yu}`:r;return [{timestamp:t,type:"info",content:o}]}function hm(t,e){let n=He(e.type);if(n==="thought"){let r=He(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=He(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return gm(t,e);if(n==="tool_call"){let r=He(e.toolCallId),o=He(e.toolName)??He(e.title),s=e.rawInput===void 0?void 0:el(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=He(e.status);if(r!=="completed"&&r!=="failed"&&r!=="error")return [];let o=lm(e),s=r!=="completed"||e.isError===true;return [{timestamp:t,type:"tool_result",toolUseId:He(e.toolCallId),toolName:He(e.toolName)??He(e.title),...o!==void 0?st(o,s):{isError:s}}]}if(n==="error"){let r=tl(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}function mm(t){return process.platform==="win32"?{flags:["--prompt-file",Zu]}:{flags:["--prompt-file","/dev/stdin"],stdinMessage:t}}var qo,am,dm,cm,Vu,Xu,Yu,Zu,Di,Pi=C(()=>{g();Xt();Js();Yt();qn();Ar();mn();qo="cli/grok",am=new Set(["available_commands","usage","end"]),dm=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,cm=/\u001b\[[0-?]*[ -/]*[@-~]/g,Vu=20,Xu=4e3,Yu="\u2026",Zu="__CREWX_GROK_PROMPT_FILE__";Di={command:"grok",createSessionId:()=>randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=Qt(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],c=n?Pt("grok").some(J=>J.id===n):false,d=n&&c?Fn("grok",n):[],u=!o||d.length===0||d.includes(o)?o:void 0,l=Zc(u),p=e.additionalArgs??[],_=J=>p.some(oe=>oe===J||oe.startsWith(`${J}=`)),h=e.providerOptions,m=h?.alwaysApprove,k=h?.sandbox,w=_("--permission-mode")?[]:Xc(e.mode),x=_("--always-approve")?[]:Yc(m),T=_("--sandbox")?[]:Qc(k),L=_("--verbatim")?[]:["--verbatim"],N=mm(t),D=["--no-auto-update",...s,...N.flags,...L,"--output-format","streaming-json","--no-alt-screen",...i,...l,...w,...x,...T,...p],A={args:D,stdinMessage:N.stdinMessage};if(process.platform==="win32"){let J=D.indexOf(Zu);if(J<0)throw new Error("Grok Windows prompt file placeholder is missing from argv");let oe,qe,Ae;A.prepare=()=>Ae?Promise.reject(new Error("Grok prompt invocation was already disposed")):(qe||(qe=(async()=>{oe=await mkdtemp(join(tmpdir(),"crewx-grok-"));let on=join(oe,"prompt.txt"),eo=await open(on,"wx",384);try{await eo.writeFile(t,{encoding:"utf8"});}finally{await eo.close();}D[J]=on;})()),qe),A.dispose=()=>(Ae||(Ae=(async()=>{await qe?.catch(()=>{}),oe&&(await rm(oe,{recursive:true,force:true}),oe=void 0);})()),Ae);}return A},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
91
|
+
`).flatMap(xr))typeof r.type=="string"&&(n=true),r.type==="text"&&typeof r.data=="string"&&e.push(r.data);return e.length>0?e.join(""):n?"":t.trim()},extractFailure(t){for(let e of xr(t))if(e.type==="error"){let n=tl(e);return Qu(el(e))?new hn(n,qo):new G(n,qo)}return null},interpretExit(t,e){if(t===0)return null;let n=nl(e)||`Grok CLI exited with code ${t}.`;return Qu(e)?new hn(n,qo):new G(n,qo)},parseResultMeta(t){let n=t.split(`
|
|
92
|
+
`).flatMap(xr).find(r=>r.type==="end");return n?{usage:_m(n),model:pm(n)}:{usage:fm(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return xr(t).flatMap(r=>hm(at(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return zn(n)&&typeof n.type=="string"?am.has(n.type):!1}catch{return false}}};});var ki,yi=C(()=>{g();ai();ci();li();Si();xi();Ku();Pi();ai();ci();li();Si();xi();Pi();Un();ki={codex:ui,claude:Co,opencode:Ri,antigravity:Ci,copilot:di,grok:Di};});function rl(t){if(t.startsWith("cli/"))return ki[t.slice(4)]}var ol=C(()=>{g();Oc();yi();});function Bo(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function km(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function Fo(t){if(typeof t.provider!="string"||t.provider.length===0)return;let n=t.taskLogRepository.readLogs(t.taskId)?.entries.filter(_=>_.level==="stdout").map(_=>_.message).join(`
|
|
93
|
+
`)??"";if(!n.trim())return;let r=rl(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=km(o?.model,t.model),i=o?.usage;if(!i)return {stdout:n,adapter:r};let c=Bo(i.inputTokens),d=Bo(i.outputTokens),u=Bo(i.cachedInputTokens),l=sc(Bo(i.costUsd),c,d,u,s);return c!==0||d!==0||u!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:c,outputTokens:d,cachedInputTokens:u,costUsd:l,model:s,...i.complete===void 0?{}:{complete:i.complete}}}:{stdout:n,adapter:r}}var Li=C(()=>{g();ol();yo();});function $i(t){let e=new Set;for(let n of t)for(let r of ym.get(n)??[n])e.add(r);return [...e]}function Hi(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.terminalReason;return typeof n=="string"&&Tm.has(n)?n:void 0}catch{return}}function dt(t){let e=Hi(t.metadata);if(e)return e;if(t.status==="runner_lost")return "runner_lost";if(t.status==="stopped")return "user_stop";if(t.status==="failed"&&typeof t.error=="string"){if(Mi.stopped.test(t.error))return "user_stop";if(Mi.runnerLost.test(t.error))return "runner_lost"}}function De(t){switch(t.status){case "stopped":case "pending":case "running":case "paused":case "success":return t.status;case "completed":case "done":return "success";case "error":case "runner_lost":return "failed";case "failed":{let e=Hi(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&Mi.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function wm(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function Dr(t){let e=De(t);return t.status==="runner_lost"&&Hi(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...wm(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var En,ym,Mi,Tm,Jn=C(()=>{g();En=["success","completed","done","failed","error","stopped","runner_lost"],ym=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);Mi={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},Tm=new Set(["user_stop","runner_lost","launch_failed"]);});function Ui(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let o=Number(r);return !Number.isFinite(o)||o<=0?e:Math.max(n,Math.trunc(o))}function Lr(){return Ui("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Xn(){return Ui("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Go(){return Ui("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Vn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Wo(t){let e=typeof t=="object"&&t!==null&&"code"in t?String(t.code):t instanceof Error?t.name:typeof t;console.warn(`[crewx] task heartbeat write failed (${e}); execution continues`);}function Em(t){return t?{id:t.id,status:t.status,run_epoch:t.run_epoch,stop_requested_at:t.stop_requested_at,stop_requested_epoch:t.stop_requested_epoch,pid:t.pid,metadata:t.metadata,started_at:t.started_at,duration_ms:t.duration_ms}:null}function sl(t,e){return !!t.stop_requested_at&&Vn(t.stop_requested_epoch)===Vn(e)}function il(t,e){let n=Vn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=Em(t.getTask(e.taskId));return !o||o.status!=="running"||Vn(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function ul(t,e){let n=Pr.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),Pr.delete(t),true)}function Mr(t,e){let n=Pr.get(t);return !n||e!==void 0&&n.runEpoch!==Vn(e)?false:ul(t,n)}function ll(t,e){let n=Vn(e.runEpoch);Mr(e.taskId);let r=true,o=null;try{let u=il(t,{...e,runEpoch:n});r=u.accepted,o=u.row;}catch(u){Wo(u);}if(!r)return false;let s=Lr(),i=Math.min(s,1e3),c=setInterval(()=>{let u=Pr.get(e.taskId);if(!(!u||u.timer!==c))try{u.heartbeatElapsedMs+=i;let l=u.heartbeatElapsedMs>=s,p=il(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){ul(e.taskId,u);return}l&&(u.heartbeatElapsedMs%=s,u.lastHeartbeatAt=Date.now()),p.row&&sl(p.row,n)&&!u.stopRequested&&(u.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(Wo));}catch(l){Wo(l);}},i),d={timer:c,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return Pr.set(e.taskId,d),typeof c=="object"&&c!==null&&"unref"in c&&c.unref(),o&&sl(o,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(Wo)),true}var al,dl,cl,Pr,$r=C(()=>{g();al=1e4,dl=3e4,cl=18e5;Pr=new Map;});function zo(t,e=Date.now(),n=ji){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=Ji(n,ji,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function Yi(t){let e=[],n=typeof t.pid=="number"&&t.pid>0?t.pid:void 0;n!==void 0&&e.push({pid:n,startedAt:t.pid_started_at});let r=gl(t.metadata),o=r.ownership==="runner"&&typeof r.providerPid=="number"&&Number.isSafeInteger(r.providerPid)&&r.providerPid>0?r.providerPid:void 0;if(o!==void 0&&o!==n){let s=r.providerPidStartedAt;e.push({pid:o,startedAt:typeof s=="string"?s:null});}return e}async function Qi(t,e={}){if(t.pid===process.pid||t.pid===process.ppid)return {verdict:"unproven",ownership:"not_owned",reason:"pid is this process or its parent"};let n=typeof t.startedAt=="string"?Date.parse(t.startedAt):Number.NaN,r=Number.isFinite(n),o=e.legacyStartBoundaryMs;if(!r&&o===void 0)return {verdict:"unproven",ownership:"unknown",reason:"no start time recorded"};let s=e.processControlOptions??{},i=e.processControl?.checkProcessOwnershipAsync??fc,c=e.processControl?.readProcessIdentityAsync??kc,d;try{d=await i(t.pid,e.ownershipMarkers??Sm,s);}catch{d="unknown";}let u;try{u=await c(t.pid,s);}catch{u={status:"unknown"};}if(u.status==="not_found")return {verdict:"unproven",ownership:"not_found",reason:"process is no longer running"};if(u.status!=="found")return {verdict:"unproven",ownership:"unknown",reason:"start time could not be read"};let l=new Date(u.startedAtMs).toISOString();if(r){if(Math.abs(u.startedAtMs-n)>wo)return {verdict:"reused",reason:`started ${l}, not the recorded ${t.startedAt}`}}else return o!==void 0&&u.startedAtMs>o?{verdict:"reused",reason:`started ${l}, after the row's last heartbeat`}:{verdict:"unproven",ownership:"unknown",reason:"no start time recorded and it started before the row's last heartbeat"};return d!=="owned"?{verdict:"unproven",ownership:d,reason:"command line has no owned marker"}:u.groupId!==null&&u.groupId!==t.pid?{verdict:"unproven",ownership:"not_owned",reason:"pid does not lead its process group"}:{verdict:"owned"}}async function Zi(t,e={}){let n=await Qi(t,e);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function Ji(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function gl(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function bm(t){if(!t)return;let e=gl(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function ze(t,e){if(!t)return {status:"not_running",finalStatus:"not_running",...e?{pid:e}:{}};let n=typeof t.pid=="number"&&t.pid>0?t.pid:e;if(t.status==="stopped"){let r=bm(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function jo(t,e,n="Process owner could not be verified"){let r=e??(t.pid&&t.pid>0?t.pid:void 0);return {status:"ownership_unverified",finalStatus:t.status,...r?{pid:r}:{},error:n}}function ae(t,e,n){let r=n??(t?.pid&&t.pid>0?t.pid:void 0);return {status:"failed",finalStatus:t?.status??null,...r?{pid:r}:{},error:e}}function Gi(t,e){return ae(t,Am,e)}function Cm(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Xn():false}function xm(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Dm(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return ze(r,n)}async function Pm(t,e,n,r){let o=Date.now()+n;for(;;){let s=Dm(t,e);if(s)return s;let i=o-Date.now();if(i<=0)return;await new Promise(c=>{setTimeout(c,Math.min(r,i));});}}async function fl(t,e,n){let r=new Date().toISOString(),o={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},s=t.requestTaskStop({id:e,requestedAt:r,...o}),i=t.getTask(e);if(!s.accepted){if(s.status==="pending"){let L=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),N=t.getTask(e);if(L||!N||N.status!=="running")return ze(N);if(s=t.requestTaskStop({id:e,requestedAt:r,...o}),!s.accepted&&s.status!=="running"||!s.accepted&&!s.alreadyRequestedAt)return ze(t.getTask(e))}else if(!(s.status==="running"&&s.alreadyRequestedAt))return ze(i)}let c=s.runEpoch,d=Ji(n.graceMs,ji,0),u=Ji(n.pollMs,Rm,1),l=await Pm(t,e,d,u);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return ze(p);let _=Yi(p),h=_.map(L=>L.pid),m=h[0];if(!m){let L=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),N=t.getTask(e);return L||N?.status!=="running"?ze(N):ae(N,"Failed to finalize task stop")}let k=xm(n);if(!Cm(p,Date.now())){for(let L of _)if(await Zi(L,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:k})!=="owned")return jo(p)}let w=n.processControl?.terminateProcessTree??Vt;for(let L of h){let N;try{N=await w(L,{...k,signal:Jt});}catch(D){N={status:"failed",pid:L,method:k.platform==="win32"?"taskkill":"process-group",error:D instanceof Error?D.message:String(D)};}if(N.status==="failed")return ae(t.getTask(e),N.error??"Failed to terminate process tree")}let x=t.finalizeTaskStop({id:e,runEpoch:c,method:"forced"}),T=t.getTask(e);return x||T?.status!=="running"?ze(T,m):ae(T,"Task changed before stop was finalized")}function Vi(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Xi(t){return Number.isSafeInteger(t)&&t>=0}function Hr(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Lm(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Mm(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function $m(t,e){let n=t?.pid&&t.pid>0?t.pid:e;return {status:"stopped",method:"forced",finalStatus:t?.status??"failed",...n?{pid:n}:{}}}function Hm(t){switch(t){case "epoch_mismatch":return zi;case "workspace_mismatch":return Ki;default:return}}async function hl(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Gi(n,Vi(e.targetPid)?e.targetPid:void 0);if(!Xi(e.sourceRunEpoch)||!Xi(e.settleRunEpoch)||Hr(n.run_epoch)!==e.settleRunEpoch)return ae(n,qi,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return ae(n,Bi,e.targetPid);let r=new Date().toISOString(),o;try{o=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return ae(n,Wi,e.targetPid)}let s=x=>o.stopRequestReceipt?{...x,stopRequestReceipt:o.stopRequestReceipt}:x,i=n,c=()=>{let x=t.getTask(e.taskId);return i=x,x},d=(x,T=false)=>{if(T)try{c();}catch{}return s(ae(i,x,e.targetPid))},u;try{u=c();}catch{return d(Wi)}if(!u||u.status!=="running")return s(Gi(u,e.targetPid));if(o.runEpoch!==e.settleRunEpoch||Hr(u.run_epoch)!==e.settleRunEpoch)return s(ae(u,qi,e.targetPid));if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId)return s(ae(u,Bi,e.targetPid));if(!Vi(e.targetPid))return s(ae(u,Im));let l=Lm(e),p;try{p=await Zi({pid:e.targetPid,startedAt:u.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:l});}catch{return s(jo(u,e.targetPid))}if(p!=="owned")return s(jo(u,e.targetPid));let _;try{_=c();}catch{return d(Wi)}if(!_||_.status!=="running")return s(Gi(_,e.targetPid));if(Hr(_.run_epoch)!==e.settleRunEpoch)return s(ae(_,qi,e.targetPid));if(e.workspaceId!==void 0&&_.workspace_id!==e.workspaceId)return s(ae(_,Bi,e.targetPid));let h=e.processControl?.terminateProcessTree??Vt,m;try{m=await h(e.targetPid,{...l,signal:Jt});}catch{return d(pl,true)}if(m.status==="failed")return d(pl,true);let k;try{k=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return d(Fi,true)}if(!k)return d(Fi,true);let w;try{w=c();}catch{return d(Fi)}return s(ze(w,e.targetPid))}async function ml(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return ze(n);if(!Xi(e.expectedRunEpoch)||Hr(n.run_epoch)!==e.expectedRunEpoch)return ae(n,zi);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return ae(n,Ki);let r=n.pid;if(!Vi(r))return ae(n,Nm);let o=Mm(e);if(await Zi({pid:r,startedAt:n.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:o})!=="owned")return jo(n,r,Om);let i=e.processControl?.terminateProcessTree??Vt,c;try{c=await i(r,{...o,signal:Jt});}catch{return ae(t.getTask(e.taskId),_l,r)}if(c.status==="failed")return ae(t.getTask(e.taskId),_l,r);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return ze(d,r);if(Hr(d.run_epoch)!==e.expectedRunEpoch)return ae(d,zi,r);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return ae(d,Ki,r);let u;try{u=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return ae(t.getTask(e.taskId),vm,r)}let l=Hm(u);return l?ae(t.getTask(e.taskId),l,r):u!=="settled"?ze(t.getTask(e.taskId),r):$m(t.getTask(e.taskId),r)}function kl(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(ta(),yl)).then(({TaskRepository:s})=>fl(new s,r,o))}return fl(t,e,n)}var ji,Rm,Sm,Im,qi,Bi,Am,pl,Fi,Wi,zi,Ki,Nm,Om,_l,vm,ea=C(()=>{g();Eo();$r();ji=5e3,Rm=250;Sm=["agy","crewx","claude","codex","opencode","grok","node"];Im="INSTRUCTION_STOP_TARGET_PID_MISSING",qi="INSTRUCTION_STOP_EPOCH_MISMATCH",Bi="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Am="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",pl="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Fi="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Wi="INSTRUCTION_STOP_REQUEST_FAILED",zi="HOST_SHUTDOWN_EPOCH_MISMATCH",Ki="HOST_SHUTDOWN_WORKSPACE_MISMATCH",Nm="HOST_SHUTDOWN_TARGET_PID_MISSING",Om="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",_l="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",vm="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var yl={};yp(yl,{CANONICAL_USER_STOP_ERROR:()=>la,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Ol,HOST_SHUTDOWN_TERMINAL_ERROR:()=>Sl,PENDING_ADOPT_GRACE_MS:()=>Nl,PID_NULL_REAP_GRACE_MS:()=>ga,RATED_TASK_EXCERPT_MAX_CHARS:()=>ha,RATED_TASK_LIST_MAX_LIMIT:()=>bl,TASK_HEARTBEAT_HARD_STALE_MS:()=>cl,TASK_HEARTBEAT_INTERVAL_MS:()=>al,TASK_HEARTBEAT_STALE_MS:()=>dl,TASK_RATINGS:()=>vl,TaskRatingError:()=>Gr,TaskRepository:()=>Wr,WORKFLOW_ANCHOR_TASK_KINDS:()=>zt,buildRatedTasksCountQuery:()=>xl,buildRatedTasksQuery:()=>Cl,countRatedTasks:()=>rk,hasRecordedUsage:()=>_a,isWorkflowAnchorTaskKind:()=>yr,listRatedTasks:()=>nk,mergeTerminalReason:()=>pa,resolveTaskHeartbeatHardStaleMs:()=>Go,resolveTaskHeartbeatIntervalMs:()=>Lr,resolveTaskHeartbeatStaleMs:()=>Xn,setTaskRating:()=>tk});function ut(t){return Dr(t)}function ra(t){return Dr(t)}function oa(){return or(...zt.map(t=>like(a.metadata,`%"kind":"${t}"%`)))}function Tl(){return and(...zt.map(t=>notLike(a.metadata,`%"kind":"${t}"%`)))}function ia(t=a.model,e=a.metadata){let n=sql`
|
|
94
|
+
CASE
|
|
95
|
+
WHEN ${t} LIKE 'claude-%' OR ${t} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
96
|
+
WHEN ${t} LIKE 'gpt-%' OR ${t} LIKE 'codex-%' THEN 'codex'
|
|
97
|
+
WHEN ${t} LIKE 'gemini-%' THEN 'gemini'
|
|
98
|
+
WHEN ${t} LIKE 'grok-%' THEN 'grok'
|
|
99
|
+
WHEN ${t} LIKE 'zai-%' OR ${t} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
100
|
+
WHEN ${t} LIKE 'minimax/%' THEN 'minimax'
|
|
101
|
+
WHEN ${t} LIKE 'qwen%' THEN 'qwen'
|
|
102
|
+
ELSE 'unknown'
|
|
103
|
+
END
|
|
104
|
+
`,r=sql`json_extract(${e}, '$.provider')`,o=sql`trim(${r})`,s=sql`substr(${o}, 1, instr(${o}, '/') - 1)`,i=sql`
|
|
105
|
+
CASE
|
|
106
|
+
WHEN instr(${o}, '/') > 0
|
|
107
|
+
AND ${s} IN ('cli', 'acp', 'api', 'plugin', 'remote')
|
|
108
|
+
THEN substr(${o}, instr(${o}, '/') + 1)
|
|
109
|
+
ELSE ${o}
|
|
110
|
+
END
|
|
111
|
+
`;return sql`
|
|
112
|
+
CASE
|
|
113
|
+
WHEN ${e} IS NULL THEN ${n}
|
|
114
|
+
WHEN json_valid(${e}) = 0 THEN 'unknown'
|
|
115
|
+
WHEN json_type(${e}, '$') IS NOT 'object' THEN 'unknown'
|
|
116
|
+
WHEN json_type(${e}, '$.provider') IS NULL THEN ${n}
|
|
117
|
+
WHEN json_type(${e}, '$.provider') IS NOT 'text' THEN 'unknown'
|
|
118
|
+
WHEN ${o} = '' THEN 'unknown'
|
|
119
|
+
WHEN trim(${i}) = '' THEN 'unknown'
|
|
120
|
+
ELSE ${i}
|
|
121
|
+
END
|
|
122
|
+
`}function zm(t){let e={status:t.status,metadata:t.metadata},n=De(e);return n==="stopped"||n==="failed"&&dt(e)==="runner_lost"}function Br(t){return sql`${t} NOT IN (${sql.join(Km.map(e=>sql`${e}`),sql`, `)})`}function Ko(t){let e=sql`
|
|
123
|
+
CASE
|
|
124
|
+
WHEN json_valid(${t}) = 1
|
|
125
|
+
THEN json_extract(${t}, '$.usageAccounting')
|
|
126
|
+
ELSE NULL
|
|
127
|
+
END
|
|
128
|
+
`;return sql`
|
|
129
|
+
COALESCE(SUM(
|
|
130
|
+
CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
|
|
131
|
+
), 0)
|
|
132
|
+
`}function Rn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ge(t){if(!t)return {};try{let e=JSON.parse(t);return Rn(e)?{...e}:{}}catch{return {}}}function Qo(t){return t==null||t===""}function Jo(t,e){return Qo(t)&&!Qo(e)?e:t}function Jm(t,e){let n=ge(t);if(!e)return n;for(let[r,o]of Object.entries(e))Qo(n[r])&&!Qo(o)&&(n[r]=o);return n}function Vo(t,e){let n=t.origin&&Il.has(t.origin)?t.origin:"internal",r=t.callerPid!==void 0&&Number.isInteger(t.callerPid)&&t.callerPid>0?t.callerPid:process.pid;return {origin:n,at:t.at??e,callerPid:r,...t.callerTaskId?{callerTaskId:t.callerTaskId}:{}}}function Vm(t){let e=ge(t).stopRequest;if(Rn(e)&&!(typeof e.origin!="string"||!Il.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function wl(){return or(isNull(a.stop_requested_at),ne(sql`COALESCE(${a.stop_requested_epoch}, 0)`,sql`COALESCE(${a.run_epoch}, 0)`))}function pa(t,e){let n=ge(t??null);return n.terminalReason=e,JSON.stringify(n)}function da(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==la&&(n[jm]=e),{error:la,metadata:n}}function Se(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function _a(t){return Se(t.input_tokens)!==0||Se(t.output_tokens)!==0||Se(t.cached_input_tokens)!==0||Se(t.cost_usd)!==0}function V(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function El(t){return {inputTokens:Se(t.inputTokens??0),outputTokens:Se(t.outputTokens??0),cachedInputTokens:Se(t.cachedInputTokens??0),costUsd:Se(t.costUsd??0)}}function Al(t){if(Rn(t))return {inputTokens:Se(t.inputTokens),outputTokens:Se(t.outputTokens),cachedInputTokens:Se(t.cachedInputTokens),costUsd:Se(t.costUsd)}}function Fr(t){if(!Rn(t))return;let e=t.accounting;return e==="recorded"||e==="partial"||e==="unavailable"?e:void 0}function fa(t){return t.inputTokens!==0||t.outputTokens!==0||t.cachedInputTokens!==0||t.costUsd!==0}function Xm(t){let e=Fr(t);if(e==="recorded"||e==="partial")return true;if(e==="unavailable")return false;let n=Al(t);return n!==void 0&&fa(n)}function Ym(t){return Object.values(t).some(e=>{let n=Fr(e);return n==="partial"||n==="unavailable"})}function Qm(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){if(Fr(n)==="unavailable")continue;let r=Al(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Xo(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}function ca(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return null;let n=mc(t,e);return n.status==="found"?new Date(n.startedAtMs).toISOString():null}function er(t,e){if(typeof t!="string"||t.length===0)throw new f("VALIDATION",`${e} is required`);return t}function ma(t,e){let n=Date.parse(t);if(!Number.isFinite(n))throw new f("VALIDATION",`${e} is not a valid ISO time: ${t}`);return new Date(n).toISOString()}function tk(t,e){let n=er(e.workspaceId,"workspaceId"),r=er(e.taskId,"taskId"),o=e.rating;if(o!==null&&!vl.includes(o))throw new f("VALIDATION","rating must be 'up', 'down' or null");let s=e.now===void 0?new Date().toISOString():ma(e.now,"now");try{return t.transaction(i=>{let c=and(eq(a.id,r),eq(a.workspace_id,n),inArray(a.status,[...En])),d=i.update(a).set({rating:o,rated_at:o===null?null:s}).where(and(c,sql`${a.rating} IS NOT ${o}`)).returning({rating:a.rating,ratedAt:a.rated_at}).all();if(d.length>0)return {taskId:r,rating:d[0].rating,ratedAt:d[0].ratedAt,changed:!0};let u=i.select({status:a.status,rating:a.rating,rated_at:a.rated_at}).from(a).where(and(eq(a.id,r),eq(a.workspace_id,n))).limit(1).get();if(!u)throw new Gr("TASK_NOT_FOUND",r);if(!ek.has(u.status))throw new Gr("TASK_RATING_NOT_TERMINAL",r);return {taskId:r,rating:u.rating,ratedAt:u.rated_at,changed:!1}},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to set task rating",i)}}function Cl(t){let e=sql`
|
|
133
|
+
SELECT id, rated_at FROM tasks
|
|
134
|
+
WHERE workspace_id = ${t.workspaceId}
|
|
135
|
+
AND rating IS NOT NULL
|
|
136
|
+
${t.agentId!==void 0?sql`AND agent_id = ${t.agentId}`:sql``}
|
|
137
|
+
${t.sinceIso!==void 0?sql`AND rated_at >= ${t.sinceIso}`:sql``}
|
|
138
|
+
ORDER BY rated_at DESC, id DESC
|
|
139
|
+
LIMIT ${t.limit}
|
|
140
|
+
`;return sql`
|
|
141
|
+
SELECT t.id AS taskId, t.agent_id AS agentId, t.thread_id AS threadId, t.status AS status,
|
|
142
|
+
substr(t.error, 1, ${Zm}) AS errorHead,
|
|
143
|
+
CASE WHEN json_valid(t.metadata) THEN json_extract(t.metadata, '$.terminalReason') END AS terminalReason,
|
|
144
|
+
t.rating AS rating, t.rated_at AS ratedAt,
|
|
145
|
+
NULLIF(substr(t.prompt, 1, ${ha}), '') AS promptExcerpt,
|
|
146
|
+
NULLIF(substr(t.result, 1, ${ha}), '') AS resultExcerpt
|
|
147
|
+
FROM (${e}) AS page
|
|
148
|
+
JOIN tasks t ON t.id = page.id
|
|
149
|
+
ORDER BY page.rated_at DESC, page.id DESC
|
|
150
|
+
`}function nk(t,e){let n=er(e.workspaceId,"workspaceId");if(e.agentId!==void 0&&er(e.agentId,"agentId"),!Number.isFinite(e.limit)||Math.trunc(e.limit)<1)throw new f("VALIDATION","limit must be a positive integer");let r=Math.min(Math.trunc(e.limit),bl),o=e.sinceIso===void 0?void 0:ma(e.sinceIso,"sinceIso");try{return t.all(Cl({workspaceId:n,agentId:e.agentId,sinceIso:o,limit:r})).map(i=>({taskId:i.taskId,agentId:i.agentId,threadId:i.threadId,status:De({status:i.status,error:i.errorHead,metadata:i.terminalReason===null?null:JSON.stringify({terminalReason:i.terminalReason})}),rating:i.rating,ratedAt:i.ratedAt,promptExcerpt:i.promptExcerpt,resultExcerpt:i.resultExcerpt}))}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to list rated tasks",s)}}function xl(t){return sql`
|
|
151
|
+
SELECT COUNT(*) AS total FROM tasks
|
|
152
|
+
WHERE workspace_id = ${t.workspaceId}
|
|
153
|
+
AND rating IS NOT NULL
|
|
154
|
+
${t.agentId!==void 0?sql`AND agent_id = ${t.agentId}`:sql``}
|
|
155
|
+
${t.sinceIso!==void 0?sql`AND rated_at >= ${t.sinceIso}`:sql``}
|
|
156
|
+
`}function rk(t,e){let n=er(e.workspaceId,"workspaceId");e.agentId!==void 0&&er(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:ma(e.sinceIso,"sinceIso");try{return t.all(xl({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to count rated tasks",o)}}var sa,Yn,Wm,Qn,Zn,Gm,aa,qr,et,la,Sl,jm,Km,Il,ga,Nl,Ol,Wr,vl,ha,bl,Zm,Gr,ek,ta=C(()=>{g();vt();Bt();Ft();Ot();jt();mo();yo();uc();Eo();Ic();Nc();Li();Jn();$r();ea();$r();mo();sa=40,Yn="2026-05-09",Wm="0.8.9-rc.13",Qn=10,Zn=parseInt(Wm.split("rc.")[1]);Gm=new Set(["workflow","mcp"]),aa="usageByEpoch",qr="lateUsage",et="usageAccounting",la="Stopped by user",Sl="Stopped by app shutdown",jm="terminalErrorOriginal";Km=["pending","running"];Il=new Set(["http","cli","instruction","workflow","internal"]);ga=600*1e3,Nl=600*1e3,Ol=300*1e3;Wr=class extends ke{dbPath;clock;taskLogRepository;processControl;lastReaperTickAt;orphanReapInFlight;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),this.processControl=e.processControl??{},e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Ro({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?sn(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new f("NOT_FOUND","Database not found");let r=U(n);if(e)try{Le(r.db,n);}catch(o){throw r.close(),o}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=V(e.runEpoch),o=r===0?or(eq(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(and(eq(a.id,e.id),o,eq(a.status,"running"))).run().changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!s)return;let i=V(s.run_epoch);if(s.status!=="running"){r={accepted:!1,status:s.status,runEpoch:i};return}let c=s.stop_requested_at!==null&&V(s.stop_requested_epoch)===i,d=c?s.stop_requested_at:e.requestedAt,u=ge(s.metadata),l=c?Vm(s.metadata)??Vo({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):Vo({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...u,stopRequest:l})}).where(and(eq(a.id,e.id),eq(a.status,"running"),wl())).run().changes===0){let m=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:V(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:V(m.run_epoch),...m.stop_requested_at&&V(m.stop_requested_epoch)===V(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:s.status,runEpoch:i};let _=new Set([e.id]),h=(m,k)=>{if(k>=8)return;let w=o.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(and(eq(a.parent_task_id,m),eq(a.status,"running"))).all();for(let x of w)_.has(x.id)||(_.add(x.id),o.update(a).set({stop_requested_at:d,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...ge(x.metadata),stopRequest:l})}).where(and(eq(a.id,x.id),eq(a.status,"running"),wl())).run(),h(x.id,k+1));};h(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!s)return;let i=V(s.run_epoch),c=V(e.sourceRunEpoch),d=V(e.settleRunEpoch);if(s.status!=="running"||i!==d||e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId){r={accepted:!1,status:s.status,runEpoch:i};return}let u=d===0?or(eq(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,d),l=or(isNull(a.stop_requested_at),isNull(a.stop_requested_epoch),ne(a.stop_requested_epoch,c)),p=Vo({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),_=JSON.stringify({...ge(s.metadata),stopRequest:p}),h=T=>o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:c,metadata:_}).where(and(eq(a.id,e.id),eq(a.status,"running"),u,T,l)).returning({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).all(),k=(e.workspaceId===void 0?h():e.workspaceId===null?h(isNull(a.workspace_id)):h(eq(a.workspace_id,e.workspaceId)))[0];if(k){if(k.stop_requested_at===null||k.stop_requested_epoch===null||k.metadata===null)throw new Error("Instruction stop request write returned incomplete fields");r={accepted:!0,status:k.status,runEpoch:V(k.run_epoch),stopRequestReceipt:{taskId:k.id,workspaceId:k.workspace_id,sourceRunEpoch:c,settleRunEpoch:V(k.run_epoch),stopRequestedAt:k.stop_requested_at,stopRequestedEpoch:V(k.stop_requested_epoch),metadataBefore:s.metadata,metadataAfter:k.metadata}};return}let w=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!w||w.status!=="running"){r={accepted:!1,status:w?.status??"not_running",runEpoch:V(w?.run_epoch)};return}let x=V(w.run_epoch);r={accepted:!1,status:w.status,runEpoch:x,...w.stop_requested_at&&V(w.stop_requested_epoch)===c?{alreadyRequestedAt:w.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=!1;return n.db.transaction(s=>{let i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||V(i.run_epoch)!==V(e.runEpoch))return;let c=i.stop_requested_at!==null&&V(i.stop_requested_epoch)===V(e.runEpoch),d=ge(i.metadata),u=c?da(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...u.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??Xo(i.started_at,r,void 0),_=i.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,i.run_epoch);o=s.update(a).set({status:"stopped",error:u.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(and(eq(a.id,e.id),eq(a.status,"running"),_)).run().changes>0;},{behavior:"immediate"}),o}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=V(e.expectedRunEpoch),s="not_running";return n.db.transaction(i=>{let c=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!c||c.status!=="running"){s="not_running";return}if(V(c.run_epoch)!==o){s="epoch_mismatch";return}if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId){s="workspace_mismatch";return}let u=c.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,c.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?isNull(a.workspace_id):eq(a.workspace_id,e.workspaceId),p={...ge(c.metadata),terminalReason:"runner_lost"},_=c.duration_ms??Xo(c.started_at,r,void 0);s=i.update(a).set({status:"failed",error:Sl,completed_at:r,duration_ms:_,metadata:JSON.stringify(p)}).where(and(eq(a.id,e.id),eq(a.status,"running"),u,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),s}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return kl(this,e,n)}async stopTaskGenerationForInstruction(e){return hl({requestTaskStop:n=>this.requestTaskStopForInstruction(n),getTask:n=>this.getTask(n),finalizeTaskStop:n=>this.finalizeTaskStop(n)},e)}startTask(e){let n=this.openHandle(true);try{let r=e.actorKind==="human"&&typeof e.workspaceId=="string"&&e.workspaceId.length>0&&typeof e.actorId=="string"&&e.actorId.length>0,o=r?n.db.select({id:a.id}).from(a).where(eq(a.id,e.id)).get()!==void 0:!0,s={id:e.id,agent_id:e.agentId,actor_kind:e.actorKind??null,actor_id:e.actorId??null,user_id:e.userId??null,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,pid_started_at:ca(e.pid,this.processControl),parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workflow_run_id:rc(e.metadata),schedule_id:cc(e.metadata),workspace_id:e.workspaceId??null,cwd:e.cwd??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,security_key:e.securityKey??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},i=c=>{n.db.insert(a).values(c).onConflictDoUpdate({target:a.id,set:{status:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:sql`COALESCE(excluded.pid, ${a.pid})`,pid_started_at:sql`CASE WHEN excluded.pid IS NULL THEN ${a.pid_started_at} ELSE excluded.pid_started_at END`,actor_kind:sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_kind ELSE ${a.actor_kind} END`,actor_id:sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_id ELSE ${a.actor_id} END`,command:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workflow_run_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.workflow_run_id ELSE ${a.workflow_run_id} END`,schedule_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.schedule_id ELSE ${a.schedule_id} END`,workspace_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.workspace_id}, excluded.workspace_id) ELSE ${a.workspace_id} END`,cwd:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.project_id}, excluded.project_id) ELSE ${a.project_id} END`,crewx_version:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,security_key:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.security_key ELSE ${a.security_key} END`,coding_agent_command:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:or(eq(a.status,"running"),and(eq(a.status,"pending"),isNull(a.pid)))}).run();};try{i(s);}catch(c){let d=c instanceof Error?c.message:typeof c=="object"&&c!==null&&"message"in c?String(c.message):String(c);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|pid_started_at|cwd|actor_kind|actor_id/i.test(d)||!/no such column|no column named/i.test(d))throw c;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(on=>on.name)),l=u.has("cwd"),p=u.has("user_id"),_=u.has("actor_kind"),h=u.has("actor_id"),m=u.has("log_storage"),k=l?", cwd":"",w=l?", ?":"",x=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",T=m?", log_storage":"",L=m?", ?":"",N=p?", user_id":"",D=p?", ?":"",A=_?", actor_kind":"",J=_?", ?":"",oe=h?", actor_id":"",qe=h?", ?":"",Ae=m?`,
|
|
157
|
+
log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
|
|
158
|
+
id, agent_id, prompt, mode, status, started_at, pid,
|
|
159
|
+
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
160
|
+
workspace_id${k}, project_id, platform, crewx_version, thread_id,
|
|
161
|
+
model, rendered_prompt, coding_agent_command${N}${A}${oe}${T}
|
|
162
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${w}${D}${J}${qe}${L})
|
|
163
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
164
|
+
status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
|
|
165
|
+
pid = COALESCE(excluded.pid, tasks.pid),
|
|
166
|
+
command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.command ELSE tasks.command END,
|
|
167
|
+
metadata = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.metadata ELSE tasks.metadata END,
|
|
168
|
+
workspace_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.workspace_id, excluded.workspace_id) ELSE tasks.workspace_id END${x},
|
|
169
|
+
project_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.project_id, excluded.project_id) ELSE tasks.project_id END,
|
|
170
|
+
crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
|
|
171
|
+
model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
|
|
172
|
+
rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
|
|
173
|
+
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${Ae}
|
|
174
|
+
WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[s.id,s.agent_id,s.prompt,s.mode,s.status,s.started_at,s.pid,s.parent_task_id,s.caller_agent_id,s.trace_id,s.command,s.metadata,s.workspace_id,...l?[s.cwd]:[],s.project_id,s.platform,s.crewx_version,s.thread_id,s.model,s.rendered_prompt,s.coding_agent_command,...p?[s.user_id]:[],..._?[s.actor_kind]:[],...h?[s.actor_id]:[],...m?[s.log_storage]:[]]);}r&&!o&&new So({dbPath:this.resolveDbPath()}).recordAccepted({workspaceId:e.workspaceId,actorId:e.actorId,actorKind:e.actorKind,agentId:e.agentId});}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to start task",r)}finally{n.close();}}recordTaskPid(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:a.status,run_epoch:a.run_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||V(r.run_epoch)!==V(e.runEpoch))return !1;let o=r.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,r.run_epoch);return n.db.update(a).set({pid:e.pid,pid_started_at:ca(e.pid,this.processControl)}).where(and(eq(a.id,e.id),eq(a.status,"running"),o)).run().changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to record task pid",r)}finally{n.close();}}updateTaskOwnership(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:a.status,run_epoch:a.run_epoch,metadata:a.metadata,model:a.model,rendered_prompt:a.rendered_prompt,security_key:a.security_key,coding_agent_command:a.coding_agent_command}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||V(r.run_epoch)!==V(e.runEpoch))return !1;let o=Jm(r.metadata,e.runtime?.metadata);if(o.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0){o.providerPid=e.providerPid;let c=ca(e.providerPid,this.processControl);c!==null?o.providerPidStartedAt=c:delete o.providerPidStartedAt;}let s=r.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,r.run_epoch),i=n.db.update(a).set({metadata:JSON.stringify(o),model:Jo(r.model,e.runtime?.model),rendered_prompt:Jo(r.rendered_prompt,e.runtime?.renderedPrompt),security_key:Jo(r.security_key,e.runtime?.securityKey),coding_agent_command:Jo(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(and(eq(a.id,e.id),eq(a.status,"running"),s)).run();return i.changes>0&&V(e.runEpoch)>0&&n.db.update(a).set({stop_requested_at:null,stop_requested_epoch:null}).where(and(eq(a.id,e.id),eq(a.status,"running"),s,sql`${a.stop_requested_at} IS NOT NULL
|
|
175
|
+
AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(a).set({status:"running"}).where(and(eq(a.id,e),eq(a.status,"pending"),isNull(a.pid))).run().changes===1}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let o=this.openHandle(true);try{return o.db.update(a).set({status:"failed",error:n,completed_at:r}).where(and(eq(a.id,e),eq(a.status,"pending"))).run().changes>0}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to fail pending task",s)}finally{o.close();}}stopPendingTask(e,n,r=new Date().toISOString(),o={}){let s=this.openHandle(true);try{let i=!1;return s.db.transaction(c=>{let d=c.select({metadata:a.metadata}).from(a).where(and(eq(a.id,e),eq(a.status,"pending"))).limit(1).get();if(!d)return;let u=da(ge(d.metadata),n),l={...u.metadata,stopMethod:"cooperative",stopRequest:Vo(o,r)};i=c.update(a).set({status:"stopped",error:u.error,completed_at:r,metadata:JSON.stringify(l)}).where(and(eq(a.id,e),eq(a.status,"pending"))).run().changes===1;},{behavior:"immediate"}),i}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to stop pending task",i)}finally{s.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select(pe).from(a).where(eq(a.project_id,e)).orderBy(desc(a.started_at)).all().map(ut)}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true),r,o;try{n.db.transaction(s=>{let i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,result:a.result,exit_code:a.exit_code,error:a.error,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!i)return;let c=V(i.run_epoch),d=V(e.runEpoch),u=i.status==="running"&&c===d,l=i.stop_requested_at!==null&&V(i.stop_requested_epoch)===c,p=u&&l,_=i.status==="stopped"&&c===d&&l,h=ge(i.metadata),m=Rn(h[qr])?h[qr]:{},k=String(d),w=zm(i),x=w&&c===d&&!_a(i)&&!Object.prototype.hasOwnProperty.call(m,k),T=w&&c===d&&!Object.prototype.hasOwnProperty.call(m,k),L=c>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||e.usageComplete!==void 0||c!==d,N={},D;if(i.status!=="running"&&(r=i.status,o=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),L&&(i.status==="running"||T)){D=ge(i.metadata);let A=Rn(D[aa])?{...D[aa]}:{},J=String(d),oe=El(e),qe=Fr(A[J]);e.usageComplete!==void 0?A[J]={...oe,accounting:e.usagePresent===!0?e.usageComplete?"recorded":"partial":"unavailable"}:qe!==void 0?A[J]={...oe,accounting:qe}:A[J]=oe,D[aa]=A;let Ae=Qm(A),on=fa(Ae),eo=Object.values(A).some(Xm),hp=Object.values(A).some(mp=>Fr(mp)!==void 0);e.usageComplete!==void 0||hp?(D[et]=eo?"recorded":"unavailable",Ym(A)?D.usageIncomplete=!0:delete D.usageIncomplete):on&&h[et]==="unavailable"?D[et]="recorded":i.status!=="running"&&!on&&h[et]===void 0&&(D[et]="unavailable"),N.metadata=JSON.stringify(D),N.input_tokens=Ae.inputTokens,N.output_tokens=Ae.outputTokens,N.cached_input_tokens=Ae.cachedInputTokens,N.cost_usd=Ae.costUsd;}else if(u||x)if(u)N.input_tokens=Se(e.inputTokens??0),N.output_tokens=Se(e.outputTokens??0),N.cached_input_tokens=Se(e.cachedInputTokens??0),N.cost_usd=Se(e.costUsd??0);else {let A=El(e),J=e.usageComplete!==void 0?e.usagePresent===!0:fa(A);J&&(N.input_tokens=A.inputTokens,N.output_tokens=A.outputTokens,N.cached_input_tokens=A.cachedInputTokens,N.cost_usd=A.costUsd),D={...h};let oe=Rn(h[qr])?{...h[qr]}:{};oe[k]={at:e.completedAt},D[qr]=oe,D[et]===void 0?D[et]=J?"recorded":"unavailable":J&&D[et]==="unavailable"&&(D[et]="recorded"),N.metadata=JSON.stringify(D);}if((u||x)&&e.model!==void 0&&e.model!==null&&(!x||i.model===null)&&(N.model=e.model),p){D??=ge(i.metadata);let A=da(D,e.error);D={...A.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:zo(i.stop_requested_at,e.completedAt)},N.status="stopped",N.result=e.result??i.result,N.error=A.error,N.completed_at=e.completedAt,N.duration_ms=i.duration_ms??e.durationMs??Xo(i.started_at,e.completedAt,void 0),N.exit_code=e.exitCode??i.exit_code,N.metadata=JSON.stringify(D);}else if(u)e.partialResultRecovered===!0&&(D??=ge(i.metadata),D.partialResultRecovered=!0,N.metadata=JSON.stringify(D)),N.status=e.status,N.result=e.result??null,N.error=e.error??null,N.completed_at=e.completedAt,N.duration_ms=c>0?Xo(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,N.exit_code=e.exitCode??null;else if(_){let A=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(N.result=e.result,A=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(N.exit_code=e.exitCode),e.partialResultRecovered===!0&&(D??=ge(i.metadata),D.partialResultRecovered=!0,N.metadata=JSON.stringify(D)),A&&(r=void 0,o=void 0);}Object.keys(N).length>0&&s.update(a).set(N).where(eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to finish task",s)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:o??`task:end status=${e.status}`});}catch(s){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${s instanceof Error?s.message:String(s)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
|
|
176
|
+
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=and(eq(a.id,e.id),eq(a.workspace_id,e.workspaceId)),o={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let s=n.db.select({metadata:a.metadata}).from(a).where(r).limit(1).get(),i=ge(s?.metadata??null);i.terminalReason=e.terminalReason,o.metadata=JSON.stringify(i);}n.db.update(a).set(o).where(r).run();}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task lifecycle",r)}finally{n.close();}}appendLog(e,n){this.taskLogRepository.appendLog(e,n);}appendLogs(e,n){this.taskLogRepository.appendLogs(e,n);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,n){return this.taskLogRepository.readLogsTail(e,n)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(pe).from(a).where(eq(a.status,"running")).orderBy(desc(a.started_at)).all().map(ut)}catch(n){throw new f("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getActiveTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(pe).from(a).where(inArray(a.status,["pending","running"])).orderBy(desc(a.started_at)).all().map(ut)}catch(n){throw new f("DB_ERROR","Failed to get active tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(pe).from(a).orderBy(desc(a.started_at)).limit(100).all().map(ut)}catch(n){throw new f("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}readTaskSecurityKey(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({security_key:a.security_key}).from(a).where(eq(a.id,e)).limit(1).get()?.security_key??null}catch(r){throw new f("DB_ERROR","Failed to read task security key",r)}finally{n.close();}}recordProviderInput(e){if(!this.dbExists())return false;let n=V(e.runEpoch);if(n===0&&e.interceptedRequest!==true)return false;let r=e.recordedAt??new Date(this.clock()).toISOString(),o=this.openHandle(true);try{let s=!1;return o.db.transaction(i=>{let c=i.select({run_epoch:a.run_epoch}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!c||V(c.run_epoch)!==n)return;s=i.insert(bt).values({task_id:e.id,run_epoch:n,input:e.input,key_wrap_skipped:e.keyWrapSkipped?1:0,recorded_at:r}).onConflictDoNothing().run().changes>0;}),s}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to record provider input",s)}finally{o.close();}}listProviderInputEpochs(e,n={}){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({run_epoch:a.run_epoch}).from(a).where(eq(a.id,e)).limit(1).get();if(!o)return [];let s=V(o.run_epoch),i=r.db.select({run_epoch:bt.run_epoch,key_wrap_skipped:bt.key_wrap_skipped}).from(bt).where(eq(bt.task_id,e)).all(),c=new Map(i.map(u=>[u.run_epoch,u])),d=[];for(let u=1;u<=s;u++){let l=c.get(u);l?d.push({runEpoch:u,available:!0,...l.key_wrap_skipped===1?{keyWrapSkipped:!0}:{}}):d.push({runEpoch:u,available:!1,reason:n.archivedRunEpochs?.has(u)?"pruned":"absent"});}return d}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to list provider inputs",o)}finally{r.close();}}readProviderInput(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let o=r.db.select().from(bt).where(and(eq(bt.task_id,e),eq(bt.run_epoch,V(n)))).limit(1).get();return o?{runEpoch:o.run_epoch,input:o.input,keyWrapSkipped:o.key_wrap_skipped===1,recordedAt:o.recorded_at}:void 0}catch(o){throw new f("DB_ERROR","Failed to read provider input",o)}finally{r.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select(pe).from(a).where(eq(a.id,e)).limit(1).get();return r?ut(r):void 0}catch(r){throw new f("DB_ERROR","Failed to get task",r)}finally{n.close();}}async killTask(e){let n=await this.stopTask(e);return n.status==="stopped"?{status:"terminated",killed:n.method==="forced"||n.method==="cooperative",...n.pid?{pid:n.pid}:{}}:n.status==="not_running"?{status:"not_running",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}:{status:"failed",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}}reapOrphanedTasks(e={}){return this.orphanReapInFlight===void 0&&(this.orphanReapInFlight=this.runOrphanReaperPass(e).finally(()=>{this.orphanReapInFlight=void 0;})),this.orphanReapInFlight}async runOrphanReaperPass(e){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=n.db.select({id:a.id,status:a.status,pid:a.pid,pid_started_at:a.pid_started_at,platform:a.platform,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at,started_at:a.started_at,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(or(eq(a.status,"running"),eq(a.status,"pending"))).all(),o=this.clock(),s=Math.max(1,Math.trunc(e.tickIntervalMs??Ol)),i=this.lastReaperTickAt,c=i===void 0?Number.POSITIVE_INFINITY:o-i,d=i!==void 0&&c>=0&&c<=s*2;this.lastReaperTickAt=o;let u=Xn(),l=Go(),p=new Date(o-Nl).toISOString(),_=new Date(o).toISOString(),h=new Set,m=[],k=0,w=(T,L)=>{let N=ge(pa(T.metadata,"runner_lost")),D=typeof N.provider=="string"?N.provider:void 0,A;try{A=Fo({taskLogRepository:this.taskLogRepository,taskId:T.id,provider:D,model:T.model})?.usage;}catch{}let J={status:"failed",error:L,completed_at:_};A?(J.input_tokens=A.inputTokens,J.output_tokens=A.outputTokens,J.cached_input_tokens=A.cachedInputTokens,J.cost_usd=A.costUsd,T.model===null&&A.model!==null&&(J.model=A.model),N[et]="recorded"):!_a(T)&&N[et]!=="recorded"&&(N[et]="unavailable"),J.metadata=JSON.stringify(N);let oe=T.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,T.run_epoch),qe=T.heartbeat_at===null?isNull(a.heartbeat_at):eq(a.heartbeat_at,T.heartbeat_at),Ae=n.db.update(a).set(J).where(and(eq(a.id,T.id),eq(a.status,"running"),oe,qe)).run();return Ae.changes>0&&k++,Ae.changes>0};for(let T of r){if(T.status==="pending"){if(T.pid!==null||T.started_at>=p)continue;let A=pa(T.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:_,metadata:A}).where(and(eq(a.id,T.id),eq(a.status,"pending"),isNull(a.pid),lt(a.started_at,p))).run().changes>0&&k++;continue}if(Gm.has(T.platform??"cli"))continue;if(T.pid===null){let A=`${T.id}:${T.run_epoch??0}`;h.add(A);let J=this.pidNullObservedSince.get(A);if(J===void 0){this.pidNullObservedSince.set(A,o);continue}o-J>=ga&&w(T,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(A);continue}if(T.heartbeat_at===null){Kt(T.pid,this.processControl.kill)==="not_found"&&w(T,"Reaped: process not found (orphaned task)");continue}let L=Date.parse(T.heartbeat_at),N=Number.isFinite(L)?o-L:Number.POSITIVE_INFINITY;if(N<=u)continue;let D=Yi(T).filter(A=>Kt(A.pid,this.processControl.kill)!=="not_found");D.length===0?w(T,"Reaped: process not found (orphaned task)"):N>l&&d&&m.push({row:T,targets:D});}let x=new Map;for(let T of m){let{row:L,targets:N}=T,D=n.db.select({status:a.status,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at}).from(a).where(eq(a.id,L.id)).get();if(!D||D.status!=="running"||V(D.run_epoch)!==V(L.run_epoch)||D.heartbeat_at!==L.heartbeat_at)continue;let A=await this.judgeRecordedTargets(L,N);if(A.unproven!==void 0){console.warn("[crewx] reaper left running task",{taskId:L.id,reason:A.unproven});continue}if(A.owned.length>0){let J=await this.terminateRecordedProcesses(A.owned,x);if(J!==void 0){console.warn("[crewx] reaper left running task",{taskId:L.id,reason:J});continue}}w(L,"Reaped: heartbeat stale beyond hard limit (orphaned task)")&&A.reused.length>0&&console.warn("[crewx] reaper reaped task whose recorded pid was reused",{taskId:L.id,reason:A.reused.join("; ")});}for(let T of Array.from(this.pidNullObservedSince.keys()))h.has(T)||this.pidNullObservedSince.delete(T);return k}finally{n.close();}}async judgeRecordedTargets(e,n){let r=e.heartbeat_at===null?Number.NaN:Date.parse(e.heartbeat_at),o=Number.isFinite(r)?r+Lr()+wo:void 0,s=[],i=[];for(let c of n){let d=await Qi(c,{processControlOptions:this.processControl,legacyStartBoundaryMs:o});if(d.verdict==="owned")s.push(c);else if(d.verdict==="reused")i.push(`pid ${c.pid} reused (${d.reason})`);else return {owned:s,reused:i,unproven:`pid ${c.pid} not proven owned (${d.ownership}): ${d.reason}`}}return {owned:s,reused:i}}async terminateRecordedProcesses(e,n){for(let r of e){if(!n.has(r.pid)){let o;try{o=(await Vt(r.pid,{...this.processControl,signal:Jt})).status==="failed"?"failed":"terminated";}catch{o="failed";}n.set(r.pid,o);}if(n.get(r.pid)==="failed")return `pid ${r.pid} termination not confirmed`;if(Kt(r.pid,this.processControl.kill)!=="not_found")return `pid ${r.pid} still alive after termination`}}reapRunningWorkflowTasks(e=ga){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),o=and(eq(a.status,"running"),eq(a.platform,"workflow"),isNull(a.pid),lt(a.started_at,r),or(isNull(a.metadata),Tl())),s=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(o).all(),i=new Date().toISOString(),c=0;for(let d of s){let u=ge(d.metadata);u.terminalReason="runner_lost";let l=n.db.update(a).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:i,metadata:JSON.stringify(u)}).where(and(eq(a.id,d.id),eq(a.status,"running"))).run();c+=l.changes??0;}return c}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=U(o);try{let i=n?eq(a.workspace_id,n):void 0,c=i?and(eq(a.id,e),i):eq(a.id,e),d=s.db.select(pe).from(a).where(c).limit(1).get()??void 0;if(!d){let u=i?and(eq(a.thread_id,e),i):eq(a.thread_id,e);d=s.db.select(pe).from(a).where(u).orderBy(desc(a.started_at)).limit(1).get()??void 0;}if(d)return ut(d)}catch(i){throw new f("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=U(i);try{let d=n?and(eq(a.parent_task_id,e),eq(a.workspace_id,n)):eq(a.parent_task_id,e),u=c.db.select(pe).from(a).where(d).orderBy(asc(a.started_at)).all();for(let l of u)o.has(l.id)||(o.add(l.id),s.push(ut(l)));}catch(d){throw new f("DB_ERROR","Failed to find child tasks",d)}finally{c.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?sql`
|
|
17
177
|
SELECT
|
|
18
178
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
19
179
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -21,7 +181,7 @@ ${n.join(`
|
|
|
21
181
|
COALESCE(SUM(cost_usd), 0) AS cost_usd,
|
|
22
182
|
COUNT(*) AS task_count
|
|
23
183
|
FROM tasks
|
|
24
|
-
WHERE workspace_id = ${
|
|
184
|
+
WHERE workspace_id = ${e}
|
|
25
185
|
GROUP BY workspace_id
|
|
26
186
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
27
187
|
`:sql`
|
|
@@ -34,103 +194,45 @@ ${n.join(`
|
|
|
34
194
|
FROM tasks
|
|
35
195
|
GROUP BY workspace_id
|
|
36
196
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
37
|
-
`)}catch(
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
t.
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
ORDER BY (
|
|
65
|
-
COALESCE(SUM(
|
|
66
|
-
COALESCE(t.input_tokens, 0)
|
|
67
|
-
+ CASE
|
|
68
|
-
WHEN t.started_at >= ${B}
|
|
69
|
-
AND (
|
|
70
|
-
t.crewx_version IS NULL
|
|
71
|
-
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
72
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${z}) AS INTEGER) < ${q})
|
|
73
|
-
)
|
|
74
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
75
|
-
ELSE 0
|
|
76
|
-
END
|
|
77
|
-
), 0)
|
|
78
|
-
+ COALESCE(SUM(t.output_tokens), 0)
|
|
79
|
-
) DESC
|
|
80
|
-
`:sql`
|
|
81
|
-
SELECT
|
|
82
|
-
t.agent_id,
|
|
83
|
-
t.workspace_id,
|
|
84
|
-
COUNT(*) AS total_tasks,
|
|
85
|
-
COALESCE(SUM(
|
|
86
|
-
COALESCE(t.input_tokens, 0)
|
|
87
|
-
+ CASE
|
|
88
|
-
WHEN t.started_at >= ${B}
|
|
89
|
-
AND (
|
|
90
|
-
t.crewx_version IS NULL
|
|
91
|
-
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
92
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${z}) AS INTEGER) < ${q})
|
|
93
|
-
)
|
|
94
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
95
|
-
ELSE 0
|
|
96
|
-
END
|
|
97
|
-
), 0) AS input_tokens,
|
|
98
|
-
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
99
|
-
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
100
|
-
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
101
|
-
FROM tasks t
|
|
102
|
-
WHERE t.status IN ('completed', 'success')
|
|
103
|
-
AND t.started_at >= ${t}
|
|
104
|
-
AND t.started_at < ${e}
|
|
105
|
-
GROUP BY t.agent_id, t.workspace_id
|
|
106
|
-
ORDER BY (
|
|
107
|
-
COALESCE(SUM(
|
|
108
|
-
COALESCE(t.input_tokens, 0)
|
|
109
|
-
+ CASE
|
|
110
|
-
WHEN t.started_at >= ${B}
|
|
111
|
-
AND (
|
|
112
|
-
t.crewx_version IS NULL
|
|
113
|
-
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
114
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${z}) AS INTEGER) < ${q})
|
|
115
|
-
)
|
|
116
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
117
|
-
ELSE 0
|
|
118
|
-
END
|
|
119
|
-
), 0)
|
|
120
|
-
+ COALESCE(SUM(t.output_tokens), 0)
|
|
121
|
-
) DESC
|
|
122
|
-
`).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(o){throw new _("DB_ERROR","Failed to get agent usage",o)}finally{s.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
|
|
197
|
+
`)}catch(r){throw new f("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,c=0;for(let d of r){if(!existsSync(d))continue;let u=U(d);try{let l=eq(a.thread_id,e),p=n?and(l,eq(a.workspace_id,n)):l,_=u.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(p).all();for(let h of _)o.has(h.id)||(o.add(h.id),s+=h.input_tokens??0,i+=h.output_tokens??0,c+=h.cost_usd??0);}catch(l){throw new f("DB_ERROR","Failed to get thread token usage",l)}finally{u.close();}}return {inputTokens:s,outputTokens:i,costUsd:c}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],c=r?.projection==="activity-log";for(let d of o){if(!existsSync(d))continue;let u=U(d);try{let l=eq(a.thread_id,e),p=n?and(l,eq(a.workspace_id,n)):l,_=c?u.db.select({id:a.id,thread_id:a.thread_id,agent_id:a.agent_id,parent_task_id:a.parent_task_id,started_at:a.started_at,completed_at:a.completed_at}).from(a).where(p).orderBy(asc(a.started_at)).all():u.db.select(pe).from(a).where(p).orderBy(asc(a.started_at)).all().map(ut);for(let h of _)s.has(h.id)||(s.add(h.id),i.push(h));}catch(l){throw new f("DB_ERROR","Failed to find tasks by thread",l)}finally{u.close();}}return i}parseWorkflowCardMetadata(e){if(!e)return {};try{let n=JSON.parse(e);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=U(n);try{e.push(...r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),inArray(a.status,["running","pending"]),oa())).orderBy(desc(a.started_at)).all().map(ra));}catch(o){throw new f("DB_ERROR","Failed to find workflow parent tasks",o)}finally{r.close();}}return e}findWorkflowParentTasksByWorkspace(e){let n=[],r=new Map;for(let o of this.resolveDbPaths()){if(!existsSync(o))continue;let s=U(o);try{let i=s.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),eq(a.workspace_id,e))).orderBy(desc(a.started_at),desc(a.id)).all();for(let c of i){let d=this.parseWorkflowCardMetadata(c.metadata);if(!yr(d.kind)||typeof d.workflowRunId!="string")continue;let u=d.kind,l=r.get(u)??new Set;l.has(d.workflowRunId)||(l.add(d.workflowRunId),r.set(u,l),n.push(ra(c)));}}catch(i){throw new f("DB_ERROR","Failed to find workflow parent tasks by workspace",i)}finally{s.close();}}return n}findWorkflowParentTask(e){if(this.dbExists())for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=U(n);try{let o=r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),eq(a.workspace_id,e.workspaceId))).orderBy(desc(a.started_at),desc(a.id)).all();for(let s of o){let i=this.parseWorkflowCardMetadata(s.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return ra(s)}}catch(o){throw new f("DB_ERROR","Failed to find workflow parent task",o)}finally{r.close();}}}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let o=new Set(e),s=new Map,i=n?eq(a.workspace_id,n):void 0,c=(d,u)=>{if(!d)return;let l=s.get(d);if(l&&u.started_at<=l)return;let p=this.parseWorkflowCardMetadata(u.metadata);yr(p.kind)&&(s.set(d,u.started_at),r.set(d,{taskId:u.id,workflowRunId:p.workflowRunId,raw:u.result??void 0}));};for(let d of this.resolveDbPaths()){if(!existsSync(d))continue;let u=U(d);try{let l=and(inArray(a.thread_id,e),oa()),p=u.db.select({id:a.id,thread_id:a.thread_id,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(l,i):l).all();for(let m of p)c(m.thread_id,m);let _=and(isNull(a.thread_id),oa()),h=u.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(_,i):_).all();for(let m of h){let k=this.extractThreadIdFromCommand(m.command);!k||!o.has(k)||c(k,m);}}catch(l){throw new f("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{u.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(a.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(inArray(a.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(inArray(a.status,$i(s)));let i=e.q??e.search;i&&r.push(like(a.prompt,`%${i}%`)),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt(a.started_at,e.to));let c=r.length>0?and(...r):void 0,d=n.db.select({count:sql`count(*)`}).from(a).where(c).get(),u=(e.sortDir??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at);return {rows:n.db.select(pe).from(a).where(c).orderBy(u).limit(e.limit).offset(e.offset).all().map(ut),total:d?.count??0}}catch(r){throw new f("DB_ERROR","Failed to find all tasks",r)}finally{n.close();}}getAgentUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=ia(sql.raw("t.model"),sql.raw("t.metadata")),i=Br(sql.raw("t.status")),c=Ko(sql.raw("t.metadata")),d=sql`
|
|
198
|
+
COALESCE(t.input_tokens, 0)
|
|
199
|
+
+ CASE
|
|
200
|
+
WHEN t.started_at >= ${Yn}
|
|
201
|
+
AND (
|
|
202
|
+
t.crewx_version IS NULL
|
|
203
|
+
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
204
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Qn}) AS INTEGER) < ${Zn})
|
|
205
|
+
)
|
|
206
|
+
THEN COALESCE(t.cached_input_tokens, 0)
|
|
207
|
+
ELSE 0
|
|
208
|
+
END
|
|
209
|
+
`,u=r?sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.workspace_id = ${r} AND t.agent_id != 'workflow'`:sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.agent_id != 'workflow'`,l=o.db.all(sql`
|
|
210
|
+
SELECT
|
|
211
|
+
t.agent_id,
|
|
212
|
+
t.workspace_id,
|
|
213
|
+
${s} AS provider,
|
|
214
|
+
COUNT(*) AS total_tasks,
|
|
215
|
+
${c} AS unavailable_task_count,
|
|
216
|
+
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
217
|
+
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
218
|
+
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
219
|
+
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
220
|
+
FROM tasks t
|
|
221
|
+
${u}
|
|
222
|
+
GROUP BY t.agent_id, t.workspace_id, ${s}
|
|
223
|
+
`),p=new Map;for(let m of l){let k=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",w={provider:k,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,totalTokens:m.input_tokens+m.output_tokens,costUsd:m.cost_usd,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count},x=m.workspace_id??null,T=JSON.stringify([m.agent_id,x]),L=p.get(T);if(!L){p.set(T,{agentId:m.agent_id,workspaceId:x,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,costUsd:m.cost_usd,totalTokens:m.input_tokens+m.output_tokens,providers:[w]});continue}L.totalTasks+=m.total_tasks,L.unavailableTaskCount=(L.unavailableTaskCount??0)+m.unavailable_task_count,L.inputTokens+=m.input_tokens,L.outputTokens+=m.output_tokens,L.cachedInputTokens+=m.cached_input_tokens,L.costUsd+=m.cost_usd,L.totalTokens+=m.input_tokens+m.output_tokens;let N=L.providers.find(D=>D.provider===k);N?(N.inputTokens+=w.inputTokens,N.outputTokens+=w.outputTokens,N.cachedInputTokens+=w.cachedInputTokens,N.totalTokens+=w.totalTokens,N.costUsd+=w.costUsd,N.totalTasks+=w.totalTasks,N.unavailableTaskCount+=w.unavailableTaskCount):L.providers.push(w);}let _=[...p.values()];for(let m of _)m.providers.sort((k,w)=>k.provider===w.provider?0:k.provider==="unknown"?1:w.provider==="unknown"?-1:k.totalTokens!==w.totalTokens?w.totalTokens-k.totalTokens:k.provider<w.provider?-1:1);let h=(m,k)=>m===k?0:m<k?-1:1;return _.sort((m,k)=>{if(m.totalTokens!==k.totalTokens)return k.totalTokens-m.totalTokens;let w=h(m.agentId,k.agentId);return w!==0?w:m.workspaceId===k.workspaceId?0:m.workspaceId===null?1:k.workspaceId===null?-1:h(m.workspaceId,k.workspaceId)}),_}catch(s){throw new f("DB_ERROR","Failed to get agent usage",s)}finally{o.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Br(sql.raw("t.status")),i=Ko(sql.raw("t.metadata"));return o.db.all(r?sql`
|
|
123
224
|
SELECT
|
|
124
225
|
date(t.started_at) AS date,
|
|
125
226
|
t.agent_id,
|
|
227
|
+
${i} AS unavailable_task_count,
|
|
126
228
|
COALESCE(SUM(
|
|
127
229
|
COALESCE(t.input_tokens, 0)
|
|
128
230
|
+ CASE
|
|
129
|
-
WHEN t.started_at >= ${
|
|
231
|
+
WHEN t.started_at >= ${Yn}
|
|
130
232
|
AND (
|
|
131
233
|
t.crewx_version IS NULL
|
|
132
234
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
133
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
235
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Qn}) AS INTEGER) < ${Zn})
|
|
134
236
|
)
|
|
135
237
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
136
238
|
ELSE 0
|
|
@@ -140,24 +242,26 @@ ${n.join(`
|
|
|
140
242
|
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
141
243
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
142
244
|
FROM tasks t
|
|
143
|
-
WHERE
|
|
144
|
-
AND t.started_at >= ${
|
|
145
|
-
AND t.started_at < ${
|
|
146
|
-
AND t.workspace_id = ${
|
|
245
|
+
WHERE ${s}
|
|
246
|
+
AND t.started_at >= ${e}
|
|
247
|
+
AND t.started_at < ${n}
|
|
248
|
+
AND t.workspace_id = ${r}
|
|
249
|
+
AND t.agent_id != 'workflow'
|
|
147
250
|
GROUP BY date(t.started_at), t.agent_id
|
|
148
251
|
ORDER BY date(t.started_at) ASC
|
|
149
252
|
`:sql`
|
|
150
253
|
SELECT
|
|
151
254
|
date(t.started_at) AS date,
|
|
152
255
|
t.agent_id,
|
|
256
|
+
${i} AS unavailable_task_count,
|
|
153
257
|
COALESCE(SUM(
|
|
154
258
|
COALESCE(t.input_tokens, 0)
|
|
155
259
|
+ CASE
|
|
156
|
-
WHEN t.started_at >= ${
|
|
260
|
+
WHEN t.started_at >= ${Yn}
|
|
157
261
|
AND (
|
|
158
262
|
t.crewx_version IS NULL
|
|
159
263
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
160
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
264
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Qn}) AS INTEGER) < ${Zn})
|
|
161
265
|
)
|
|
162
266
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
163
267
|
ELSE 0
|
|
@@ -167,152 +271,433 @@ ${n.join(`
|
|
|
167
271
|
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
168
272
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
169
273
|
FROM tasks t
|
|
170
|
-
WHERE
|
|
171
|
-
AND t.started_at >= ${
|
|
172
|
-
AND t.started_at < ${
|
|
274
|
+
WHERE ${s}
|
|
275
|
+
AND t.started_at >= ${e}
|
|
276
|
+
AND t.started_at < ${n}
|
|
277
|
+
AND t.agent_id != 'workflow'
|
|
173
278
|
GROUP BY date(t.started_at), t.agent_id
|
|
174
279
|
ORDER BY date(t.started_at) ASC
|
|
175
|
-
`).map(
|
|
176
|
-
|
|
177
|
-
WHEN ${r.model} LIKE 'claude-%' OR ${r.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
178
|
-
WHEN ${r.model} LIKE 'gpt-%' OR ${r.model} LIKE 'codex-%' THEN 'codex'
|
|
179
|
-
WHEN ${r.model} LIKE 'gemini-%' THEN 'gemini'
|
|
180
|
-
WHEN ${r.model} LIKE 'zai-%' OR ${r.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
181
|
-
WHEN ${r.model} LIKE 'minimax/%' THEN 'minimax'
|
|
182
|
-
WHEN ${r.model} LIKE 'qwen%' THEN 'qwen'
|
|
183
|
-
ELSE 'unknown'
|
|
184
|
-
END
|
|
185
|
-
`,i=sql`
|
|
186
|
-
COALESCE(${r.input_tokens}, 0)
|
|
280
|
+
`).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(s){throw new f("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let o=r.db.select(pe).from(a).where(and(eq(a.id,e),eq(a.workspace_id,n))).limit(1).get();return o?ut(o):void 0}catch(o){throw new f("DB_ERROR","Failed to find task for stop",o)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(and(eq(a.agent_id,e.agentId),eq(a.workspace_id,e.workspaceId),sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(a.started_at)).limit(1).get()??null}catch(r){throw new f("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r,o="failed",s){if(!this.dbExists())return;let i=this.openHandle(true);try{let c=new Date().toISOString(),d=r?and(eq(a.id,e),eq(a.status,"running"),eq(a.workspace_id,r)):and(eq(a.id,e),eq(a.status,"running")),u=i.db.select({metadata:a.metadata}).from(a).where(d).limit(1).get();if(!u)return;let l={status:o,error:n,completed_at:c};if(s){let p=ge(u.metadata);p.terminalReason=s,l.metadata=JSON.stringify(p);}i.db.update(a).set(l).where(d).run();}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to mark task failed",c)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=U(i);try{let d=n?and(like(a.prompt,`%${e}%`),eq(a.workspace_id,n)):like(a.prompt,`%${e}%`),u=c.db.select(pe).from(a).where(d).orderBy(asc(a.started_at)).all();for(let l of u)o.has(l.id)||(o.add(l.id),s.push(ut(l)));}catch(d){throw new f("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{c.close();}}return s}getProviderUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=ia(),i=Br(a.status),c=Ko(a.metadata),d=sql`
|
|
281
|
+
COALESCE(${a.input_tokens}, 0)
|
|
187
282
|
+ CASE
|
|
188
|
-
WHEN ${
|
|
283
|
+
WHEN ${a.started_at} >= ${Yn}
|
|
189
284
|
AND (
|
|
190
|
-
${
|
|
191
|
-
OR (${
|
|
192
|
-
OR (${
|
|
285
|
+
${a.crewx_version} IS NULL
|
|
286
|
+
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
287
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Qn}) AS INTEGER) < ${Zn})
|
|
193
288
|
)
|
|
194
|
-
THEN COALESCE(${
|
|
289
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
195
290
|
ELSE 0
|
|
196
291
|
END
|
|
197
|
-
`,
|
|
292
|
+
`,u=r?sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return o.db.all(sql`
|
|
198
293
|
SELECT
|
|
199
|
-
${
|
|
294
|
+
${s} AS provider,
|
|
200
295
|
COUNT(*) AS total_tasks,
|
|
201
|
-
|
|
202
|
-
COALESCE(SUM(${
|
|
203
|
-
COALESCE(SUM(${
|
|
204
|
-
COALESCE(SUM(${
|
|
205
|
-
COALESCE(SUM(${
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
${a}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
WHEN ${r.model} LIKE 'gpt-%' OR ${r.model} LIKE 'codex-%' THEN 'codex'
|
|
215
|
-
WHEN ${r.model} LIKE 'gemini-%' THEN 'gemini'
|
|
216
|
-
WHEN ${r.model} LIKE 'zai-%' OR ${r.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
217
|
-
WHEN ${r.model} LIKE 'minimax/%' THEN 'minimax'
|
|
218
|
-
WHEN ${r.model} LIKE 'qwen%' THEN 'qwen'
|
|
219
|
-
ELSE 'unknown'
|
|
220
|
-
END
|
|
221
|
-
`,i=sql`
|
|
222
|
-
COALESCE(${r.input_tokens}, 0)
|
|
296
|
+
${c} AS unavailable_task_count,
|
|
297
|
+
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
298
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
299
|
+
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
300
|
+
COALESCE(SUM(${a.cost_usd}), 0) AS cost_usd,
|
|
301
|
+
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
302
|
+
MAX(${a.completed_at}) AS last_active_at
|
|
303
|
+
FROM ${a}
|
|
304
|
+
${u}
|
|
305
|
+
GROUP BY ${s}
|
|
306
|
+
ORDER BY (COALESCE(SUM(${d}), 0) + COALESCE(SUM(${a.output_tokens}), 0)) DESC
|
|
307
|
+
`).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(s){throw new f("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=ia(),i=Br(a.status),c=Ko(a.metadata),d=sql`
|
|
308
|
+
COALESCE(${a.input_tokens}, 0)
|
|
223
309
|
+ CASE
|
|
224
|
-
WHEN ${
|
|
310
|
+
WHEN ${a.started_at} >= ${Yn}
|
|
225
311
|
AND (
|
|
226
|
-
${
|
|
227
|
-
OR (${
|
|
228
|
-
OR (${
|
|
312
|
+
${a.crewx_version} IS NULL
|
|
313
|
+
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
314
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Qn}) AS INTEGER) < ${Zn})
|
|
229
315
|
)
|
|
230
|
-
THEN COALESCE(${
|
|
316
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
231
317
|
ELSE 0
|
|
232
318
|
END
|
|
233
|
-
`,
|
|
319
|
+
`,u=r?sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,l=o.db.all(sql`
|
|
234
320
|
SELECT
|
|
235
|
-
${
|
|
236
|
-
${
|
|
321
|
+
${a.model} AS model,
|
|
322
|
+
${s} AS provider,
|
|
237
323
|
COUNT(*) AS total_tasks,
|
|
238
|
-
|
|
239
|
-
COALESCE(SUM(${
|
|
240
|
-
COALESCE(SUM(${
|
|
241
|
-
COALESCE(SUM(${
|
|
242
|
-
COALESCE(SUM(${
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
${a}
|
|
246
|
-
|
|
247
|
-
|
|
324
|
+
${c} AS unavailable_task_count,
|
|
325
|
+
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
326
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
327
|
+
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
328
|
+
COALESCE(SUM(${a.cost_usd}), 0) AS cost_usd,
|
|
329
|
+
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
330
|
+
MAX(${a.completed_at}) AS last_active_at
|
|
331
|
+
FROM ${a}
|
|
332
|
+
${u}
|
|
333
|
+
GROUP BY ${a.model}, ${s}
|
|
334
|
+
`),p=new Map;for(let _ of l){let h=Gs(_.model??""),m=JSON.stringify([_.provider,h]),k=p.get(m);k?(k.totalTasks+=_.total_tasks,k.unavailableTaskCount=(k.unavailableTaskCount??0)+_.unavailable_task_count,k.inputTokens+=_.input_tokens,k.outputTokens+=_.output_tokens,k.cachedInputTokens+=_.cached_input_tokens,k.costUsd+=_.cost_usd,k.totalTokens+=_.input_tokens+_.output_tokens,k.activeDurationMs+=_.active_duration_ms??0,_.last_active_at&&(!k.lastActiveAt||_.last_active_at>k.lastActiveAt)&&(k.lastActiveAt=_.last_active_at)):p.set(m,{model:h,provider:_.provider,totalTasks:_.total_tasks,unavailableTaskCount:_.unavailable_task_count,inputTokens:_.input_tokens,outputTokens:_.output_tokens,cachedInputTokens:_.cached_input_tokens,costUsd:_.cost_usd,totalTokens:_.input_tokens+_.output_tokens,activeDurationMs:_.active_duration_ms??0,lastActiveAt:_.last_active_at??null});}return Array.from(p.values()).sort((_,h)=>h.costUsd-_.costUsd)}catch(s){throw new f("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=r?sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return o.db.all(sql`
|
|
335
|
+
SELECT
|
|
336
|
+
${a.thread_id} AS thread_id,
|
|
337
|
+
${a.agent_id} AS agent_id,
|
|
338
|
+
${a.started_at} AS started_at,
|
|
339
|
+
${a.status} AS status,
|
|
340
|
+
${a.error} AS error,
|
|
341
|
+
${a.exit_code} AS exit_code,
|
|
342
|
+
${a.metadata} AS metadata
|
|
343
|
+
FROM ${a}
|
|
344
|
+
${s}
|
|
345
|
+
ORDER BY ${a.started_at} ASC
|
|
346
|
+
`).map(c=>({threadId:c.thread_id,agentId:c.agent_id,startedAt:c.started_at,status:c.status,error:c.error,exitCode:c.exit_code,terminalReason:dt({status:c.status,error:c.error,metadata:c.metadata})??null}))}catch(s){throw new f("DB_ERROR","Failed to get tasks for report",s)}finally{o.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let o=this.openHandle(false);try{let s=sql`
|
|
347
|
+
COALESCE(${a.input_tokens}, 0)
|
|
348
|
+
+ CASE
|
|
349
|
+
WHEN ${a.started_at} >= ${Yn}
|
|
350
|
+
AND (
|
|
351
|
+
${a.crewx_version} IS NULL
|
|
352
|
+
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
353
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Qn}) AS INTEGER) < ${Zn})
|
|
354
|
+
)
|
|
355
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
356
|
+
ELSE 0
|
|
357
|
+
END
|
|
358
|
+
`,i=Br(a.status),c=r?sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,d=o.db.all(sql`
|
|
248
359
|
SELECT
|
|
249
|
-
${
|
|
250
|
-
${
|
|
251
|
-
|
|
252
|
-
${
|
|
253
|
-
${
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
${
|
|
257
|
-
ORDER BY ${
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
360
|
+
${a.caller_agent_id} AS caller_agent_id,
|
|
361
|
+
${a.agent_id} AS agent_id,
|
|
362
|
+
COUNT(*) AS task_count,
|
|
363
|
+
COALESCE(SUM(${s}), 0) AS input_tokens,
|
|
364
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens
|
|
365
|
+
FROM ${a}
|
|
366
|
+
${c}
|
|
367
|
+
GROUP BY ${a.caller_agent_id}, ${a.agent_id}
|
|
368
|
+
ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
|
|
369
|
+
LIMIT ${sa+1}
|
|
370
|
+
`),u=d.length>sa;return {edges:d.slice(0,sa).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:u}}catch(s){throw new f("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(a.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(inArray(a.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(inArray(a.status,$i(e.statuses))),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt(a.started_at,e.to));let o=r.length>0?and(...r):void 0,s=(e.order??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at),i={id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id,error:a.error,metadata:a.metadata};return (e.limit?n.db.select(i).from(a).where(o).orderBy(s).limit(e.limit).all():n.db.select(i).from(a).where(o).orderBy(s).all()).map(({error:d,metadata:u,...l})=>({...l,status:De({status:l.status,error:d,metadata:u}),terminalReason:dt({status:l.status,error:d,metadata:u})??null}))}catch(r){throw new f("DB_ERROR","Failed to find task evidence",r)}finally{n.close();}}findThreadChains(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[isNotNull(a.thread_id),isNull(a.parent_task_id),isNull(a.caller_agent_id),or(isNull(a.platform),ne(a.platform,"workflow")),or(isNull(a.metadata),Tl()),or(isNull(a.metadata),notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(a.workspace_id,e.workspaceId)),e.from&&s.push(gte(a.started_at,e.from)),e.to&&s.push(lt(a.started_at,e.to));let i=n.db.select({id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id}).from(a).where(and(...s)).orderBy(asc(a.started_at),asc(a.id)).all(),c=new Map;for(let u of i){if(!u.thread_id)continue;let l={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},p=c.get(u.thread_id);p?p.push(l):c.set(u.thread_id,[l]);}let d=[];for(let[u,l]of c){let p=l.filter(_=>_.agentId===e.targetAgentId).length;p<2||d.push({threadId:u,targetAgentTurnCount:p,turns:l});}return d.sort((u,l)=>{let p=u.turns[u.turns.length-1].startedAt,_=l.turns[l.turns.length-1].startedAt;return p<_?1:p>_?-1:0}),d.slice(0,r).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(r){throw new f("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}},vl=["up","down"],ha=1e3,bl=200,Zm=64,Gr=class extends f{stableCode;taskId;constructor(e,n){super(e==="TASK_NOT_FOUND"?"NOT_FOUND":"CONFLICT",e==="TASK_NOT_FOUND"?`Task not found: ${n}`:`Task is not finished, so it cannot be rated: ${n}`),this.name="TaskRatingError",this.stableCode=e,this.taskId=n;}},ek=new Set(En);});g();g();g();var qt=class{detach(e){}};g();function $a(t){let e=n=>String(n).padStart(2,"0");return `${t.getFullYear()}${e(t.getMonth()+1)}${e(t.getDate())}T${e(t.getHours())}${e(t.getMinutes())}${e(t.getSeconds())}`}function gs(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var hs=class extends qt{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(e){super(),this.logsDir=join(e?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=e?.version??"unknown";}attach(e){this.unsubs.push(e.on("task:start",n=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let r=$a(n.timestamp),o=join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,o);let s=`=== TASK LOG: ${n.traceId} ===
|
|
371
|
+
CrewX Version: ${this.version}
|
|
372
|
+
Mode: ${n.mode}
|
|
373
|
+
Agent: ${n.agentRef}
|
|
374
|
+
Started: ${gs(n.timestamp)}
|
|
375
|
+
Message: ${n.message}
|
|
376
|
+
|
|
377
|
+
`;writeFileSync(o,s,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=new Date().toISOString();appendFileSync(r,`[${o}] STDOUT: ${n.output}
|
|
378
|
+
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=gs(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
|
|
379
|
+
[${o}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
380
|
+
`;appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};g();g();var qa=Symbol.for("crewx.interceptor.run-stops");function Np(){let t=globalThis,e=t[qa];if(e)return e;let n=new Map;return t[qa]=n,n}function Ba(t){let e=Np().get(t);return e?(e.abort(),true):false}g();var Nn=new Map;function to(t){let e=Oe.resolve(t);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(n,r)=>`${r.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function Ga(t){let e=to(t);return createHash("sha256").update(e).digest("hex")}function ja(t){let e=to(t),n=Nn.get(e);if(n!==void 0)return n;let r=e;try{let o=Oe.join(e,".git");if(!lstatSync(o).isFile())return Nn.set(e,r),r;let s=/^gitdir:\s*(.+?)\s*$/i.exec(readFileSync(o,"utf8").trim());if(!s)return Nn.set(e,r),r;let i=s[1],c=Oe.isAbsolute(i)?i:Oe.resolve(Oe.dirname(o),i),d=readFileSync(Oe.join(c,"commondir"),"utf8").trim();if(!d)return Nn.set(e,r),r;let u=Oe.isAbsolute(d)?d:Oe.resolve(c,d);if(Oe.basename(u)!==".git"||!statSync(u).isDirectory())return Nn.set(e,r),r;let l=to(realpathSync.native(e)),p=to(realpathSync.native(Oe.dirname(u)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return Nn.set(e,r),r}Ot();ta();Hn();Li();$r();ea();Eo();var sk=200,ik=200;function ak(t){if(typeof t!="object"||t===null||!("code"in t))return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function dk(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=ak(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function Pl(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function ck(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ll(t){if(!t)return {};try{let e=JSON.parse(t);return ck(e)?e:{}}catch{return {}}}function tr(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var uk=new Set(["workflow","mcp"]),ka=class extends qt{name="sqlite-tracing";unsubs=[];dbPath;version;inheritWorktreeOwner;runnerIdentity;taskRepo;heartbeatTaskIds=new Set;ownedTaskRuns=new Map;ignoredDetachedTaskIds=new Set;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super();let n=process.env.CREWX_DB;this.dbPath=e?.dbRoot!==void 0?join(e.dbRoot,".crewx","crewx.db"):n??join(homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown",this.inheritWorktreeOwner=e?.inheritWorktreeOwner===true;let r=e?.runnerIdentity;this.runnerIdentity={detachedRunner:r?.detachedRunner===true,assignedTaskId:r?.detachedRunner===true&&r.assignedTaskId?.trim()||void 0};}attach(e){let n=new Wr({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),o=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml")),s=this.inheritWorktreeOwner?ja(r):r,i=o?Ga(s):null,c=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let u=d.callerAgentId??null,l=d.parentTaskId??null,p=d.rootTraceId??d.traceId,{detachedRunner:_,assignedTaskId:h}=this.runnerIdentity,m=h??d.traceId,k=tr(d.metadata?.runEpoch),w=_?"runner":"caller",x=d.workspaceId??i,T=_?n.getTask(m):void 0,L=d.pid??null,N={...d.metadata??{provider:d.provider??"cli/claude"},ownership:w,..._&&L!==null?{providerPid:L}:{}},D=JSON.stringify(N);if(_&&T?.status==="running"&&T.pid!==null&&k===0){this.ignoredDetachedTaskIds.add(m);return}n.startTask({id:m,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",actorKind:d.actorKind??null,actorId:d.actorId??null,pid:_?process.pid:L,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,securityKey:d.renderedPrompt==null?null:d.securityKey??null,command:c,codingAgentCommand:d.codingAgentCommand??null,workspaceId:x,projectId:d.projectId??null,callerAgentId:u,parentTaskId:l,traceId:p,metadata:D,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:k,ownership:w,..._?{providerPid:L}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:N}})?this.recordOwnedTaskRun({taskId:m,runEpoch:k,workspaceId:x,ownership:w}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:k,ownership:w}),uk.has(d.platform??"cli")||ll(n,{taskId:m,runEpoch:k,onStopRequested:qe=>this.handleStopRequested(n,qe)})&&this.heartbeatTaskIds.add(m);}catch(u){console.warn("[crewx] task:start tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:output",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;this.enqueueLog(u,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(u){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(u,[l],Pl(l));}}),e.on("task:run-update",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;let l=tr(d.runEpoch),p=this.runnerIdentity.detachedRunner;n.updateTaskOwnership({id:u,runEpoch:l,ownership:p?"runner":"caller",...p&&d.pid!==void 0?{providerPid:d.pid}:{},runtime:{...d.model!==void 0?{model:d.model}:{},...d.renderedPrompt!==void 0?{renderedPrompt:d.renderedPrompt}:{},...d.securityKey!==void 0?{securityKey:d.securityKey}:{},...d.codingAgentCommand!==void 0?{codingAgentCommand:d.codingAgentCommand}:{},...d.metadata?{metadata:d.metadata}:{}}}),!p&&d.pid!==void 0&&n.recordTaskPid({id:u,runEpoch:l,pid:d.pid});}catch(u){console.warn("[crewx] task:run-update tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:provider-input",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;n.recordProviderInput({id:u,runEpoch:d.runEpoch,input:d.input,keyWrapSkipped:d.keyWrapSkipped,interceptedRequest:d.interceptedRequest===!0,recordedAt:d.timestamp.toISOString()});}catch(u){console.warn("[crewx] task:provider-input tracing failed",{cause:u instanceof Error?u.name:typeof u});}}),e.on("task:end",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(u))return;let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(u,tr(l)),Mr(u,l)&&this.heartbeatTaskIds.delete(u),this.flushTaskLogs(u);let _=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{},...d.error.mode?{mode:d.error.mode}:{}}):null,h=d.result??null,m=!1,k=d.metadata?.suppressPartialResultRecovery===!0;if(d.error&&!k&&(!h||h.trim()==="")){let w=this.recoverPartialResult(u,d,l);w&&(h=w,m=!0);}n.finishTask({id:u,status:d.error?"failed":"success",result:h,error:_,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,usagePresent:d.inputTokens!==void 0||d.outputTokens!==void 0||d.cachedInputTokens!==void 0,usageComplete:d.usageComplete,model:d.model??null,runEpoch:l,partialResultRecovered:m});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)Mr(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let o=await ml(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(o.status==="failed"||o.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:o.status,...o.error?{error:o.error}:{}});}catch(o){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:o instanceof Error?o.name:typeof o});}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=Pl(n),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=sk){this.flushTaskLogs(e);return}if(!r.timer){let o=setTimeout(()=>{let s=this.queues.get(e);!s||s.timer!==o||(s.timer=void 0,this.flushTaskLogs(e));},ik);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo;if(!o)return;let s=o.getTask(e);if(!s||s.status!=="running"||tr(s.run_epoch)!==tr(r))return;let i=Ll(s.metadata),c=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!c)return;let d=Fo({taskLogRepository:o,taskId:e,provider:c,model:s.model});if(!d?.adapter.extractPartialText)return;let u=d.adapter.extractPartialText(d.stdout);return !u||!u.trim()||Rt(u,c)?void 0:u}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let o=tr(n.run_epoch),s=Ll(n.metadata??null),i=s.ownership==="runner"?"runner":"caller";if(i==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let c=typeof s.providerPid=="number"&&Number.isSafeInteger(s.providerPid)&&s.providerPid>0?s.providerPid:void 0,d=i==="runner"?c:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(Ba(r),d!==void 0){let u;try{u=await Vt(d,{signal:Jt});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(u.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:u.error??"process termination failed"});return}}try{let u=e.finalizeTaskStop({id:r,runEpoch:o,method:zo(n.stop_requested_at)}),l=e.getTask(r);(u||l?.status!=="running")&&Mr(r,o)&&this.heartbeatTaskIds.delete(r);}catch(u){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:u instanceof Error?u.name:typeof u});}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,o=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,o);}let s=this.queues.get(e);s&&s.entries.length===0&&(s.timer&&clearTimeout(s.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let o=dk(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[o.code]=(this.metrics.appendFailureByCode[o.code]??0)+1,this.metrics.appendFailureByCause[o.cause]=(this.metrics.appendFailureByCause[o.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:o.code,cause:o.cause,pendingEntries:n.length,pendingBytes:r});}};g();g();g();vt();Bt();Ft();Ot();jt();mo();Jn();g();function es(t){return t!==null&&t!==""}function lk(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":es(t.parent_task_id)||es(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function Ml(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&es(e)?e:null}}function ts(t){let e=lk(t),n=es(t.caller_agent_id)?t.caller_agent_id:null,r=t.parent_thread_id!==null&&t.parent_thread_id!==t.thread_id;return {origin:e==="human"?"direct":"delegated",delegatedByAgentId:e==="agent"?n??(r&&t.parent_agent_id||null):null}}function $l(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?Ml(t.creator_actor_kind,t.creator_actor_id):e?ts(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?Ml(t.created_by_kind,t.created_by_id):n?ts(n):void 0}function jr(t){return Dr(t)}function mk({metadata:t,...e}){return {...e,status:De({...e,metadata:t}),terminalReason:dt({...e,metadata:t})??null}}var zr=32,Ul=100,kk=["running","failed"];function yk(t){return t==="running"?0:t==="failed"?1:2}function ql(t,e){return t[0]!==e[0]?t[0]-e[0]:t[1]!==e[1]?t[1]===null?1:e[1]===null||t[1]<e[1]?-1:1:t[2]<e[2]?-1:t[2]>e[2]?1:0}function Tk(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function wk(t){try{let e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(Array.isArray(e)&&e.length===3&&Number.isInteger(e[0])&&e[0]>=0&&e[0]<=2&&(e[1]===null||typeof e[1]=="string")&&typeof e[2]=="string")return [e[0],e[1],e[2]]}catch{}throw new f("VALIDATION","Invalid descendant cursor")}function Bl(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function ya(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function Ek(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function Ta(t,e,n,r){let o=Ek(e);o&&(t[o]+=r,t.total+=r,o==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var rs=900,Fl=20;function Wl(t,e){return (t?.origin??"direct")===e}function Gl(t,e){let n=new Date(e.updated_at).getTime()-new Date(t.updated_at).getTime();return n!==0?n:t.id.localeCompare(e.id)}var nr=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function rr(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Rk(t){let n=rr(t).threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {priority:null,state:null};let r=n;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}function jl(t,e,n){return t.get(sql`
|
|
381
|
+
SELECT id
|
|
382
|
+
FROM tasks INDEXED BY idx_tasks_thread_id
|
|
383
|
+
WHERE thread_id = ${e}
|
|
384
|
+
AND id <> ${n}
|
|
385
|
+
LIMIT 1
|
|
386
|
+
`)!==void 0}function Sk(t,e,n){let r=n?and(eq(y.id,e),eq(y.workspace_id,n)):eq(y.id,e),o=t.select({pinned:y.pinned,metadata:y.metadata}).from(y).where(r).get();if(!o)return null;let s=o.pinned?0:1,i=rr(o.metadata);if(s){let c=n?and(eq(y.pinned,1),eq(y.workspace_id,n)):eq(y.pinned,1),d=t.select({metadata:y.metadata}).from(y).where(c).all(),u=null;for(let l of d){let p=rr(l.metadata);typeof p.pinOrder=="number"&&(u===null||p.pinOrder<u)&&(u=p.pinOrder);}i.pinOrder=u===null?0:u-1;}else delete i.pinOrder;return t.update(y).set({pinned:s,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(r).run(),{pinned:!!s}}function Ik(t,e,n){for(let r=0;r<e.length;r++){let o=n?and(eq(y.id,e[r]),eq(y.workspace_id,n)):eq(y.id,e[r]),s=t.select({metadata:y.metadata}).from(y).where(o).get();if(!s)continue;let i=rr(s.metadata);i.pinOrder=r+1,t.update(y).set({metadata:JSON.stringify(i)}).where(o).run();}}var os=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new f("NOT_FOUND","Database not found");let r=U(n);if(e)try{Le(r.db,n);}catch(o){throw r.close(),o}return r}topLevelTaskPredicateSql(e="child",n){let r=n?`tasks parent INDEXED BY ${n}`:"tasks parent";return sql.raw(`NOT EXISTS (
|
|
387
|
+
SELECT 1 FROM ${r}
|
|
388
|
+
WHERE parent.id = ${e}.parent_task_id
|
|
389
|
+
AND parent.thread_id = ${e}.thread_id
|
|
390
|
+
)`)}workflowAnchorPredicateSql(e){let n=zt.map(r=>`OR ${e}.metadata LIKE '%"kind":"${r}"%'`).join(`
|
|
391
|
+
`);return sql.raw(`COALESCE(
|
|
392
|
+
${e}.agent_id = 'workflow'
|
|
393
|
+
${n}
|
|
394
|
+
OR (
|
|
395
|
+
${e}.metadata LIKE '%"workflow"%'
|
|
396
|
+
AND CASE WHEN json_valid(${e}.metadata)
|
|
397
|
+
THEN json_type(${e}.metadata, '$.workflow')
|
|
398
|
+
END IN ('object', 'array')
|
|
399
|
+
),
|
|
400
|
+
0
|
|
401
|
+
)`)}descendantTraversalSql(e,n,r){return sql`
|
|
402
|
+
WITH RECURSIVE
|
|
403
|
+
own_tasks(task_id) AS (${e}),
|
|
404
|
+
seeds(task_id) AS (${n}),
|
|
405
|
+
descendants(root_task_id, task_id, depth) AS (
|
|
406
|
+
SELECT seed.task_id, seed.task_id, 0 FROM seeds seed
|
|
407
|
+
UNION
|
|
408
|
+
SELECT descendants.root_task_id, child.id, descendants.depth + 1
|
|
409
|
+
FROM descendants
|
|
410
|
+
JOIN tasks child INDEXED BY idx_tasks_parent_task_id
|
|
411
|
+
ON child.parent_task_id = descendants.task_id
|
|
412
|
+
WHERE descendants.depth < ${r}
|
|
413
|
+
),
|
|
414
|
+
descendant_ids(root_task_id, task_id, depth) AS (
|
|
415
|
+
SELECT descendants.root_task_id, descendants.task_id, MIN(descendants.depth)
|
|
416
|
+
FROM descendants
|
|
417
|
+
WHERE descendants.depth > 0
|
|
418
|
+
AND descendants.task_id <> descendants.root_task_id
|
|
419
|
+
GROUP BY descendants.root_task_id, descendants.task_id
|
|
420
|
+
)
|
|
421
|
+
`}descendantSkippedSql(e){let n=sql.raw(e);return sql`(
|
|
422
|
+
${this.workflowAnchorPredicateSql(e)}
|
|
423
|
+
OR (
|
|
424
|
+
EXISTS (SELECT 1 FROM own_tasks own WHERE own.task_id = ${n}.id)
|
|
425
|
+
AND ${this.topLevelTaskPredicateSql(e)}
|
|
426
|
+
)
|
|
427
|
+
)`}findAllThreadsQuery(e,n){let r=[];e&&r.push(sql`workspace_id = ${e}`),n&&r.push(sql`created_by_kind = ${n}`);let o=r.length>0?sql` WHERE ${sql.join(r,sql` AND `)}`:sql``;return sql`SELECT * FROM threads${o} ORDER BY updated_at DESC`}findThreadIdsQuery(e){return e?sql`SELECT id FROM threads INDEXED BY idx_threads_ws_updated
|
|
428
|
+
WHERE workspace_id = ${e}
|
|
429
|
+
ORDER BY updated_at DESC`:sql`SELECT id FROM threads`}readThreadIds(e,n="Failed to find thread ids"){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=U(i);try{let d=c.db.all(this.findThreadIdsQuery(e));for(let u of d)o.has(u.id)||(o.add(u.id),s.push(u.id));}catch(d){throw new f("DB_ERROR",n,d)}finally{c.close();}}return s}findThreadSortKeysQuery(e){return sql`SELECT id, updated_at
|
|
430
|
+
FROM threads INDEXED BY idx_threads_ws_updated
|
|
431
|
+
WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!existsSync(s))continue;let i=U(s);try{let c=i.db.all(this.findThreadSortKeysQuery(e));for(let d of c)r.has(d.id)||(r.add(d.id),o.push(d));}catch(c){throw new f("DB_ERROR","Failed to find recent direct threads",c)}finally{i.close();}}return o}readThreadRowsByIds(e,n,r="Failed to find threads by ids"){if(e.length===0)return [];let o=this.resolveDbPaths(),s=new Set,i=[];for(let c of o){if(!existsSync(c))continue;let d=U(c);try{for(let u=0;u<e.length;u+=rs){let l=e.slice(u,u+rs),p=inArray(y.id,l),_=n?and(p,eq(y.workspace_id,n)):p,h=d.db.select().from(y).where(_).all();for(let m of h)s.has(m.id)||(s.add(m.id),i.push(m));}}catch(u){throw new f("DB_ERROR",r,u)}finally{d.close();}}return i}readThreadRows(e,n,r="Failed to find all threads"){let o=this.resolveDbPaths(),s=new Set,i=[];for(let c of o){if(!existsSync(c))continue;let d=U(c);try{let u=d.db.all(this.findAllThreadsQuery(e,n));for(let l of u)s.has(l.id)||(s.add(l.id),i.push(l));}catch(u){throw new f("DB_ERROR",r,u)}finally{d.close();}}return i}findAllThreads(e,n){return this.readThreadRows(e,n)}explainFindAllThreadsPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=U(o);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.findAllThreadsQuery(e,n)}`).map(c=>c.detail)}finally{s.close();}}return []}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=U(i);try{let d=or(inArray(y.id,e),inArray(y.title,e)),u=n?and(d,eq(y.workspace_id,n)):d,l=c.db.select().from(y).where(u).orderBy(desc(y.updated_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(p));}catch(d){throw new f("DB_ERROR","Failed to find threads by ids or titles",d)}finally{c.close();}}return s}findThreadById(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=U(o);try{let i=eq(y.id,e),c=n?and(i,eq(y.workspace_id,n)):i,d=s.db.select().from(y).where(c).limit(1).get()??void 0;if(d)return d}catch(i){throw new f("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}createAppLaunchThread(e){let n=this.openHandle(true);try{return n.db.transaction(r=>{if(!r.select({id:le.id}).from(le).where(eq(le.id,e.workspaceId)).limit(1).get())throw new f("NOT_FOUND","Workspace not found");let s=r.select().from(y).where(eq(y.id,e.threadId)).limit(1).get();if(s){let l=rr(s.metadata).appLaunch,p=l&&typeof l=="object"&&!Array.isArray(l)?l.appId:void 0,_=r.get(sql`
|
|
432
|
+
SELECT COUNT(*) AS count FROM tasks WHERE thread_id = ${e.threadId}
|
|
433
|
+
`)?.count??0;return s.workspace_id===e.workspaceId&&p===e.appId&&s.message_count===0&&s.first_message===null&&s.last_message===null&&_===0?{status:"existing",thread:s}:{status:"conflict"}}let i=new Date().toISOString(),c=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(y).values({id:e.threadId,workspace_id:e.workspaceId,platform:e.platform,title:e.title,title_locked:1,created_by_kind:"human",created_by_id:e.createdById,created_by_task_id:null,message_count:0,first_message:null,last_message:null,metadata:c,created_at:i,updated_at:i}).run();let d=r.select().from(y).where(eq(y.id,e.threadId)).limit(1).get();if(!d)throw new f("DB_ERROR","App-launch thread could not be read after insert");return {status:"created",thread:d}},{behavior:"immediate"})}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to create App-launch thread",r)}finally{n.close();}}threadExists(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=U(o);try{let i=eq(y.id,e),c=n?and(i,eq(y.workspace_id,n)):i;if(s.db.select({id:y.id}).from(y).where(c).limit(1).get())return !0}catch(i){throw new f("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),o=0,s=0,i=0,c=0,d=0,u=0,l=0,p=0,_=0,h=0,m=new Set;for(let k of r){if(!existsSync(k))continue;let w=U(k);try{let x=w.db.get(sql`
|
|
434
|
+
SELECT count(*) AS cnt
|
|
435
|
+
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
436
|
+
WHERE child.thread_id = ${e}
|
|
437
|
+
AND ${this.topLevelTaskPredicateSql()}
|
|
438
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
439
|
+
`);x&&(o+=x.cnt);let T=w.db.get(sql`
|
|
263
440
|
SELECT
|
|
264
|
-
count(*) AS cnt,
|
|
265
441
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
266
442
|
COALESCE(SUM(child.output_tokens), 0) AS total_output,
|
|
267
443
|
COALESCE(SUM(child.cached_input_tokens), 0) AS total_cached,
|
|
268
444
|
COALESCE(SUM(child.cost_usd), 0) AS total_cost
|
|
269
|
-
FROM tasks child
|
|
270
|
-
WHERE child.thread_id = ${
|
|
271
|
-
AND ${
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
445
|
+
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
446
|
+
WHERE child.thread_id = ${e}
|
|
447
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
448
|
+
`);T&&(s+=T.total_input,i+=T.total_output,c+=T.total_cached,d+=T.total_cost);let L=w.db.get(sql`
|
|
449
|
+
WITH RECURSIVE
|
|
450
|
+
own_tasks(task_id) AS (
|
|
451
|
+
SELECT own.id
|
|
452
|
+
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
453
|
+
WHERE own.thread_id = ${e}
|
|
454
|
+
${n?sql`AND own.workspace_id = ${n}`:sql``}
|
|
455
|
+
),
|
|
456
|
+
descendants(task_id, depth) AS (
|
|
457
|
+
SELECT own.task_id, 0 FROM own_tasks own
|
|
458
|
+
UNION
|
|
459
|
+
SELECT child.id, descendants.depth + 1
|
|
460
|
+
FROM descendants
|
|
461
|
+
JOIN tasks child INDEXED BY idx_tasks_parent_task_id
|
|
462
|
+
ON child.parent_task_id = descendants.task_id
|
|
463
|
+
WHERE descendants.depth < ${zr}
|
|
464
|
+
),
|
|
465
|
+
delegated_ids(task_id) AS (
|
|
466
|
+
SELECT DISTINCT descendants.task_id
|
|
467
|
+
FROM descendants
|
|
468
|
+
WHERE descendants.depth > 0
|
|
469
|
+
AND NOT EXISTS (
|
|
470
|
+
SELECT 1 FROM own_tasks own
|
|
471
|
+
WHERE own.task_id = descendants.task_id
|
|
472
|
+
)
|
|
473
|
+
)
|
|
474
|
+
SELECT
|
|
475
|
+
count(*) AS cnt,
|
|
476
|
+
COALESCE(SUM(task.input_tokens), 0) AS total_input,
|
|
477
|
+
COALESCE(SUM(task.output_tokens), 0) AS total_output,
|
|
478
|
+
COALESCE(SUM(task.cached_input_tokens), 0) AS total_cached,
|
|
479
|
+
COALESCE(SUM(task.cost_usd), 0) AS total_cost
|
|
480
|
+
FROM delegated_ids
|
|
481
|
+
JOIN tasks task ON task.id = delegated_ids.task_id
|
|
482
|
+
`);L&&(u+=L.cnt,l+=L.total_input,p+=L.total_output,_+=L.total_cached,h+=L.total_cost);let N=w.db.all(sql`
|
|
483
|
+
SELECT DISTINCT child.agent_id FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
484
|
+
WHERE child.thread_id = ${e}
|
|
276
485
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
486
|
+
AND child.agent_id != 'workflow'
|
|
277
487
|
AND ${this.topLevelTaskPredicateSql()}
|
|
278
|
-
${
|
|
279
|
-
`);for(let
|
|
488
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
489
|
+
`);for(let D of N)m.add(D.agent_id);}catch(x){throw new f("DB_ERROR","Failed to aggregate task stats",x)}finally{w.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:c,costUsd:d,agentIds:Array.from(m),delegated:{taskCount:u,inputTokens:l,outputTokens:p,cachedInputTokens:_,costUsd:h}}}getDescendantSummaryByTaskId(e,n){let r=this.resolveDbPaths(),o={},s=new Date().toISOString();for(let i of r){if(!existsSync(i))continue;let c=U(i);try{let d=sql`
|
|
490
|
+
SELECT own.id
|
|
491
|
+
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
492
|
+
WHERE own.thread_id = ${e}
|
|
493
|
+
${n?sql`AND own.workspace_id = ${n}`:sql``}
|
|
494
|
+
`,u=c.db.all(sql`
|
|
495
|
+
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,zr)}
|
|
496
|
+
SELECT
|
|
497
|
+
descendant_ids.root_task_id AS root_task_id,
|
|
498
|
+
task.status AS status,
|
|
499
|
+
task.error AS error,
|
|
500
|
+
task.metadata AS metadata,
|
|
501
|
+
count(*) AS task_count
|
|
502
|
+
FROM descendant_ids
|
|
503
|
+
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
504
|
+
WHERE NOT ${this.descendantSkippedSql("task")}
|
|
505
|
+
GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
|
|
506
|
+
`);for(let l of u){let p=o[l.root_task_id]??=ya(s);Ta(p,De(l),dt(l),l.task_count);}}catch(d){throw new f("DB_ERROR","Failed to aggregate task descendant summaries",d)}finally{c.close();}}return o}listUnreadReplyCandidates(e,n){let r=new Map,o=new Map;for(let{threadId:i,readThroughAt:c}of e)c!==null&&o.set(i,c);if(o.size===0)return r;let s=new Set;for(let i of this.resolveDbPaths()){if(!existsSync(i))continue;let c=U(i);try{let d=c.db.all(this.unreadReplyCandidatesQuery(o,n));for(let u of d){if(s.has(u.id))continue;s.add(u.id);let l={id:u.id,threadId:u.thread_id,completedAt:u.completed_at,status:De(u),result:u.result,error:u.error,metadata:u.metadata},p=r.get(u.thread_id);p?p.push(l):r.set(u.thread_id,[l]);}}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to list unread reply candidates",d)}finally{c.close();}}return r}unreadReplyCandidatesQuery(e,n){let r=sql.join([...e].map(([s,i])=>sql`(${s}, ${i})`),sql`, `),o=sql.join(En.map(s=>sql`${s}`),sql`, `);return sql`
|
|
507
|
+
WITH watermarks(thread_id, read_through_at) AS (VALUES ${r})
|
|
508
|
+
SELECT child.id, child.thread_id, child.completed_at, child.status,
|
|
509
|
+
child.result, child.error, child.metadata
|
|
510
|
+
FROM watermarks w
|
|
511
|
+
JOIN tasks child INDEXED BY idx_tasks_thread_id ON child.thread_id = w.thread_id
|
|
512
|
+
WHERE julianday(child.completed_at) > julianday(w.read_through_at)
|
|
513
|
+
AND child.status IN (${o})
|
|
514
|
+
AND ${this.topLevelTaskPredicateSql()}
|
|
515
|
+
AND NOT ${this.workflowAnchorPredicateSql("child")}
|
|
516
|
+
AND COALESCE(length(child.result), 0) > 0
|
|
517
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
518
|
+
ORDER BY julianday(child.completed_at), child.id
|
|
519
|
+
`}getThreadTaskStatusBatch(e,n){let r=[...new Set(e)];if(r.length===0)return {tasksByThread:new Map,descendantSummaryByTaskId:{}};let o=this.batchFetchTasks(r,n),s={},i=new Date().toISOString(),c=sql.join(r.map(u=>sql`${u}`),sql`, `),d=sql`
|
|
520
|
+
SELECT own.id
|
|
521
|
+
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
522
|
+
WHERE own.thread_id IN (${c})
|
|
523
|
+
${n?sql`AND own.workspace_id = ${n}`:sql``}
|
|
524
|
+
`;for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let l=U(u);try{let p=l.db.all(sql`
|
|
525
|
+
${this.descendantTraversalSql(d,sql`SELECT own.task_id FROM own_tasks own`,zr)}
|
|
526
|
+
SELECT
|
|
527
|
+
descendant_ids.root_task_id AS root_task_id,
|
|
528
|
+
task.status AS status,
|
|
529
|
+
task.error AS error,
|
|
530
|
+
task.metadata AS metadata,
|
|
531
|
+
count(*) AS task_count
|
|
532
|
+
FROM descendant_ids
|
|
533
|
+
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
534
|
+
WHERE NOT ${this.descendantSkippedSql("task")}
|
|
535
|
+
GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
|
|
536
|
+
`);for(let _ of p){let h=s[_.root_task_id]??=ya(i);Ta(h,De(_),dt(_),_.task_count);}}catch(p){throw p instanceof f?p:new f("DB_ERROR","Failed to batch summarize thread task statuses",p)}finally{l.close();}}return {tasksByThread:o,descendantSummaryByTaskId:s}}listDescendantsByTaskId(e,n,r={}){let o=new Set(r.states??kk),s=Bl(r.limit,Ul,Ul),i=Bl(r.maxDepth,zr,zr),c=r.cursor?wk(r.cursor):void 0;for(let d of this.resolveDbPaths()){if(!existsSync(d))continue;let u=U(d);try{if(!u.db.get(sql`
|
|
537
|
+
SELECT anchor.id FROM tasks anchor
|
|
538
|
+
WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
|
|
539
|
+
`))continue;let p=sql`
|
|
540
|
+
SELECT own.id
|
|
541
|
+
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
542
|
+
WHERE own.thread_id = (
|
|
543
|
+
SELECT anchor.thread_id FROM tasks anchor
|
|
544
|
+
WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
|
|
545
|
+
)
|
|
546
|
+
AND own.workspace_id = ${n}
|
|
547
|
+
`,_=u.db.all(sql`
|
|
548
|
+
${this.descendantTraversalSql(p,sql`SELECT ${e}`,i)}
|
|
549
|
+
SELECT
|
|
550
|
+
task.id AS task_id,
|
|
551
|
+
task.parent_task_id AS parent_task_id,
|
|
552
|
+
task.status AS status,
|
|
553
|
+
task.error AS error,
|
|
554
|
+
task.metadata AS metadata,
|
|
555
|
+
task.started_at AS started_at,
|
|
556
|
+
descendant_ids.depth AS depth,
|
|
557
|
+
parent.agent_id AS parent_agent_id,
|
|
558
|
+
CASE
|
|
559
|
+
WHEN descendant_ids.depth >= ${i}
|
|
560
|
+
AND EXISTS (
|
|
561
|
+
SELECT 1 FROM tasks deeper INDEXED BY idx_tasks_parent_task_id
|
|
562
|
+
WHERE deeper.parent_task_id = task.id
|
|
563
|
+
)
|
|
564
|
+
THEN 1 ELSE 0
|
|
565
|
+
END AS has_deeper,
|
|
566
|
+
CASE WHEN ${this.descendantSkippedSql("task")} THEN 1 ELSE 0 END AS skipped
|
|
567
|
+
FROM descendant_ids
|
|
568
|
+
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
569
|
+
LEFT JOIN tasks parent ON parent.id = task.parent_task_id
|
|
570
|
+
`),h=ya(new Date().toISOString()),m=!1,k=[];for(let D of _){if(D.has_deeper&&(m=!0),D.skipped)continue;let A=De(D);Ta(h,A,dt(D),1),o.has(A)&&k.push({row:D,key:[yk(A),D.started_at?D.started_at:null,D.task_id]});}k.sort((D,A)=>ql(D.key,A.key));let w=c?k.filter(D=>ql(D.key,c)>0):k,x=w.slice(0,s),T=w.length>x.length?Tk(x[x.length-1].key):null,L=new Map;if(x.length>0){let D=u.db.select(pe).from(a).where(inArray(a.id,x.map(A=>A.row.task_id))).all();for(let A of D)L.set(A.id,jr(A));}let N=[];for(let{row:D}of x){let A=L.get(D.task_id);!A||!D.parent_task_id||N.push({task:A,parentTaskId:D.parent_task_id,parentAgentId:D.parent_agent_id,depth:D.depth});}return {rows:N,summary:h,nextCursor:T,traversalTruncated:m}}catch(l){throw l instanceof f?l:new f("DB_ERROR","Failed to list task descendants",l)}finally{u.close();}}}findInterceptedRequests(e){let n=new Map;if(e.length===0)return n;for(let r of this.resolveDbPaths()){if(!existsSync(r))continue;let o=U(r);try{let s=o.db.all(sql`
|
|
571
|
+
SELECT task_id, input FROM task_provider_inputs
|
|
572
|
+
WHERE run_epoch = 0
|
|
573
|
+
AND task_id IN (${sql.join(e.map(i=>sql`${i}`),sql`, `)})
|
|
574
|
+
`);for(let i of s)n.set(i.task_id,i.input);}catch{}finally{o.close();}}return n}findTopLevelTasks(e,n,r,o){let s=this.resolveDbPaths(),i=o?sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${o})`:this.topLevelTaskPredicateSql(),c=new Set,d=[];for(let u of s){if(!existsSync(u))continue;let l=U(u);try{let p;r!==void 0?p=l.db.all(sql`
|
|
280
575
|
SELECT * FROM (
|
|
281
576
|
SELECT child.*,
|
|
282
577
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
283
578
|
FROM tasks child
|
|
284
|
-
WHERE child.thread_id = ${
|
|
285
|
-
AND ${
|
|
286
|
-
${
|
|
579
|
+
WHERE child.thread_id = ${e}
|
|
580
|
+
AND ${i}
|
|
581
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
287
582
|
) ranked
|
|
288
|
-
WHERE rn <= ${
|
|
583
|
+
WHERE rn <= ${r}
|
|
289
584
|
ORDER BY started_at ASC
|
|
290
|
-
`):l
|
|
585
|
+
`):p=l.db.all(sql`
|
|
291
586
|
SELECT child.* FROM tasks child
|
|
292
|
-
WHERE child.thread_id = ${
|
|
293
|
-
AND ${
|
|
294
|
-
${
|
|
587
|
+
WHERE child.thread_id = ${e}
|
|
588
|
+
AND ${i}
|
|
589
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
295
590
|
ORDER BY child.started_at ASC
|
|
296
|
-
`);for(let
|
|
591
|
+
`);for(let _ of p)c.has(_.id)||(c.add(_.id),d.push(jr(_)));}catch(p){throw new f("DB_ERROR","Failed to find top-level tasks",p)}finally{l.close();}}if(r!==void 0&&s.length>1){let u=new Map;for(let l of d){let p=l.agent_id??"";u.has(p)||u.set(p,[]),u.get(p).push(l);}d=[];for(let l of u.values())l.sort((p,_)=>(_.started_at??"").localeCompare(p.started_at??"")),d.push(...l.slice(0,r));d.sort((l,p)=>(l.started_at??"").localeCompare(p.started_at??""));}return d}findAllTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let c=U(i);try{let d=eq(a.thread_id,e),u=n?and(d,eq(a.workspace_id,n)):d,l=c.db.select(pe).from(a).where(u).orderBy(asc(a.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(jr(p)));}catch(d){throw new f("DB_ERROR","Failed to find all tasks for thread",d)}finally{c.close();}}return s}findRespondedAgents(e,n){let r=this.resolveDbPaths(),o=new Map;for(let s of r){if(!existsSync(s))continue;let i=U(s,{readOnly:true});try{let c=[eq(a.thread_id,e),sql`${a.completed_at} IS NOT NULL`,sql`length(trim(coalesce(${a.result}, ''))) > 0`];n&&c.push(eq(a.workspace_id,n));let d=i.db.select({agentId:a.agent_id,lastRepliedAt:sql`MAX(${a.completed_at})`}).from(a).where(and(...c)).groupBy(a.agent_id).all();for(let u of d){let l=o.get(u.agentId);u.lastRepliedAt&&(!l||u.lastRepliedAt>l)&&o.set(u.agentId,u.lastRepliedAt);}}catch(c){throw new f("DB_ERROR","Failed to find responded agents for thread",c)}finally{i.close();}}return [...o.entries()].map(([s,i])=>({agentId:s,lastRepliedAt:i})).sort((s,i)=>(s.lastRepliedAt===i.lastRepliedAt?0:s.lastRepliedAt>i.lastRepliedAt?-1:1)||(s.agentId===i.agentId?0:s.agentId<i.agentId?-1:1))}findTaskById(e,n,r){let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=U(s);try{let c=and(eq(a.id,n),eq(a.thread_id,e)),d=r?and(c,eq(a.workspace_id,r)):c,u=i.db.select(pe).from(a).where(d).limit(1).get();if(!u)continue;let l=i.db.select(pe).from(a).where(eq(a.parent_task_id,u.id)).orderBy(asc(a.started_at)).all().map(jr);return {task:jr(u),children:l}}catch(c){throw new f("DB_ERROR","Failed to find task by id",c)}finally{i.close();}}}batchFetchTasksQuery(e,n){return sql`
|
|
297
592
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
298
593
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
299
594
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
300
|
-
child.cost_usd, child.error
|
|
595
|
+
child.cost_usd, child.error, child.rating, child.rated_at, child.metadata
|
|
301
596
|
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
302
|
-
WHERE child.thread_id IN (${sql.join(
|
|
597
|
+
WHERE child.thread_id IN (${sql.join(e.map(r=>sql`${r}`),sql`, `)})
|
|
303
598
|
AND ${this.topLevelTaskPredicateSql()}
|
|
304
|
-
${
|
|
599
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
305
600
|
ORDER BY child.started_at ASC
|
|
306
|
-
`}batchFetchTasks(
|
|
601
|
+
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=U(s);try{let c=i.db.all(this.batchFetchTasksQuery(e,n));for(let d of c){let u=d.thread_id;r.has(u)||r.set(u,[]),r.get(u).push(mk(d));}}catch(c){throw new f("DB_ERROR","Failed to batch fetch tasks",c)}finally{i.close();}}return r}findThreadOriginsQuery(e,n){return sql`
|
|
602
|
+
WITH root AS (
|
|
603
|
+
SELECT child.thread_id, child.id, child.caller_agent_id, child.parent_task_id,
|
|
604
|
+
CASE
|
|
605
|
+
WHEN json_valid(child.metadata) = 1
|
|
606
|
+
THEN json_extract(child.metadata, '$.schedule_id')
|
|
607
|
+
ELSE NULL
|
|
608
|
+
END AS schedule_id,
|
|
609
|
+
child.platform,
|
|
610
|
+
ROW_NUMBER() OVER (
|
|
611
|
+
PARTITION BY child.thread_id
|
|
612
|
+
ORDER BY child.started_at ASC, child.id ASC
|
|
613
|
+
) AS rn
|
|
614
|
+
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
615
|
+
WHERE child.thread_id IN (${sql.join(e.map(r=>sql`${r}`),sql`, `)})
|
|
616
|
+
AND ${this.topLevelTaskPredicateSql("child","idx_tasks_thread_creator")}
|
|
617
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
618
|
+
)
|
|
619
|
+
SELECT root.id AS task_id, root.thread_id, root.caller_agent_id, root.parent_task_id,
|
|
620
|
+
root.schedule_id, root.platform,
|
|
621
|
+
parent.thread_id AS parent_thread_id, parent.agent_id AS parent_agent_id
|
|
622
|
+
FROM root
|
|
623
|
+
LEFT JOIN tasks parent INDEXED BY idx_tasks_thread_creator
|
|
624
|
+
ON parent.id = root.parent_task_id
|
|
625
|
+
WHERE root.rn = 1
|
|
626
|
+
`}findCreatorPointersQuery(e,n){let r=[sql`thread.id IN (${sql.join(e.map(o=>sql`${o}`),sql`, `)})`];return n&&r.unshift(sql`thread.workspace_id = ${n}`),sql`
|
|
627
|
+
SELECT thread.id AS thread_id, thread.created_by_kind, thread.created_by_id,
|
|
628
|
+
thread.created_by_task_id,
|
|
629
|
+
creator.id AS creator_task_id,
|
|
630
|
+
creator.actor_kind AS creator_actor_kind,
|
|
631
|
+
creator.actor_id AS creator_actor_id,
|
|
632
|
+
CASE WHEN unverified.thread_id IS NULL THEN 0 ELSE 1 END AS creator_pointer_unverified
|
|
633
|
+
FROM threads AS thread
|
|
634
|
+
LEFT JOIN tasks AS creator INDEXED BY idx_tasks_thread_creator
|
|
635
|
+
ON creator.id = thread.created_by_task_id
|
|
636
|
+
AND creator.thread_id = thread.id
|
|
637
|
+
LEFT JOIN thread_creator_unverified AS unverified
|
|
638
|
+
ON unverified.thread_id = thread.id
|
|
639
|
+
AND unverified.created_by_task_id = thread.created_by_task_id
|
|
640
|
+
WHERE ${sql.join(r,sql` AND `)}
|
|
641
|
+
`}findTaskOriginLineageQuery(e){return sql`
|
|
642
|
+
SELECT child.id AS task_id, child.thread_id, child.caller_agent_id, child.parent_task_id,
|
|
643
|
+
CASE
|
|
644
|
+
WHEN json_valid(child.metadata) = 1
|
|
645
|
+
THEN json_extract(child.metadata, '$.schedule_id')
|
|
646
|
+
ELSE NULL
|
|
647
|
+
END AS schedule_id,
|
|
648
|
+
child.platform,
|
|
649
|
+
parent.thread_id AS parent_thread_id, parent.agent_id AS parent_agent_id
|
|
650
|
+
FROM tasks AS child
|
|
651
|
+
LEFT JOIN tasks AS parent ON parent.id = child.parent_task_id
|
|
652
|
+
WHERE child.id IN (${sql.join(e.map(n=>sql`${n}`),sql`, `)})
|
|
653
|
+
`}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=U(s);try{for(let c=0;c<e.length;c+=rs){let d=e.slice(c,c+rs),l=i.db.all(this.findCreatorPointersQuery(d,n)).filter(T=>!r.has(T.thread_id)),p=l.filter(T=>T.creator_task_id!==null&&T.creator_pointer_unverified===0&&T.creator_actor_kind===null).map(T=>T.creator_task_id),_=p.length>0?i.db.all(this.findTaskOriginLineageQuery(p)):[],h=new Map(_.map(T=>[T.task_id,T])),m=new Map(l.map(T=>[T.thread_id,T])),k=d.filter(T=>{if(r.has(T))return !1;let L=m.get(T);return L?!(L.creator_task_id!==null&&L.creator_pointer_unverified===0)&&L.created_by_kind===null:!0}),w=k.length>0?i.db.all(this.findThreadOriginsQuery(k,n)):[],x=new Map(w.map(T=>[T.thread_id,T]));for(let T of l){if(r.has(T.thread_id))continue;let L=$l(T,T.created_by_task_id!==null?h.get(T.created_by_task_id):void 0,x.get(T.thread_id));L&&r.set(T.thread_id,L);}for(let T of w)r.has(T.thread_id)||m.has(T.thread_id)||r.set(T.thread_id,ts(T));}}catch(c){throw new f("DB_ERROR","Failed to fetch thread origins",c)}finally{i.close();}}return r}findThreadsByOrigin(e,n){let r=this.readThreadIds(n,"Failed to find threads by origin"),o=this.findThreadOrigins(r,n),s=r.filter(c=>Wl(o.get(c),e));return this.readThreadRowsByIds(s,n,"Failed to find threads by origin").sort(Gl)}findRecentDirectThreads(e,n=5){if(typeof e!="string"||e.trim().length===0)throw new f("VALIDATION","workspaceId is required");if(!Number.isInteger(n)||n<=0)throw new f("VALIDATION","limit must be a positive integer");let r=this.readThreadSortKeys(e).sort(Gl),o=[],s=new Map;for(let u=0;u<r.length;u+=Fl){let l=r.slice(u,u+Fl),p=this.findThreadOrigins(l.map(_=>_.id),e);for(let[_,h]of p)s.set(_,h);for(let _ of l)if(Wl(p.get(_.id),"direct")&&(o.push(_.id),o.length===n))break;if(o.length===n)break}let i=new Map;if(o.length>0){let u=this.readThreadRowsByIds(o,e,"Failed to find recent direct threads");for(let l of u)i.set(l.id,l);}let c=[],d=new Map;for(let u of o){let l=i.get(u);if(!l)continue;c.push(l);let p=s.get(u);p&&d.set(u,p);}return {threads:c,originsByThread:d}}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=U(o);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(c=>c.detail)}finally{s.close();}}return []}explainFindThreadOriginsPlan(e,n){if(e.length===0)return [];let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=U(o);try{let i=s.db.all(sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery(e,n)}`),c=s.db.all(sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery(e)}`),d=s.db.all(sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery(e,n)}`);return [...i,...c,...d].map(u=>u.detail)}finally{s.close();}}return []}explainFindThreadsByOriginPlan(e,n){let r=`__thread_origin_${e}_plan__`,o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=U(s);try{let c=i.db.all(sql`EXPLAIN QUERY PLAN ${this.findThreadIdsQuery(n)}`),d=i.db.all(sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery([r],n)}`),u=i.db.all(sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery([r])}`),l=i.db.all(sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery([r],n)}`);return [...c,...d,...u,...l].map(p=>p.detail)}finally{i.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=eq(y.id,e),i=r?and(s,eq(y.workspace_id,r)):s;if(!o.db.select({id:y.id}).from(y).where(i).limit(1).get())return;o.db.update(y).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(y.id,e)).run();}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{let i=(n.workspaceId?o.select({id:le.id}).from(le).where(eq(le.id,n.workspaceId)).limit(1).get():void 0)?n.workspaceId:null,c=new Date().toISOString(),d=o.select({id:y.id,message_count:y.message_count,created_by_task_id:y.created_by_task_id}).from(y).where(eq(y.id,e)).limit(1).get();if(d){let u={updated_at:c};n.title!==void 0&&(u.title=n.title),n.titleLocked!==void 0&&(u.title_locked=n.titleLocked?1:0),d.created_by_task_id===null&&n.createdByTaskId!=null&&d.message_count===0&&!jl(o,e,n.createdByTaskId)&&(u.created_by_task_id=n.createdByTaskId),o.update(y).set(u).where(eq(y.id,e)).run();}else o.insert(y).values({id:e,platform:n.platform,workspace_id:i,created_by_kind:null,created_by_id:null,created_by_task_id:n.createdByTaskId??null,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:c,updated_at:c}).run();},{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to upsert thread",o)}finally{r.close();}}ensureThread(e,n,r,o){let s=this.openHandle(true);try{s.db.transaction(i=>{let d=(r?i.select({id:le.id}).from(le).where(eq(le.id,r)).limit(1).get():void 0)?r:null,u=i.select({id:y.id,platform:y.platform,workspace_id:y.workspace_id,message_count:y.message_count,created_by_task_id:y.created_by_task_id}).from(y).where(eq(y.id,e)).limit(1).get();if(u){let p={};d&&!u.workspace_id&&(p.workspace_id=d),u.created_by_task_id===null&&o?.createdByTaskId!=null&&u.message_count===0&&!jl(i,e,o.createdByTaskId)&&(p.created_by_task_id=o.createdByTaskId),Object.keys(p).length>0&&i.update(y).set(p).where(eq(y.id,e)).run();return}let l=new Date().toISOString();i.insert(y).values({id:e,platform:n,workspace_id:d,created_by_kind:null,created_by_id:null,created_by_task_id:o?.createdByTaskId??null,message_count:0,created_at:l,updated_at:l}).run();},{behavior:"immediate"});}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to ensure thread",i)}finally{s.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(c=>{let u=c.select({message_count:y.message_count}).from(y).where(eq(y.id,e)).limit(1).get()?.message_count===0;return c.run(sql`
|
|
307
654
|
UPDATE threads
|
|
308
|
-
SET first_message = COALESCE(first_message, ${
|
|
309
|
-
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${
|
|
310
|
-
last_message = ${
|
|
655
|
+
SET first_message = COALESCE(first_message, ${n}),
|
|
656
|
+
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
657
|
+
last_message = ${n},
|
|
311
658
|
message_count = message_count + 1,
|
|
312
|
-
updated_at = ${
|
|
313
|
-
WHERE id = ${
|
|
314
|
-
`),l},{behavior:"immediate"})}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save user message",o)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.update(p).set({last_message:e,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save assistant message",o)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(p).set(s).where(eq(p.id,t)).run();}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to update thread",s)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let s=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(s).get();if(!o)return null;let i=o.pinned?0:1,a=o.metadata?JSON.parse(o.metadata):{};if(i){let c=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),l=n.db.select({metadata:p.metadata}).from(p).where(c).all(),u=0;for(let g of l){let h=g.metadata?JSON.parse(g.metadata):{};typeof h.pinOrder=="number"&&h.pinOrder>u&&(u=h.pinOrder);}a.pinOrder=u+1;}else delete a.pinOrder;return n.db.update(p).set({pinned:i,metadata:Object.keys(a).length>0?JSON.stringify(a):null}).where(s).run(),{pinned:!!i}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to toggle pin",s)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let s=0;s<t.length;s++){let o=e?and(eq(p.id,t[s]),eq(p.workspace_id,e)):eq(p.id,t[s]),i=n.db.select({metadata:p.metadata}).from(p).where(o).get();if(!i)continue;let a=i.metadata?JSON.parse(i.metadata):{};a.pinOrder=s+1,n.db.update(p).set({metadata:JSON.stringify(a)}).where(o).run();}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to reorder pins",s)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let s=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({starred:p.starred}).from(p).where(s).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(p).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,s){let i=this.openHandle(true);try{let a=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return i.db.transaction(l=>{let u=l.select({metadata:p.metadata}).from(p).where(a).get();if(!u)return null;let g=u.metadata?JSON.parse(u.metadata):{},h=g.overdrive??{},T=s?.defaultTurns??h.defaultTurns??3,X=s?.updatedBy??"ui",U=new Date().toISOString(),O,$,L,Q;switch(n){case "enable-count":{let Z=s?.turns??T,tt=s?.consumeCurrent?Math.max(Z-1,0):Z;O=tt>0?"count":"off",$=tt,L=!0,Q="count";break}case "enable-latch":{O="latch",$=0,L=!0,Q="latch";break}case "disable":{O="off",$=0,L=!1;break}default:{let Z=h.state??"off",tt=typeof h.remaining=="number"?h.remaining:0;if(Z==="count"&&tt>0){let bt=tt-1;bt<=0?(O="off",$=0):(O="count",$=bt),L=!0,Q="count";}else Z==="latch"?(O="latch",$=0,L=!0,Q="latch"):(O="off",$=0,L=!1);break}}return g.overdrive={state:O,remaining:$,defaultTurns:T,updatedAt:U,updatedBy:X},l.update(p).set({metadata:JSON.stringify(g),updated_at:U}).where(a).run(),{applied:L,appliedMode:Q,state:O,remaining:$}},{behavior:"immediate"})}catch(a){throw a instanceof _?a:new _("DB_ERROR","Failed to resolve overdrive",a)}finally{i.close();}}};function He(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
`)
|
|
318
|
-
`)
|
|
659
|
+
updated_at = ${s}
|
|
660
|
+
WHERE id = ${e}
|
|
661
|
+
`),u},{behavior:"immediate"})}}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(y).set({last_message:n,updated_at:s}).where(eq(y.id,e)).run();}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};n.title!==void 0&&(o.title=n.title,o.title_locked=1),n.titleLocked!==void 0&&(o.title_locked=n.titleLocked?1:0),r.db.update(y).set(o).where(eq(y.id,e)).run();}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let o=n;if(!o||typeof o!="object"||Array.isArray(o))return new nr("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(d=>d!=="priority"&&d!=="state"))return new nr("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new nr("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [i.priority,i.state])if(d!=null&&(typeof d!="string"||d.length===0))return new nr("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let c=this.openHandle(true);try{let d=r?and(eq(y.id,e),eq(y.workspace_id,r)):eq(y.id,e);return c.db.transaction(u=>{let l=u.select({metadata:y.metadata}).from(y).where(d).get();if(!l)return null;let p=rr(l.metadata),_=p.threadTitle,h=_&&typeof _=="object"&&!Array.isArray(_)?{..._}:{};i.priority===null?delete h.priority:i.priority!==void 0&&(h.priority=i.priority),i.state===null?delete h.state:i.state!==void 0&&(h.state=i.state),Object.keys(h).length>0?p.threadTitle=h:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,k=new Date().toISOString();u.update(y).set({metadata:m,updated_at:k}).where(d).run();let w=u.select({metadata:y.metadata}).from(y).where(d).get();if(!w)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let x=Rk(w.metadata);return {threadId:e,priority:x.priority,state:x.state}},{behavior:"immediate"})}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to patch thread-title metadata",d)}finally{c.close();}}togglePin(e,n){let r=this.openHandle(true);try{return r.db.transaction(o=>Sk(o,e,n),{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>Ik(o,e,n),{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?and(eq(y.id,e),eq(y.workspace_id,n)):eq(y.id,e),s=r.db.select({starred:y.starred}).from(y).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(y).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let c=n?and(eq(y.id,e),eq(y.workspace_id,n)):eq(y.id,e);return i.db.transaction(u=>{let l=u.select({metadata:y.metadata}).from(y).where(c).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},_=p.overdrive??{},h=o?.defaultTurns??_.defaultTurns??3,m=o?.updatedBy??"ui",k=new Date().toISOString(),w,x,T,L;switch(r){case "enable-count":{let N=o?.turns??h,D=o?.consumeCurrent?Math.max(N-1,0):N;w=D>0?"count":"off",x=D,T=!0,L="count";break}case "enable-latch":{w="latch",x=0,T=!0,L="latch";break}case "disable":{w="off",x=0,T=!1;break}default:{let N=_.state??"off",D=typeof _.remaining=="number"?_.remaining:0;if(N==="count"&&D>0){let A=D-1;A<=0?(w="off",x=0):(w="count",x=A),T=!0,L="count";}else N==="latch"?(w="latch",x=0,T=!0,L="latch"):(w="off",x=0,T=!1);break}}return p.overdrive={state:w,remaining:x,defaultTurns:h,updatedAt:k,updatedBy:m},u.update(y).set({metadata:JSON.stringify(p),updated_at:k}).where(c).run(),{applied:T,appliedMode:L,state:w,remaining:x}},{behavior:"immediate"})}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to resolve overdrive",c)}finally{i.close();}}};g();vt();Bt();Ft();Ot();g();var wa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Ak(t){let e=randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=wa[o%62]);}for(;n.length<t;)n+=wa[randomBytes(1)[0]%62];return n}function Mt(t){return `${t}_${Ak(8)}`}function Kl(t,e){let{createHash:n}=An("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=wa[i%62];return `${t}_${s}`}jt();g();var Nk=["urgent","high","medium","low"],Ok=["investigating","in-progress","in-review","on-hold","done"],Jl="custom:";var vk=new Set(Nk),bk=new Set(Ok);function Ea(t){return typeof t=="string"&&vk.has(t)}function Ra(t){if(typeof t!="string")return false;if(bk.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Jl))return false;let e=t.slice(Jl.length);return e.length>=1&&e.length<=20}function Vl(t){if(!t)return null;try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function Sa(t){let e=Vl(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return Ea(r.priority)&&(o.priority=r.priority),Ra(r.state)&&(o.state=r.state),o}function Xl(t,e){let n=Vl(t)??{},r={...Sa(t)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete n.threadTitle:n.threadTitle=r,Object.keys(n).length===0?null:JSON.stringify(n)}Jn();var Lk="regeneration_replaced";var Mk="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var $k="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Na=class extends f{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=o;}},Zr=class extends Na{},Oa=class extends f{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Hk=new Set(Hd),Uk=new Set($d),qk=new Set(Ud),Bk=new Set(qd),Fk=50,Ql=100,Zl=280,ep=40,Wk=new Set(Bd),ss=["queued","running"];function Aa(t){return Wk.has(t)}function Z(t){throw new f("VALIDATION",t)}function _t(t){throw new f("NOT_FOUND",t)}function B(t,e){(typeof t!="string"||t.trim().length===0)&&Z(`${e} is required`);}function Jr(t={}){let e=t.actor??t,n=e.actorType??"system";return Hk.has(n)||Z(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&Z("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Gk(t){B(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&B(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&Z("title must not be empty"),t.title.length>120&&Z("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Ea(t.priority)&&Z(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Ra(t.state)&&Z(`invalid state: ${String(t.state)}`);}function jk(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&Z("beforeSeq and afterSeq cannot be used together");for(let[n,r]of [["beforeSeq",t.beforeSeq],["afterSeq",t.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&Z(`${n} must be a non-negative integer`);let e=t.limit??Fk;return (!Number.isInteger(e)||e<1||e>Ql)&&Z(`limit must be between 1 and ${Ql}`),e}function va(t){typeof t!="string"&&Z("text is required");let e=t.trim();return e.length===0&&Z("text must not be empty"),e.length>Zl&&Z(`text must be at most ${Zl} characters`),e}function $t(t,e){return B(t??"",e),t}function ba(t){Bk.has(t)||Z(`invalid highlight kind: ${String(t)}`);}function zk(t){qk.has(t)||Z(`invalid highlight source: ${String(t)}`);}function Kk(t){B(t.threadId,"threadId"),B(t.workspaceId,"workspaceId");let e=t.source??"manual";zk(e),ba(t.kind);let n=va(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&o&&r===o?r:void 0),p=$t(l,"taskId");return (r!==p||o!==p)&&Z("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=$t(r,"coversFromTaskId"),i=$t(o,"coversToTaskId"),c=t.sourceTaskId??s,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),u=t.contentFingerprint??t.idempotencyKey??null;return $t(c??void 0,"sourceTaskId"),$t(d??void 0,"detectorVersion"),$t(u??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:c,detectorVersion:d,contentFingerprint:u}}function Jk(t,e){(!t||typeof t!="object")&&Z(`candidates[${e}] is required`),ba(t.kind);let n=va(t.text),r=$t(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=$t(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=$t(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Kl("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return B(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function Vk(t){Array.isArray(t)||Z("candidates must be an array"),t.length>ep&&Z(`candidates must contain at most ${ep} items`);let e=new Map;for(let[n,r]of t.entries()){let o=Jk(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function Qr(t){let e=Sa(t.metadata);return {threadId:t.id,workspaceId:t.workspace_id,title:t.title,priority:e.priority??null,state:e.state??null,metadata:t.metadata,titleLocked:t.title_locked===1,updatedAt:t.updated_at}}function Xk(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&Z("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function Vr(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${Y.seq}), 0)`}).from(Y).where(eq(Y.thread_id,e)).get()?.maxSeq??0}function Xr(t,e){return !!t.select({id:Y.id}).from(Y).where(eq(Y.thread_id,e)).limit(1).get()}function Sn(t,e){Uk.has(e.type)||Z(`invalid thread event type: ${String(e.type)}`);let n=Mt("the");t.insert(Y).values({id:n,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:Xk(e.payload),created_at:e.createdAt}).run();let r=t.select().from(Y).where(eq(Y.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function Yr(t,e,n,r,o){let s=Qr(e);Sn(t,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function as(t){return {highlightId:t.id,source:t.source,kind:t.kind,status:t.status,coversFromTaskId:t.covers_from_task_id,coversToTaskId:t.covers_to_task_id,revision:t.revision,...t.dismissed_at===null?{}:{dismissedAt:t.dismissed_at}}}function is(t,e,n,r,o,s,i){let c=o==="thread.highlight.created"?as(e):{before:i?as({...e,...i,id:e.id}):void 0,after:as(e)};return Sn(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:c})}function Yk(t,e,n,r,o,s){return Sn(t,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:as(e),...s??{}}})}var ds=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!existsSync(n))throw new f("NOT_FOUND","Database not found");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=U(n);if(e)try{Le(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=eq(y.id,n),s=r===void 0?o:r===null?and(o,isNull(y.workspace_id)):and(o,eq(y.workspace_id,r));return e.select().from(y).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(K).where(eq(K.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(B(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:y.workspace_id}).from(y).where(eq(y.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(B(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?Qr(o):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Gk(e);let n=Jr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||_t(`Thread ${e.threadId} not found`);let c=Qr(i),d=e.title!==void 0,u=d&&e.title!==c.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==c.priority,_=e.state!==void 0&&e.state!==c.state,h=u||p||_;if(!h&&!l)return c;let m=i.metadata;(p||_)&&(m=Xl(i.metadata,{priority:e.priority,state:e.state}));let k={};if(h&&(k.metadata=m,k.updated_at=r),u&&(k.title=e.title),d&&(k.title_locked=1),s.update(y).set(k).where(e.workspaceId===void 0?eq(y.id,e.threadId):e.workspaceId===null?and(eq(y.id,e.threadId),isNull(y.workspace_id)):and(eq(y.id,e.threadId),eq(y.workspace_id,e.workspaceId))).run(),!h){let T={...i,title_locked:1};return Qr(T)}let w=Vr(s,i.id)+1;Xr(s,i.id)||(Yr(s,i,n,r,w),w+=1),u&&(Sn(s,{threadId:i.id,seq:w,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.title,after:e.title}}),w+=1),p&&(Sn(s,{threadId:i.id,seq:w,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.priority,after:e.priority}}),w+=1),_&&Sn(s,{threadId:i.id,seq:w,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:c.state,after:e.state}});let x={...i,title:u?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return Qr(x)},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(B(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:sql`COALESCE(MAX(${Y.seq}), 0)`}).from(Y).where(eq(Y.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(B(e,"threadId"),B(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(and(eq(a.thread_id,e),eq(a.workspace_id,n),inArray(a.status,[...En]),or(isNull(a.parent_task_id),eq(a.parent_task_id,"")),sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(asc(a.started_at),asc(a.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){B(e.threadId,"threadId"),B(e.workspaceId,"workspaceId"),B(e.requestId,"requestId"),B(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&B(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||_t(`Thread ${e.threadId} not found`);let i=o.select().from(K).where(and(eq(K.thread_id,s.id),eq(K.request_id,e.requestId))).orderBy(desc(K.requested_at),desc(K.id)).limit(1).get();if(i)return {run:i,created:!1};let c=o.select().from(K).where(and(eq(K.thread_id,s.id),inArray(K.status,ss))).orderBy(asc(K.requested_at),asc(K.id)).limit(1).get();if(c)throw new Oa(c);let d=e.runId??Mt("thr");o.insert(K).values({id:d,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let u=o.select().from(K).where(eq(K.id,d)).get();if(!u)throw new f("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:u,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(B(e,"runId"),n!==void 0&&B(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(B(e,"threadId"),B(n,"workspaceId"),B(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(K).where(and(eq(K.thread_id,e),eq(K.request_id,r))).orderBy(desc(K.requested_at),desc(K.id)).limit(1).get()??null:null}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){B(e,"runId"),n!==void 0&&B(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,n);if(i||_t(`Highlight regeneration run ${e} not found`),Aa(i.status)||Z(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(K).set({status:"running",started_at:r}).where(and(eq(K.id,i.id),eq(K.status,"queued"))).run();let c=s.select().from(K).where(eq(K.id,i.id)).get();if(!c)throw new f("DB_ERROR","Highlight regeneration run start did not return a row");return c},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){B(e.runId,"runId"),B(e.errorCode,"errorCode"),e.workspaceId!==void 0&&B(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||_t(`Highlight regeneration run ${e.runId} not found`),Aa(s.status)||Z(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(K).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(K.id,s.id),inArray(K.status,ss))).run();let i=o.select().from(K).where(eq(K.id,s.id)).get();if(!i)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=Mk){B(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(K).set({status:"failed",completed_at:n,error_code:e}).where(inArray(K.status,ss)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){B(e.runId,"runId"),B(e.threadId,"threadId"),B(e.workspaceId,"workspaceId"),B(e.detectorVersion,"detectorVersion");let n=Vk(e.candidates),r=Jr(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let c=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!c||c.thread_id!==e.threadId)&&_t(`Highlight regeneration run ${e.runId} not found`),Aa(c.status)||Z(`invalid highlight regeneration status: ${c.status}`),c.status==="failed")throw new f("CONFLICT","Highlight regeneration run has already failed");if(c.status==="completed")return {run:c,deletedCount:0,createdCount:0,previousAutoCount:c.previous_auto_count??0,newAutoCount:c.new_auto_count??0};s=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||_t(`Thread ${e.threadId} not found`),c.detector_version!==e.detectorVersion&&Z("detectorVersion does not match the regeneration run");let u=i.select().from(F).where(eq(F.thread_id,d.id)).orderBy(asc(F.created_at),asc(F.id)).all(),l=new Set(n.map(A=>A.contentFingerprint)),p=u.filter(A=>A.source==="auto"&&A.status==="active"&&A.revision===0&&!l.has(A.content_fingerprint??"")),_=u.filter(A=>A.source==="auto"&&A.status==="active").length,h=new Set(u.filter(A=>!p.includes(A)&&A.content_fingerprint).map(A=>A.content_fingerprint)),m=n.filter(A=>!h.has(A.contentFingerprint)),k=new Date().toISOString(),w=Vr(i,d.id)+1;Xr(i,d.id)||(Yr(i,d,r,k,w),w+=1);for(let A of p)i.delete(F).where(eq(F.id,A.id)).run(),Yk(i,A,r,k,w,{runId:e.runId,reason:Lk}),w+=1;let x=0,T=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let A of m){let J=Mt("thl");i.insert(F).values({id:J,thread_id:d.id,source:"auto",kind:A.kind,status:"active",text:A.text,covers_from_task_id:A.coversFromTaskId,covers_to_task_id:A.coversToTaskId,revision:0,created_at:k,updated_at:k,agent_id:T,source_task_id:A.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:A.contentFingerprint,dismissed_at:null}).run();let oe=i.select().from(F).where(eq(F.id,J)).get();if(!oe)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");is(i,oe,r,k,"thread.highlight.created",w),w+=1,x+=1;}let N=i.select().from(F).where(eq(F.thread_id,d.id)).all().filter(A=>A.source==="auto"&&A.status==="active").length;Sn(i,{threadId:d.id,seq:w,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:c.id,detectorVersion:e.detectorVersion,previousAutoCount:_,newAutoCount:N,deletedCount:p.length,createdCount:x}}),i.update(K).set({status:"completed",started_at:c.started_at??k,completed_at:k,error_code:null,previous_auto_count:_,new_auto_count:N}).where(and(eq(K.id,c.id),inArray(K.status,ss))).run();let D=i.select().from(K).where(eq(K.id,c.id)).get();if(!D)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:D,deletedCount:p.length,createdCount:x,previousAutoCount:_,newAutoCount:N}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:$k});}catch{}throw i instanceof f?i:new f("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;B(o.threadId,"threadId"),B(o.workspaceId,"workspaceId");let s=jk(o);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let c=i.db.select({maxSeq:sql`COALESCE(MAX(${Y.seq}), 0)`}).from(Y).where(eq(Y.thread_id,o.threadId)).get()?.maxSeq??0,d;o.beforeSeq!==void 0?d=i.db.select().from(Y).where(and(eq(Y.thread_id,o.threadId),lt(Y.seq,o.beforeSeq))).orderBy(desc(Y.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?d=i.db.select().from(Y).where(and(eq(Y.thread_id,o.threadId),sql`${Y.seq} > ${o.afterSeq}`)).orderBy(asc(Y.seq)).limit(s+1).all():d=i.db.select().from(Y).where(eq(Y.thread_id,o.threadId)).orderBy(desc(Y.seq)).limit(s+1).all().reverse();let u=d.length>s,l=o.afterSeq!==void 0?d.slice(0,s):u?d.slice(1):d,p=!1,_=l[0];return _&&(p=!!i.db.select({id:Y.id}).from(Y).where(and(eq(Y.thread_id,o.threadId),lt(Y.seq,_.seq))).limit(1).get()),{items:l,latestSeq:c,hasMoreOlder:p}}catch(c){throw c instanceof f?c:new f("DB_ERROR","Failed to list thread timeline",c)}finally{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=Kk(e),r=Jr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);if(c||_t(`Thread ${e.threadId} not found`),n.source==="auto"){let _=i.select().from(F).where(and(eq(F.thread_id,e.threadId),eq(F.source_task_id,n.sourceTaskId),eq(F.detector_version,n.detectorVersion),eq(F.content_fingerprint,n.contentFingerprint))).orderBy(asc(F.created_at),asc(F.id)).limit(1).get();if(_)return _}let d=e.id??Mt("thl"),u={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(F).values(u).run();let l=i.select().from(F).where(eq(F.id,d)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=Vr(i,c.id)+1;return Xr(i,c.id)||(Yr(i,c,r,o,p),p+=1),is(i,l,r,o,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){B(e.threadId,"threadId"),B(e.workspaceId,"workspaceId"),B(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Z("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&Z("highlight update requires at least one field"),e.kind!==void 0&&ba(e.kind);let n=e.text===void 0?void 0:va(e.text),r=Jr(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let c=this.findThread(i,e.threadId,e.workspaceId);c||_t(`Thread ${e.threadId} not found`);let d=i.select().from(F).where(and(eq(F.id,e.highlightId),eq(F.thread_id,c.id))).limit(1).get();if(d||_t(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new Zr(c.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new Zr(c.id,d.id,e.expectedRevision,d.revision);let u=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,_=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||_.length===0)&&Z("highlight projection is incomplete");let h=u!==d.kind||l!==d.text||p!==d.covers_from_task_id||_!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&h?"manual":d.source;if(!(h||m!==d.source))return d;let w=d.revision+1;i.update(F).set({source:m,kind:u,text:l,covers_from_task_id:p,covers_to_task_id:_,revision:w,updated_at:o}).where(and(eq(F.id,d.id),eq(F.revision,d.revision))).run();let x=i.select().from(F).where(eq(F.id,d.id)).get();if(!x)throw new f("DB_ERROR","Highlight update did not return a row");let T=Vr(i,c.id)+1;return Xr(i,c.id)||(Yr(i,c,r,o,T),T+=1),is(i,x,r,o,"thread.highlight.updated",T,d),x},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){B(e.threadId,"threadId"),B(e.workspaceId,"workspaceId"),B(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Z("expectedRevision must be a non-negative integer");let n=Jr(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||_t(`Thread ${e.threadId} not found`);let c=s.select().from(F).where(and(eq(F.id,e.highlightId),eq(F.thread_id,i.id))).limit(1).get();if(c||_t(`Highlight ${e.highlightId} not found`),c.revision!==e.expectedRevision)throw new Zr(i.id,c.id,e.expectedRevision,c.revision);if(c.status==="dismissed")return c;let d=c.revision+1;s.update(F).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(and(eq(F.id,c.id),eq(F.revision,c.revision))).run();let u=s.select().from(F).where(eq(F.id,c.id)).get();if(!u)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=Vr(s,i.id)+1;return Xr(s,i.id)||(Yr(s,i,n,r,l),l+=1),is(s,u,n,r,"thread.highlight.deleted",l,c),u},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(B(e,"threadId"),B(n,"workspaceId"),r.taskId!==void 0&&B(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&B(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&B(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let i=o.db.select().from(F).where(and(eq(F.thread_id,e),eq(F.status,"active"))).orderBy(asc(F.created_at),asc(F.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let c=o.db.all(sql`
|
|
662
|
+
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
663
|
+
ORDER BY started_at ASC, id ASC
|
|
664
|
+
`),d=new Map(c.map((_,h)=>[_.id,h])),u=r.taskId===void 0?void 0:d.get(r.taskId),l=r.coversFromTaskId===void 0?void 0:d.get(r.coversFromTaskId),p=r.coversToTaskId===void 0?void 0:d.get(r.coversToTaskId);return i.filter(_=>{let h=d.get(_.covers_from_task_id),m=d.get(_.covers_to_task_id);if(h===void 0||m===void 0)return !1;let k=Math.min(h,m),w=Math.max(h,m);return !(u!==void 0&&(u<k||u>w)||l!==void 0&&w<l||p!==void 0&&k>p)})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};g();Bt();vt();Ot();Ft();Jn();jt();var In=12e3,ty=4,Pa=512*1024,ir=1,ee=class extends Error{code;constructor(e,n=e,r){super(n,r===void 0?void 0:{cause:r}),this.name="ThreadBranchRepositoryError",this.code=e;}};function Nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ny(t){if(!t)return {};try{let e=JSON.parse(t);return Nt(e)?e:{}}catch{return {}}}function Ut(t){let e="";for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r!==0){if(r>=55296&&r<=56319){let o=t.charCodeAt(n+1);o>=56320&&o<=57343&&(e+=t.slice(n,n+2),n+=1);continue}r>=56320&&r<=57343||(e+=t[n]);}}return e.replace(/</g,"<").replace(/>/g,">").replace(/\{\{/g,"{{")}function cs(t){if(!t)return;let e=Date.parse(t);return Number.isFinite(e)?e:void 0}function dp(t){if(!t)return "";try{let e=JSON.parse(t);if(Array.isArray(e)){let n=e.filter(r=>Nt(r)&&r.type==="text"&&typeof r.text=="string").map(r=>r.text);if(n.length>0)return n.join(`
|
|
665
|
+
`)}else if(Nt(e)&&e.result!==void 0)return typeof e.result=="string"?e.result:JSON.stringify(e.result)}catch{}return t}function cp(t){let e=ny(t),n=[e.attachments,e.files,e.images,e.attachmentReceiptContext],r=[];for(let o of n)if(Array.isArray(o))for(let s of o){if(!Nt(s))continue;let i=[s.filename,s.fileName,s.name].find(d=>typeof d=="string");if(i===void 0)continue;let c=[s.size,s.sizeBytes,s.bytes].find(d=>typeof d=="number"&&Number.isFinite(d)&&d>=0);r.push({filename:Ut(i),size:c===void 0?0:Math.floor(c)});}return r}function ry(t){return t.reduce((e,n)=>e+n.filename.length+String(n.size).length,0)}function oy(t){return t.user.length+t.assistant.length+ry(t.attachments)}function Ht(t){return t.reduce((e,n)=>e+oy(n),0)}function La(t){return `[truncated task=${Ut(t)}]`}function np(t,e,n){if(t.length<=e)return t;let r=La(n);if(e<=r.length)return r.slice(0,e);let o=e-r.length,s=Math.ceil(o/2),i=o-s;return `${t.slice(0,s)}${r}${i>0?t.slice(-i):""}`}function sy(t){return t.map(e=>({taskId:e.id,user:Ut(e.prompt),assistant:Ut(dp(e.result)),attachments:cp(e.metadata),truncated:false}))}function rp(t,e,n){let r=Ht(t);if(r<=e)return false;let o=false,s=[];for(let i of [...t].reverse()){s.push({turn:i,key:"assistant"},{turn:i,key:"user"});for(let c=i.attachments.length-1;c>=0;c-=1)s.push({turn:i,key:"filename",attachmentIndex:c});}for(let i of s){if(r<=e)break;let c=i.turn;if(i.key==="filename"){let h=i.attachmentIndex,m=c.attachments[h];if(!m.filename)continue;let k=La(c.taskId),w=c.taskId===n?k.length+1:k.length;if(m.filename.length<=w)continue;let x=Math.max(w,m.filename.length-(r-e)),T=np(m.filename,x,c.taskId);if(T.length>=m.filename.length)continue;c.attachments[h]={...m,filename:T},r=Ht(t),c.truncated=true,o=true;continue}let d=c[i.key];if(!d)continue;let u=La(c.taskId),l=c.taskId===n?u.length+1:u.length;if(d.length<=l)continue;let p=Math.max(l,d.length-(r-e)),_=np(d,p,c.taskId);_.length>=d.length||(c[i.key]=_,c.truncated=true,r=Ht(t),o=true);}return o}function iy(t){let e=sy(t),n=e.at(-1).taskId,r=Math.min(ty,e.length),o=e.slice(-r),s=false;Ht(o)>In&&(s=rp(o,In,n)||s);let i=[...o];for(let u=e.length-r-1;u>=0;u-=1){let l=e[u],p=[l,...i];if(Ht(p)<=In){i=p;continue}let _=In-Ht(i);if(_>0){let h=[{...l,attachments:[...l.attachments]},...i];rp([h[0]],_,n)&&Ht(h)<=In&&(i=h);}s=true;break}let c=i.map(u=>({taskId:u.taskId,user:u.user,assistant:u.assistant,attachments:u.attachments.map(l=>({...l})),...u.truncated?{truncated:true}:{}})),d=Ht(i);if(d>In)throw new ee("DATABASE_ERROR","Carry snapshot exceeded its character limit");return {version:ir,turns:c,turnsCount:c.length,chars:d,truncated:s||i.some(u=>u.truncated)}}function ay(t){return t.map(e=>{let n=cp(e.metadata),r={taskId:e.id,text:e.prompt,isAssistant:false,...cs(e.started_at)===void 0?{}:{timestamp:cs(e.started_at)},...n.length>0?{files:n}:{}},o={taskId:e.id,text:dp(e.result),isAssistant:true,...cs(e.completed_at??e.started_at)===void 0?{}:{timestamp:cs(e.completed_at??e.started_at)}};return {taskId:e.id,user:r,assistant:o}})}function op(t,e){let n={version:1,messages:t.flatMap(({user:r,assistant:o})=>[r,o]),...e?{truncated_before_task_id:e}:{}};return JSON.stringify(n)}function dy(t){let e=ay(t),n,r=op(e);for(;Buffer.byteLength(r,"utf8")>Pa&&e.length>1;){let s=e.shift();n??=s.taskId,r=op(e,n);}let o=Buffer.byteLength(r,"utf8");if(o>Pa)throw new ee("BRANCH_SOURCE_TOO_LARGE","Newest completed turn exceeds the branch history limit");return {sourceJson:r,bytes:o}}function sp(t,e,n){try{let r=JSON.parse(t);if(!Nt(r)||r.version!==ir||!Array.isArray(r.turns)||typeof r.turnsCount!="number"||typeof r.chars!="number"||typeof r.truncated!="boolean"||r.turnsCount!==e||r.chars!==n||r.turnsCount!==r.turns.length)throw new Error("invalid carry header");let o=r.turns.map(s=>{if(!Nt(s)||typeof s.taskId!="string"||typeof s.user!="string"||typeof s.assistant!="string"||!Array.isArray(s.attachments))throw new Error("invalid carry turn");let i=s.attachments.map(c=>{if(!Nt(c)||typeof c.filename!="string"||typeof c.size!="number")throw new Error("invalid carry attachment");return {filename:Ut(c.filename),size:Math.max(0,Math.floor(c.size))}});return {taskId:s.taskId,user:Ut(s.user),assistant:Ut(s.assistant),attachments:i,...s.truncated===!0?{truncated:!0}:{}}});if(Ht(o)!==r.chars||r.chars>In)throw new Error("carry metrics do not match");return {version:ir,turns:o,turnsCount:r.turnsCount,chars:r.chars,truncated:r.truncated}}catch(r){throw new ee("CORRUPT_BRANCH","Stored branch carry snapshot is invalid",r)}}function ip(t,e){try{if(Buffer.byteLength(t,"utf8")!==e||e>Pa)throw new Error("source byte count mismatch");let n=JSON.parse(t);if(!Nt(n)||n.version!==1||!Array.isArray(n.messages))throw new Error("invalid source header");return {version:1,messages:n.messages.map(o=>{if(!Nt(o)||typeof o.taskId!="string"||typeof o.text!="string"||typeof o.isAssistant!="boolean")throw new Error("invalid source message");let s=Array.isArray(o.files)?o.files.map(i=>{if(!Nt(i)||typeof i.filename!="string"||typeof i.size!="number")throw new Error("invalid source attachment");return {filename:i.filename,size:i.size}}):void 0;return {taskId:o.taskId,text:o.text,isAssistant:o.isAssistant,...typeof o.timestamp=="number"?{timestamp:o.timestamp}:{},...s&&s.length>0?{files:s}:{}}}),...typeof n.truncated_before_task_id=="string"?{truncated_before_task_id:n.truncated_before_task_id}:{}}}catch(n){throw new ee("CORRUPT_BRANCH","Stored branch history source is invalid",n)}}function cy(t){let e={workspaceId:t.workspaceId,parentThreadId:t.parentThreadId,actorId:t.actorId,prompt:t.prompt,model:t.model??null,provider:t.provider??null,effort:t.effort??null,attachments:(t.attachments??[]).map(n=>({filename:n.filename,size:n.size}))};return createHash("sha256").update(JSON.stringify(e)).digest("hex")}function xa(t){if(t.status!=="active"&&t.status!=="undone")throw new ee("CORRUPT_BRANCH","Stored branch has an unknown status");return {id:t.id,workspaceId:t.workspace_id,parentThreadId:t.parent_thread_id,childThreadId:t.child_thread_id,...t.child_title===null?{}:{childTitle:t.child_title},branchPointTaskId:t.branch_point_task_id,branchAnswerNo:t.branch_answer_no,firstTaskId:t.first_task_id,parentTitle:Ut(t.parent_title),actorId:t.actor_id,requestId:t.request_id,carriedTurns:t.carried_turns,carriedChars:t.carried_chars,carriedTruncated:t.carried_truncated===1,status:t.status,createdAt:t.created_at,...t.undone_at===null?{}:{undoneAt:t.undone_at}}}function ap(t,e){return t.get(sql`
|
|
666
|
+
SELECT thread_branches.id, thread_branches.workspace_id, thread_branches.parent_thread_id,
|
|
667
|
+
thread_branches.child_thread_id, child.title AS child_title,
|
|
668
|
+
thread_branches.branch_point_task_id, thread_branches.branch_answer_no,
|
|
669
|
+
thread_branches.first_task_id, thread_branches.parent_title, thread_branches.actor_id,
|
|
670
|
+
thread_branches.request_id, thread_branches.carried_turns, thread_branches.carried_chars,
|
|
671
|
+
thread_branches.carried_truncated, thread_branches.status, thread_branches.created_at,
|
|
672
|
+
thread_branches.undone_at
|
|
673
|
+
FROM thread_branches
|
|
674
|
+
LEFT JOIN threads AS child ON child.id = thread_branches.child_thread_id
|
|
675
|
+
WHERE ${e}
|
|
676
|
+
LIMIT 1
|
|
677
|
+
`)??void 0}var us=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!existsSync(n))throw new f("NOT_FOUND","Database not found");e&&!existsSync(dirname(n))&&mkdirSync(dirname(n),{recursive:true});let r=U(n);if(e)try{Le(r.db,n);}catch(o){throw r.close(),o}return r}async create(e){if(!e||typeof e.workspaceId!="string"||!e.workspaceId.trim()||typeof e.parentThreadId!="string"||!e.parentThreadId.trim()||typeof e.actorId!="string"||!e.actorId.trim()||typeof e.requestId!="string"||!e.requestId.trim()||typeof e.prompt!="string"||(e.attachments??[]).some(s=>!s||typeof s.filename!="string"||!s.filename||!Number.isFinite(s.size)||s.size<0))throw new ee("INVALID_INPUT","Thread branch input is incomplete");let n=cy(e),r=this.openHandle(true),o;try{o=r.db.transaction(s=>{let i=s.select({id:z.id,child_thread_id:z.child_thread_id,first_task_id:z.first_task_id,branch_point_task_id:z.branch_point_task_id,branch_answer_no:z.branch_answer_no,carried_turns:z.carried_turns,carried_chars:z.carried_chars,carried_truncated:z.carried_truncated,payload_hash:z.payload_hash}).from(z).where(and(eq(z.workspace_id,e.workspaceId),eq(z.actor_id,e.actorId),eq(z.request_id,e.requestId))).limit(1).get();if(i){if(i.payload_hash!==n)throw new ee("BRANCH_REQUEST_CONFLICT","Request id was already used for a different branch payload");return {branchId:i.id,childThreadId:i.child_thread_id,firstTaskId:i.first_task_id,taskId:i.first_task_id,branchPointTaskId:i.branch_point_task_id,branchAnswerNo:i.branch_answer_no,carriedTurns:i.carried_turns,carriedChars:i.carried_chars,carriedTruncated:i.carried_truncated===1,created:!1}}let c=s.select({id:y.id,workspace_id:y.workspace_id,platform:y.platform,title:y.title}).from(y).where(and(eq(y.id,e.parentThreadId),eq(y.workspace_id,e.workspaceId))).limit(1).get();if(!c)throw new ee("PARENT_NOT_FOUND","Parent thread was not found in this workspace");let u=s.all(sql`
|
|
678
|
+
SELECT child.id, child.agent_id, child.prompt, child.result, child.status,
|
|
679
|
+
child.error, child.started_at, child.completed_at, child.metadata, child.workspace_id
|
|
680
|
+
FROM tasks AS child
|
|
681
|
+
WHERE child.thread_id = ${e.parentThreadId}
|
|
682
|
+
AND (child.workspace_id = ${e.workspaceId} OR child.workspace_id IS NULL)
|
|
683
|
+
AND NOT EXISTS (
|
|
684
|
+
SELECT 1 FROM tasks AS parent_task
|
|
685
|
+
WHERE parent_task.id = child.parent_task_id
|
|
686
|
+
AND parent_task.thread_id = child.thread_id
|
|
687
|
+
)
|
|
688
|
+
ORDER BY child.started_at ASC, child.id ASC
|
|
689
|
+
`).filter(N=>De(N)==="success"),l=u.at(-1);if(!l)throw new ee("PARENT_NO_COMPLETED_TURN","Parent thread has no completed turn");let p=iy(u),_=dy(u),h=Mt("brn"),m=Mt("thd"),k=Mt("tsk"),w=new Date().toISOString(),x=Ut(c.title??"Untitled conversation"),T=JSON.stringify(p),L=JSON.stringify({branchId:h,...e.provider?{provider:e.provider}:{},...e.effort?{effort:e.effort}:{}});return s.insert(y).values({id:m,workspace_id:e.workspaceId,created_by_kind:"human",created_by_id:e.actorId,created_by_task_id:k,platform:c.platform,title:null,first_message:e.prompt,last_message:e.prompt,message_count:1,created_at:w,updated_at:w,metadata:null}).run(),s.insert(a).values({id:k,agent_id:l.agent_id,user_id:e.actorId,actor_kind:"human",actor_id:e.actorId,prompt:e.prompt,mode:"execute",status:"pending",result:null,error:null,started_at:w,completed_at:null,metadata:L,workspace_id:e.workspaceId,thread_id:m,model:e.model??null,platform:c.platform}).run(),s.insert(z).values({id:h,workspace_id:e.workspaceId,parent_thread_id:e.parentThreadId,child_thread_id:m,branch_point_task_id:l.id,branch_answer_no:u.length,first_task_id:k,parent_title:x,actor_id:e.actorId,request_id:e.requestId,payload_hash:n,snapshot_version:ir,carry_json:T,carried_turns:p.turnsCount,carried_chars:p.chars,carried_truncated:p.truncated?1:0,status:"active",created_at:w,undone_at:null}).run(),s.insert(kt).values({branch_id:h,source_json:_.sourceJson,bytes:_.bytes}).run(),{branchId:h,childThreadId:m,firstTaskId:k,taskId:k,branchPointTaskId:l.id,branchAnswerNo:u.length,carriedTurns:p.turnsCount,carriedChars:p.chars,carriedTruncated:p.truncated,created:!0}},{behavior:"immediate"});}catch(s){throw s instanceof ee?s:new ee("DATABASE_ERROR","Failed to create thread branch",s)}finally{r.close();}return o.created&&e.afterCommit&&await e.afterCommit(o),o}getByChild(e){if(!existsSync(this.resolveDbPath()))return;let n=this.openHandle(false);try{let r=ap(n.db,eq(z.child_thread_id,e));return r?xa(r):void 0}catch(r){throw r instanceof ee?r:new ee("DATABASE_ERROR","Failed to read thread branch summary",r)}finally{n.close();}}listByParent(e){if(!existsSync(this.resolveDbPath()))return [];let n=this.openHandle(false);try{return n.db.all(sql`
|
|
690
|
+
SELECT branch.id, branch.workspace_id, branch.parent_thread_id, branch.child_thread_id,
|
|
691
|
+
child.title AS child_title, branch.branch_point_task_id, branch.branch_answer_no,
|
|
692
|
+
branch.first_task_id, branch.parent_title, branch.actor_id, branch.request_id,
|
|
693
|
+
branch.carried_turns, branch.carried_chars, branch.carried_truncated,
|
|
694
|
+
branch.status, branch.created_at, branch.undone_at
|
|
695
|
+
FROM thread_branches AS branch
|
|
696
|
+
LEFT JOIN threads AS child ON child.id = branch.child_thread_id
|
|
697
|
+
WHERE branch.parent_thread_id = ${e}
|
|
698
|
+
ORDER BY branch.created_at ASC, branch.id ASC
|
|
699
|
+
`).map(xa)}catch(r){throw r instanceof ee?r:new ee("DATABASE_ERROR","Failed to list parent thread branches",r)}finally{n.close();}}getCarry(e){if(!existsSync(this.resolveDbPath()))return;let n=this.openHandle(false);try{let r=n.db.select({status:z.status,carry_json:z.carry_json,carried_turns:z.carried_turns,carried_chars:z.carried_chars,snapshot_version:z.snapshot_version}).from(z).where(eq(z.id,e)).limit(1).get();if(!r||r.status==="undone")return;if(r.status!=="active"||r.snapshot_version!==ir)throw new ee("CORRUPT_BRANCH","Stored branch snapshot version or status is invalid");return sp(r.carry_json,r.carried_turns,r.carried_chars)}catch(r){throw r instanceof ee?r:new ee("DATABASE_ERROR","Failed to read branch carry snapshot",r)}finally{n.close();}}getSource(e){if(!existsSync(this.resolveDbPath()))return;let n=this.openHandle(false);try{let r=n.db.select({status:z.status,source_json:kt.source_json,bytes:kt.bytes}).from(z).leftJoin(kt,eq(kt.branch_id,z.id)).where(eq(z.id,e)).limit(1).get();if(!r||r.status==="undone")return;if(r.status!=="active"||typeof r.source_json!="string"||r.bytes===null)throw new ee("CORRUPT_BRANCH","Stored branch history source is missing");return ip(r.source_json,r.bytes)}catch(r){throw r instanceof ee?r:new ee("DATABASE_ERROR","Failed to read branch history source",r)}finally{n.close();}}getActiveContextByChild(e){if(!existsSync(this.resolveDbPath()))return;let n=this.openHandle(false);try{let r=ap(n.db,eq(z.child_thread_id,e));if(!r||r.status==="undone")return;if(r.status!=="active")throw new ee("CORRUPT_BRANCH","Stored branch is not readable");let o=n.db.select({snapshot_version:z.snapshot_version,carry_json:z.carry_json,carried_turns:z.carried_turns,carried_chars:z.carried_chars}).from(z).where(eq(z.id,r.id)).limit(1).get();if(!o||o.snapshot_version!==ir)throw new ee("CORRUPT_BRANCH","Stored branch snapshot version is invalid");let s=n.db.select({source_json:kt.source_json,bytes:kt.bytes}).from(kt).where(eq(kt.branch_id,r.id)).limit(1).get();if(!s)throw new ee("CORRUPT_BRANCH","Stored branch history source is missing");return {branch:xa(r),carry:sp(o.carry_json,o.carried_turns,o.carried_chars),source:ip(s.source_json,s.bytes)}}catch(r){throw r instanceof ee?r:new ee("DATABASE_ERROR","Failed to read active branch context",r)}finally{n.close();}}markUndone(e){if(!existsSync(this.resolveDbPath()))return false;let n=this.openHandle(true);try{return n.db.update(z).set({status:"undone",undone_at:new Date().toISOString()}).where(and(eq(z.id,e),eq(z.status,"active"))).run().changes>0}catch(r){throw new ee("DATABASE_ERROR","Failed to mark thread branch undone",r)}finally{n.close();}}};g();vt();Bt();Ft();Ot();jt();Ds();var ie=class extends f{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},lp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ky(){let t=randomBytes(16),e="";for(let n of t)e+=lp[n%lp.length];return e.slice(0,12)}function pp(){return `c_${ky()}`}function yy(t){return typeof t=="string"&&Cs.includes(t)}function Ty(t){return typeof t=="string"&&xs.includes(t)}function dr(t){if(!yy(t))throw new ie("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function _p(t){if(!Ty(t))throw new ie("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function fp(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new ie("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function cr(t){if(typeof t!="string"||t.trim().length===0)throw new ie("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function ls(t){if(typeof t!="string"||t.trim().length===0)throw new ie("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function rn(t,e){return and(eq(M.code_group,t),or(isNull(M.workspace_id),eq(M.workspace_id,e)))}var ps=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!existsSync(n))throw new f("NOT_FOUND","Database not found");e&&mkdirSync(dirname(n),{recursive:true});let r=U(n);if(e)try{Le(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(dr(e),cr(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(M).where(and(rn(e,n),eq(M.is_archived,0))).orderBy(asc(M.sort_order),asc(M.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(dr(e),cr(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(M).where(rn(e,n)).orderBy(asc(M.sort_order),asc(M.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(dr(n),cr(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new ie("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)ls(o);if(new Set(e.codes).size!==e.codes.length)throw new ie("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new ie("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(M).where(rn(n,e.workspaceId)).all(),i=s.filter(h=>h.is_archived===0),c=new Set(s.map(h=>h.code)),d=new Set(i.map(h=>h.code)),u=e.codes.find(h=>!c.has(h));if(u)throw new ie("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${u}`);if(e.codes.length!==i.length||e.codes.some(h=>!d.has(h)))throw new ie("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let l=new Map(i.map(h=>[h.code,h])),p=e.codes.map(h=>{let m=l.get(h);if(!m)throw new ie("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${h}`);return m}),_;for(let[h,m]of p.entries())m.sort_order!==h&&(_??=new Date().toISOString(),o.update(M).set({sort_order:h,updated_at:_}).where(and(eq(M.code_group,n),eq(M.code,m.code))).run());return o.select().from(M).where(rn(n,e.workspaceId)).orderBy(asc(M.sort_order),asc(M.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(dr(e),ls(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(M).where(and(eq(M.code_group,e),eq(M.code,n))).limit(1).get()??null}catch(o){throw new f("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){cr(e.workspaceId);let n=fp(e.name);_p(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:M.code}).from(M).where(and(rn("THREAD_STATE",e.workspaceId),eq(M.is_archived,0),eq(M.code_name,n))).limit(1).get())throw new ie("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:sql`max(${M.sort_order})`}).from(M).where(rn("THREAD_STATE",e.workspaceId)).get(),c=new Date().toISOString(),d=pp();for(;o.select({code:M.code}).from(M).where(and(eq(M.code_group,"THREAD_STATE"),eq(M.code,d))).limit(1).get();)d=pp();o.insert(M).values({code_group:"THREAD_STATE",code:d,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:c,updated_at:c}).run();let u=o.select().from(M).where(and(eq(M.code_group,"THREAD_STATE"),eq(M.code,d))).limit(1).get();if(!u)throw new f("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(dr(e.group),ls(e.code),cr(e.workspaceId),e.name===void 0&&e.color===void 0)throw new ie("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:fp(e.name);e.color!==void 0&&_p(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(M).where(and(eq(M.code_group,e.group),eq(M.code,e.code))).limit(1).get();if(!s)throw new ie("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),n===null&&s.is_builtin!==1)throw new ie("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let d=and(rn(e.group,e.workspaceId),eq(M.is_archived,0));if(o.select({code:M.code}).from(M).where(and(d,eq(M.code_name,n),sql`${M.code} <> ${e.code}`)).limit(1).get())throw new ie("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=n??null),e.color!==void 0&&(i.color=e.color),o.update(M).set(i).where(and(eq(M.code_group,e.group),eq(M.code,e.code))).run();let c=o.select().from(M).where(and(eq(M.code_group,e.group),eq(M.code,e.code))).limit(1).get();if(!c)throw new f("DB_ERROR","Updated common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(dr(e),ls(n),cr(r),typeof o!="boolean")throw new ie("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let c=i.select().from(M).where(and(eq(M.code_group,e),eq(M.code,n))).limit(1).get();if(!c)throw new ie("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(c.is_builtin===1)throw new ie("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(c,r),!o&&c.code_name!==null&&i.select({code:M.code}).from(M).where(and(rn(e,r),eq(M.is_archived,0),eq(M.code_name,c.code_name),ne(M.code,n))).limit(1).get())throw new ie("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${c.code_name}`);i.update(M).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(and(eq(M.code_group,e),eq(M.code,n))).run();let d=i.select().from(M).where(and(eq(M.code_group,e),eq(M.code,n))).limit(1).get();if(!d)throw new f("DB_ERROR","Archived common code could not be read back");return d},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new ie("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};Hn();Jn();g();var ft={threadContext:"crewx_thread_context",apps:"apps",appsGuidance:"apps_guidance",availableApps:"available_apps",crewxUiState:"crewx_ui_state"};function Ry(t){return t.replace(new RegExp(`<${ft.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${ft.threadContext}>`,"g"),"").replace(new RegExp(`<${ft.apps}\\b[^>]*>[\\s\\S]*?<\\/${ft.apps}>`,"g"),"").replace(new RegExp(`<${ft.appsGuidance}\\b[^>]*>[\\s\\S]*?<\\/${ft.appsGuidance}>`,"g"),"").replace(new RegExp(`<${ft.availableApps}\\b[^>]*>[\\s\\S]*?<\\/${ft.availableApps}>`,"g"),"").replace(new RegExp(`<${ft.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${ft.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
700
|
+
`).filter(o=>!(o.startsWith("Loaded ")&&o.includes("layouts from")||o.includes("[dotenv@")||o.includes("[Nest]")&&o.includes("DEBUG")||o.startsWith("Registered custom layout:")||o.startsWith("Updated custom layout:"))).join(`
|
|
701
|
+
`).trim()}function Sy(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.provider;return typeof n=="string"?n:void 0}catch{return}}function Iy(t,e,n){if(!t||e&&Rt(t,n))return "";let r=t;try{let o=JSON.parse(r);Array.isArray(o)?r=o.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
|
|
702
|
+
`):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=Ry(r);}return r}var Ay=new Set(["success","failed","stopped","running"]),Ny=new Set(["failed","stopped"]),Oy={user_stop:"stopped by the user before it finished",runner_lost:"end of run not observed \u2014 it may have done part of the work or may still be running",launch_failed:"the runner never started this run"},_s=200;function gp(t){if(t.length<=_s)return t;let e=t.charCodeAt(_s-1),n=e>=55296&&e<=56319?_s-1:_s;return t.slice(0,n)}function vy(t){let e=dt(t),n=typeof t.error=="string"?t.error.split(`
|
|
703
|
+
`)[0]??"":"";if(e){let r=Oy[e];return gp(n?`${r}; ${n}`:r)}return n?gp(n):void 0}var fs=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new os({dbPath:this.dbPath})}getThreadHistoryRepo(){return new ds({dbPath:this.dbPath})}getThreadBranchRepo(){return new us({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r,o){let s=this.getThreadRepo(),i=s.findThreadById(e);if(i){if(i.platform!==n)throw new Error(`Thread '${e}' already exists with platform '${i.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return s.ensureThread(e,n,r,o),{created:false}}return s.ensureThread(e,n,r,o),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,o=this.getThreadRepo(),s=o.findThreadById(e),i=o.findTopLevelTasks(e,void 0,r,n?.agentId||void 0),c=new Set(["queued","cancelled"]),d=n?.currentTraceId;i=i.filter(h=>(!h.status||!c.has(h.status))&&(!d||h.trace_id!==d&&h.id!==d));let u=o.findInterceptedRequests(i.map(h=>h.id));u.size>0&&(i=i.map(h=>u.has(h.id)?{...h,prompt:u.get(h.id)}:h));let l=s?.platform??"cli",p=this.rowsToMessages(i),_=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,s?.workspace_id??null);return {threadId:e,platform:l,messages:p,..._?{highlights:_}:{},metadata:{title:s?.title??void 0,firstMessage:s?.first_message??void 0,lastMessage:s?.last_message??void 0,messageCount:s?.message_count??0,updatedAt:s?.updated_at?new Date(s.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new ps({dbPath:this.dbPath}),o=(s,i)=>{try{return r.resolve(s,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:o("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:o("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchBranchContext(e){return this.getThreadBranchRepo().getActiveContextByChild(e)}async fetchBranchMarkers(e){return this.getThreadBranchRepo().listByParent(e).filter(n=>n.status==="active").map(n=>({branchPointTaskId:n.branchPointTaskId,childTitle:n.childTitle?.trim()||"Untitled conversation"}))}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,o){let{firstMessage:s}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:s}}async saveAssistantMessage(e,n,r,o){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(o=>typeof o.text=="string"&&o.text.length>0).map(o=>({id:o.id,text:o.text,kind:o.kind,source:o.source,coversFromTaskId:o.covers_from_task_id,coversToTaskId:o.covers_to_task_id,createdAt:o.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let o={status:r.status??"",error:r.error,metadata:r.metadata},s=r.status?De(o):void 0,i=Sy(r.metadata),c=Iy(r.result,s!==void 0&&Ny.has(s),i);if(c||s!==void 0&&Ay.has(s)){let d={agent_id:r.agent_id,task_id:r.id};if(s&&s!=="success"){d.status=s;let u=vy(o);u&&(d.reason=u);}n.push({id:`${r.id}-assistant`,text:c,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:d});}}return n}};var Ma=class extends qt{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new fs(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,n,r,o){}async afterAssistantMessage(e,n,r){}attach(e){this.unsubStart=e.on("task:start",async n=>{if(!n.threadId)return;let r=n.platform??"cli";try{let o=await this._provider.ensureThread(n.threadId,r,n.workspaceId,{createdByTaskId:n.traceId}),s=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,s.id,o.created||s.firstMessage,n);}catch{}}),this.unsubEnd=e.on("task:end",async n=>{if(!n.result)return;let r=n.metadata?.threadId;if(!r)return;let o=n.agentRef?.replace(/^@/,"")??"";try{let{id:s}=await this._provider.saveAssistantMessage(r,n.result,o);await this.afterAssistantMessage(r,s,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{Ma as ConversationPlugin,hs as FileLoggerPlugin,ka as SqliteTracingPlugin};
|