@crewx/sdk 0.9.0-rc.16 → 0.9.0-rc.160
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/app/app.d.ts +148 -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 +7 -0
- package/dist/app/frame.d.ts +55 -0
- package/dist/app/index.d.ts +10 -0
- package/dist/app/index.js +10 -0
- package/dist/app/protocol.d.ts +9 -0
- package/dist/app/runtime.d.ts +21 -0
- package/dist/app/tool-mode.d.ts +3 -0
- package/dist/boxing/box.types.d.ts +4 -0
- package/dist/config/canonicalize-agent-options.d.ts +18 -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 +37 -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-budget/continuity.d.ts +63 -0
- package/dist/context-budget/index.d.ts +142 -0
- package/dist/conversation/index.d.ts +1 -1
- package/dist/conversation/sqlite-provider.d.ts +6 -3
- package/dist/conversation/to-template-messages.d.ts +9 -0
- package/dist/conversation/types.d.ts +58 -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 +10 -0
- package/dist/esm/desktop/index.js +3 -0
- package/dist/esm/index.js +1126 -224
- package/dist/esm/node/index.js +2 -0
- package/dist/esm/plugins/index.js +496 -214
- package/dist/esm/process/index.js +1 -0
- package/dist/esm/publish/index.js +2 -0
- package/dist/esm/repository/index.js +608 -211
- package/dist/esm/skills/index.js +2 -0
- package/dist/esm/testing/index.js +1 -1
- package/dist/events/types.d.ts +16 -0
- package/dist/facade/Crewx.d.ts +61 -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/index.browser.d.ts +19 -1
- package/dist/index.browser.js +6 -2
- package/dist/index.d.ts +131 -17
- package/dist/index.js +1128 -226
- 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 +82 -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 +26 -0
- package/dist/mcp-app/app-handoff.d.ts +109 -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 +29 -0
- package/dist/mcp-app/diagnostic-reason.d.ts +3 -0
- package/dist/mcp-app/discovery.d.ts +161 -0
- package/dist/mcp-app/errors.d.ts +7 -0
- package/dist/mcp-app/index.d.ts +37 -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 +132 -0
- package/dist/mcp-app/state-set.d.ts +9 -0
- package/dist/mcp-app/types.d.ts +488 -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 +72 -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/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/_journal.json +210 -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 +496 -214
- 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 +41 -0
- package/dist/prompt/tag-names.d.ts +22 -0
- package/dist/provider/acp/connection.d.ts +6 -0
- package/dist/provider/acp/meta.d.ts +11 -0
- package/dist/provider/bridge.d.ts +7 -1
- package/dist/provider/classify-task-error.d.ts +2 -0
- package/dist/provider/cli/adapter.types.d.ts +14 -2
- package/dist/provider/cli/adapters/agent-call.util.d.ts +1 -1
- 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/index.d.ts +3 -2
- package/dist/provider/cli/meta.d.ts +5 -0
- package/dist/provider/cli/protocol-envelope.d.ts +3 -0
- package/dist/provider/errors.d.ts +5 -1
- package/dist/provider/idle-watchdog.d.ts +19 -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/task-error.types.d.ts +17 -0
- package/dist/publish/constants.d.ts +6 -0
- package/dist/publish/errors.d.ts +7 -0
- package/dist/publish/index.d.ts +50 -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 +12 -1
- package/dist/repository/index.d.ts +49 -6
- package/dist/repository/index.js +608 -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/request-log-mover.d.ts +70 -0
- package/dist/repository/request-log.repository.d.ts +7 -3
- 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 +44 -0
- package/dist/repository/task-status.d.ts +21 -0
- package/dist/repository/task.repository.d.ts +300 -7
- 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 +118 -7
- package/dist/repository/usage-backfill.d.ts +62 -0
- package/dist/repository/usage-from-logs.d.ts +21 -0
- package/dist/repository/workspace.repository.d.ts +3 -0
- package/dist/schema/agent-send-history.d.ts +85 -0
- package/dist/schema/agent-suggestions.d.ts +199 -0
- package/dist/schema/common-codes.d.ts +216 -0
- package/dist/schema/index.d.ts +15 -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/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 +1058 -1
- package/dist/schema/thread-creator-unverified.d.ts +45 -0
- package/dist/schema/thread-history.d.ts +734 -0
- package/dist/schema/threads.d.ts +59 -0
- package/dist/schema/ui-action-receipts.d.ts +358 -0
- package/dist/schema/ui-definition-archive.d.ts +63 -0
- package/dist/schema/ui-instance-repins.d.ts +222 -0
- package/dist/schema/ui-instances.d.ts +324 -0
- package/dist/schema/workspaces.d.ts +17 -0
- package/dist/skills/index.d.ts +15 -0
- package/dist/skills/index.js +2 -0
- package/dist/skills/types.d.ts +18 -0
- package/dist/task-log/anchor-child-tasks.d.ts +7 -0
- package/dist/task-log/delegation-trailer.d.ts +34 -0
- package/dist/template/engine.d.ts +2 -2
- package/dist/template/helpers/exec.browser.d.ts +4 -3
- package/dist/template/helpers/exec.d.ts +4 -3
- package/dist/template/helpers/format-conversation.d.ts +1 -0
- package/dist/template/types.d.ts +20 -0
- package/dist/testing/index.js +1 -1
- package/dist/types/index.d.ts +1578 -3
- package/dist/types/task-log.types.d.ts +3 -0
- 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 +213 -0
- package/dist/ui-instance/types.d.ts +329 -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 +6 -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 +203 -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 +57 -3
- package/templates/agents/default.yaml +303 -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
package/dist/repository/index.js
CHANGED
|
@@ -1,14 +1,141 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
|
|
3
|
-
`)}`);let o=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),we(a,i),o?.cnt&&(Ee(a,r,e),be(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function D(a,t){Mt.has(t)||(nt(a),Mt.add(t));}var h=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var s=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>h.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at)}));var K=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>K.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var F=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>s.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var I=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var rt=sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));var A=sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var v=sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},a=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));function xt(a){let t=j__namespace.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Yt(a){let t=xt(a);return crypto.createHash("sha256").update(t).digest("hex")}function mt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var At=class extends S{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?j.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{nt(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=mt(j.basename(n)),i=`${mt(j.basename(j.dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:h.id}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.slug,c),drizzleOrm.ne(h.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let _=`${i}-${c}`;if(!u(_))return _}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let r of e)if(r.slug.includes("/")){let o=mt(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:o,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:o,workspacePath:i}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:o,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:i,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(h.id,n),drizzleOrm.isNull(h.workspace_path))).run();}registerWorkspace(t){let e=xt(t),n=this.openHandle(true);try{let r=Yt(e),o=j.basename(e),i=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:i,name:o,workspacePath:e}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?drizzleOrm.eq(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:drizzleOrm.sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(drizzleOrm.desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(drizzleOrm.sql`SELECT t.*,
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
1
|
+
'use strict';var Sd=require('fs'),Ae=require('path'),aa=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Sd__namespace=/*#__PURE__*/_interopNamespace(Sd);var Ae__namespace=/*#__PURE__*/_interopNamespace(Ae);var aa__default=/*#__PURE__*/_interopDefault(aa);var Bl=Object.defineProperty;var St=(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 x=(t,e)=>()=>(t&&(e=t(t=0)),e);var ql=(t,e)=>{for(var n in e)Bl(t,n,{get:e[n],enumerable:true});};var h=x(()=>{});function sa(t){if(t===":memory:")return t;let e=Ae.resolve(t),n=e,r=[];for(;!Sd.existsSync(n);){let s=Ae.dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=Sd.realpathSync(n);for(let s of r)o=Ae.join(o,s);return Ae.resolve(o)}function zl(t,e){let n=sa(t),r=sa(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function He(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&Gl.some(e=>zl(t,Ae.join(aa__default.default.homedir(),".crewx",e))))throw new Error(`${Wl}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var Wl,Gl;exports.BaseSqliteRepository=void 0;var re=x(()=>{h();Wl="[crewx] Refusing to open the real CrewX database from a test process";Gl=["crewx.db","logs.db"];exports.BaseSqliteRepository=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||Ae.join(aa__default.default.homedir(),".crewx","crewx.db");return He(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return Sd.existsSync(e??this.resolveDbPath())}};});exports.RepositoryError=void 0;var ie=x(()=>{h();exports.RepositoryError=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 N(t,e={}){let n=He(t),r=St("better-sqlite3"),{drizzle:o}=St("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 = ${exports.CREWX_JOURNAL_SIZE_LIMIT_BYTES}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),runRaw:(i,d=[])=>s.prepare(i).run(...d),close:()=>s.close()}}function Zo(t,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let n=He(t),r=St("better-sqlite3"),o=da(n),s;try{s=new r(n),s.pragma("busy_timeout = 1000");let i=s.pragma(`wal_checkpoint(${e})`),d=da(n);return {busy:i[0]?.busy===1,walBytesBefore:o,walBytesAfter:d}}finally{s?.close();}}var da;exports.CREWX_JOURNAL_SIZE_LIMIT_BYTES=void 0;var ue=x(()=>{h();re();da=t=>{try{return Sd__namespace.statSync(`${t}-wal`).size}catch{return 0}},exports.CREWX_JOURNAL_SIZE_LIMIT_BYTES=32*1024*1024;});function dn(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Vl(t,e){if(e>0||!dn(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(Kl))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function Xl(t,e,n){if(!dn(t,"__drizzle_migrations")||!dn(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(Sd.readFileSync(Ae__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=Jl[i.tag];if(!d)continue;let c=Ae__namespace.default.join(e,`${i.tag}.sql`);if(!Sd.existsSync(c))continue;let u=Sd.readFileSync(c,"utf-8"),f=crypto.createHash("sha256").update(u).digest("hex");if(o.has(f))continue;let l=t.all("PRAGMA table_info(tasks)"),g=new Set(l.map(_=>_.name));for(let[_,m]of Object.entries(d))g.has(_)||(t.run(`ALTER TABLE tasks ADD COLUMN ${_} ${m}`),g.add(_));}}function pa(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 fa(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function Yl(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(s=>s.name===n)}function Ql(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function Ur(t,e){return e.kind==="add-column"?Yl(t,e.table,e.column):Ql(t,e.name)}function ga(t,e,n){let r=t;for(let o of fa(e)){let s=pa(o);s?.kind==="add-column"&&Ur(r,s)||s?.kind==="create-index"&&Ur(r,s)||s?.kind==="drop-index"&&!Ur(r,s)||r.run(n.raw(o));}}function Zl(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(Sd.readFileSync(Ae__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=Ae__namespace.default.join(e,`${i.tag}.sql`);if(!Sd.existsSync(d))continue;let c=Sd.readFileSync(d,"utf-8"),u=crypto.createHash("sha256").update(c).digest("hex");if(o.has(u))continue;let l=fa(c).map(pa);if(l.some(_=>!_))continue;let g=l;g.some(_=>_.kind==="add-column")&&g.some(_=>Ur(t,_))&&(t.transaction(_=>{ga(_,c,n),_.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 ep(t,e){let{sql:n}=St("drizzle-orm"),r=JSON.parse(Sd.readFileSync(Ae__namespace.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 d=r.entries.find(u=>u.tag===i);if(!d)throw new Error(`Missing release/App compatibility migration: ${i}`);let c=Sd.readFileSync(Ae__namespace.default.join(e,`${i}.sql`),"utf-8");return {entry:d,content:c,hash:crypto.createHash("sha256").update(c).digest("hex")}});t.transaction(i=>{let d=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(c=>c.hash));if(d.has(s[0].hash))for(let c of s.slice(1))d.has(c.hash)||(ga(i,c.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c.hash}, ${c.entry.when})`),d.add(c.hash),console.error(`[crewx] Replayed release/App migration ${c.entry.tag} safely.`));},{behavior:"immediate"});}function op(t,e,n,r){let s=JSON.parse(Sd.readFileSync(Ae__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:l})=>l===tp);if(!s)return;let i=Ae__namespace.default.join(e,`${s.tag}.sql`);if(!Sd.existsSync(i))return;let d=crypto.createHash("sha256").update(Sd.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.hash===d))return;if(!dn(t,"tasks"))return {hash:d,affectedRows:0};let c=t.all("PRAGMA table_info(tasks)"),u=new Set(c.map(l=>l.name));if(!u.has("stop_requested_at")||!u.has("stop_requested_epoch"))return {hash:d,affectedRows:0};let f=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:d,affectedRows:f?.count??0}}function sp(t,e,n,r){let s=JSON.parse(Sd.readFileSync(Ae__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:l})=>l===np);if(!s)return;let i=Ae__namespace.default.join(e,`${s.tag}.sql`);if(!Sd.existsSync(i))return;let d=crypto.createHash("sha256").update(Sd.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.hash===d))return;if(!dn(t,"threads"))return {hash:d,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(l=>l.name==="created_by_task_id"))return {hash:d,markedPointers:0};let u=dn(t,la)?`AND NOT EXISTS (
|
|
7
|
+
SELECT 1
|
|
8
|
+
FROM ${la} AS marked
|
|
9
|
+
WHERE marked.thread_id = current.id
|
|
10
|
+
AND marked.created_by_task_id = current.created_by_task_id
|
|
11
|
+
)`:"",f=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 = '${rp}'
|
|
19
|
+
)
|
|
20
|
+
${u}`);return {hash:d,markedPointers:f?.count??0}}function cn(t){let{migrate:e}=St("drizzle-orm/better-sqlite3/migrator"),{sql:n}=St("drizzle-orm"),r=[Ae__namespace.default.join(__dirname,"../migrations"),Ae__namespace.default.join(__dirname,"migrations"),Ae__namespace.default.join(__dirname,"../../../../drizzle/migrations"),Ae__namespace.default.join(process.cwd(),"drizzle/migrations")],o=r.find(l=>Sd.existsSync(Ae__namespace.default.join(l,"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),Vl(t,i),s?.cnt&&(ep(t,o),Zl(t,o,n),Xl(t,o,n));let d=op(t,o,n,!!s?.cnt),c=sp(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let f=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(f>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${f} migration${f>1?"s":""} applied).`);}d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.hash===d.hash)&&console.error(`[crewx] Task stop-marker cleanup (${d.affectedRows} success/failed row(s) affected).`),c&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.hash===c.hash)&&console.error(`[crewx] Thread creator pointer migration (${c.markedPointers} pointer(s) marked unverified).`);}function V(t,e){ua.has(e)||(cn(t),ua.add(e));}var ua,Kl,Jl,tp,np,rp,la,_e=x(()=>{h();ua=new Set,Kl={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"};Jl={"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"}};tp="0027_task_stop_scope_cleanup",np="0033_thread_creator_boundary_guard",rp="trg_threads_creator_late_fill_guard",la="thread_creator_unverified";});var P,es=x(()=>{h();P=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});exports.tasks=void 0;var wT,up;exports.taskRowColumns=void 0;var un=x(()=>{h();exports.tasks=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),actor_kind:sqliteCore.text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:sqliteCore.text("actor_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),heartbeat_at:sqliteCore.text("heartbeat_at"),stop_requested_at:sqliteCore.text("stop_requested_at"),stop_requested_epoch:sqliteCore.integer("stop_requested_epoch"),rendered_prompt:sqliteCore.text("rendered_prompt"),security_key:sqliteCore.text("security_key"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),cwd:sqliteCore.text("cwd"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0),rating:sqliteCore.text("rating",{enum:["up","down"]}),rated_at:sqliteCore.text("rated_at")},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),rating_check:sqliteCore.check("tasks_rating_ck",drizzleOrm.sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:sqliteCore.index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:sqliteCore.index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:sqliteCore.index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(drizzleOrm.sql`${t.rating} IS NOT NULL`)})),{security_key:wT,...up}=drizzleOrm.getTableColumns(exports.tasks),exports.taskRowColumns=up;});var bt,ka=x(()=>{h();un();bt=sqliteCore.sqliteTable("task_provider_inputs",{task_id:sqliteCore.text("task_id").notNull().references(()=>exports.tasks.id,{onDelete:"cascade"}),run_epoch:sqliteCore.integer("run_epoch").notNull(),input:sqliteCore.text("input").notNull(),key_wrap_skipped:sqliteCore.integer("key_wrap_skipped").notNull().default(0),recorded_at:sqliteCore.text("recorded_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.task_id,t.run_epoch]})}));});var ft,wa=x(()=>{h();un();ft=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>exports.tasks.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:sqliteCore.index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var mp,kp,w,Fr=x(()=>{h();es();mp="json_extract(metadata, '$.threadTitle.state')",kp="json_extract(metadata, '$.threadTitle.priority')",w=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>P.id,{onDelete:"set null"}),created_by_kind:sqliteCore.text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:sqliteCore.text("created_by_id"),created_by_task_id:sqliteCore.text("created_by_task_id"),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:sqliteCore.index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(mp)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(kp))}));});var Ea,Sa=x(()=>{h();Ea=sqliteCore.sqliteTable("thread_creator_unverified",{thread_id:sqliteCore.text("thread_id").notNull(),created_by_task_id:sqliteCore.text("created_by_task_id").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var It,Ia=x(()=>{h();un();It=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>exports.tasks.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>It.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var gt,Aa=x(()=>{h();un();gt=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>exports.tasks.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));});var Je,va=x(()=>{h();Fr();Je=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>w.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));});var xa,Ca=x(()=>{h();xa=sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));});var Da=x(()=>{h();sqliteCore.sqliteTable("request_log_daily",{day:sqliteCore.text("day").notNull(),scope:sqliteCore.text("scope").notNull(),ok:sqliteCore.integer("ok").notNull(),client:sqliteCore.integer("client").notNull(),server:sqliteCore.integer("server").notNull(),p50_ms:sqliteCore.integer("p50_ms"),p95_ms:sqliteCore.integer("p95_ms"),computed_at:sqliteCore.text("computed_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.day,t.scope]})}));});var Te,Ma=x(()=>{h();Te=sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var $e,Ha=x(()=>{h();$e=sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var q,pe,Ua=x(()=>{h();q=sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),pe=sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var W,qa=x(()=>{h();W=sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var Fa=x(()=>{h();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),app_id:sqliteCore.text("app_id"),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),opened_by_json:sqliteCore.text("opened_by_json"),agent_open_request_json:sqliteCore.text("agent_open_request_json"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("ui_instances_app_id_ck",drizzleOrm.sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:sqliteCore.check("ui_instances_opened_by_json_ck",drizzleOrm.sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:sqliteCore.uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(drizzleOrm.sql`${t.status} = 'active'`)}));});var Wa=x(()=>{h();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),definition_id:sqliteCore.text("definition_id"),definition_version:sqliteCore.integer("definition_version"),definition_hash:sqliteCore.text("definition_hash"),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
|
|
23
|
+
(${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
|
|
24
|
+
OR
|
|
25
|
+
(${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
|
|
26
|
+
)`),instanceRequestUnique:sqliteCore.uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:sqliteCore.index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:sqliteCore.index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var za=x(()=>{h();sqliteCore.sqliteTable("ui_instance_repins",{instance_id:sqliteCore.text("instance_id").notNull(),from_version:sqliteCore.integer("from_version").notNull(),from_hash:sqliteCore.text("from_hash").notNull(),to_version:sqliteCore.integer("to_version").notNull(),to_hash:sqliteCore.text("to_hash").notNull(),from_revision:sqliteCore.integer("from_revision").notNull(),to_revision:sqliteCore.integer("to_revision"),status:sqliteCore.text("status").notNull(),code:sqliteCore.text("code"),attempts:sqliteCore.integer("attempts").notNull().default(1),first_at:sqliteCore.integer("first_at").notNull(),last_at:sqliteCore.integer("last_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.instance_id,t.to_hash],name:"ui_instance_repins_pk"}),instanceIdCheck:sqliteCore.check("ui_instance_repins_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 5 AND 128 AND ${t.instance_id} GLOB 'uic_*'`),fromVersionCheck:sqliteCore.check("ui_instance_repins_from_version_ck",drizzleOrm.sql`${t.from_version} >= 1`),toVersionCheck:sqliteCore.check("ui_instance_repins_to_version_ck",drizzleOrm.sql`${t.to_version} >= 1`),fromHashCheck:sqliteCore.check("ui_instance_repins_from_hash_ck",drizzleOrm.sql`length(${t.from_hash}) = 64 AND ${t.from_hash} NOT GLOB '*[^0-9a-f]*'`),toHashCheck:sqliteCore.check("ui_instance_repins_to_hash_ck",drizzleOrm.sql`length(${t.to_hash}) = 64 AND ${t.to_hash} NOT GLOB '*[^0-9a-f]*'`),fromRevisionCheck:sqliteCore.check("ui_instance_repins_from_revision_ck",drizzleOrm.sql`${t.from_revision} >= 0`),toRevisionCheck:sqliteCore.check("ui_instance_repins_to_revision_ck",drizzleOrm.sql`${t.to_revision} IS NULL OR ${t.to_revision} >= 0`),statusCheck:sqliteCore.check("ui_instance_repins_status_ck",drizzleOrm.sql`${t.status} IN ('applied', 'deferred', 'failed')`),attemptsCheck:sqliteCore.check("ui_instance_repins_attempts_ck",drizzleOrm.sql`${t.attempts} >= 1`),datesCheck:sqliteCore.check("ui_instance_repins_dates_ck",drizzleOrm.sql`${t.first_at} >= 0 AND ${t.last_at} >= ${t.first_at}`),resultCheck:sqliteCore.check("ui_instance_repins_result_ck",drizzleOrm.sql`(
|
|
27
|
+
(${t.status} = 'applied' AND ${t.code} IS NULL
|
|
28
|
+
AND ${t.to_revision} = ${t.from_revision} + 1)
|
|
29
|
+
OR
|
|
30
|
+
(${t.status} IN ('deferred', 'failed') AND ${t.code} IS NOT NULL
|
|
31
|
+
AND ${t.to_revision} IS NULL)
|
|
32
|
+
)`)}));});var Ka=x(()=>{h();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`)}));});var G,qe,et,Ja=x(()=>{h();G=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},t=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${t.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${t.stage_index} >= 1`)})),qe=sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>G.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),et=sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>G.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},t=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});exports.COMMON_CODE_GROUPS=void 0;exports.COMMON_CODE_COLORS=void 0;var C,ps=x(()=>{h();exports.COMMON_CODE_GROUPS=["THREAD_STATE","THREAD_PRIORITY"],exports.COMMON_CODE_COLORS=["gray","blue","violet","green","amber","orange","red","pink"],C=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.code_group,t.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${t.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var Xa,Ya,Qa,Za,ed,K,F,U,td=x(()=>{h();Fr();Xa=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Ya=["user","agent","system"],Qa=["auto","manual"],Za=["decision","judgment","issue","result","pivot"],ed=["queued","running","completed","failed"],K=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>w.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},t=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.sql`${t.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),F=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>w.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},t=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.sql`(${t.previous_auto_count} IS NULL OR ${t.previous_auto_count} >= 0) AND (${t.new_auto_count} IS NULL OR ${t.new_auto_count} >= 0)`),threadRequestUnique:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(drizzleOrm.sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),U=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>w.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},t=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${t.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.sql`${t.source} = 'manual' OR (${t.source} = 'auto' AND ${t.source_task_id} IS NOT NULL AND ${t.detector_version} IS NOT NULL AND ${t.content_fingerprint} IS NOT NULL AND length(${t.source_task_id}) > 0 AND length(${t.detector_version}) > 0 AND length(${t.content_fingerprint}) > 0)`),threadStatusCreatedIndex:sqliteCore.index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(drizzleOrm.sql`${t.source} = 'auto'`)}));});var rd=x(()=>{h();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});exports.agent_send_history=void 0;var od=x(()=>{h();exports.agent_send_history=sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var fe=x(()=>{h();es();un();ka();wa();Fr();Sa();Ia();Aa();va();Ca();Da();Ma();Ha();Ua();qa();Fa();Wa();za();Ka();Ja();ps();td();rd();od();});var If;exports.AgentSendHistoryRepository=void 0;var ws=x(()=>{h();re();ue();_e();ie();fe();If=50,exports.AgentSendHistoryRepository=class extends exports.BaseSqliteRepository{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=N(e);try{return V(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(exports.agent_send_history).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[exports.agent_send_history.workspace_id,exports.agent_send_history.actor_id,exports.agent_send_history.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${exports.agent_send_history.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:exports.agent_send_history.agent_id,lastAcceptedAt:exports.agent_send_history.last_accepted_at}).from(exports.agent_send_history).where(drizzleOrm.and(drizzleOrm.eq(exports.agent_send_history.workspace_id,e),drizzleOrm.eq(exports.agent_send_history.actor_id,n))).orderBy(drizzleOrm.desc(exports.agent_send_history.last_accepted_at),drizzleOrm.asc(exports.agent_send_history.agent_id)).limit(If).all()}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to find recent agent sends",o)}finally{r?.close();}}};});var mn,Ss,Od,bs=x(()=>{h();mn={"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":{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":{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-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.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"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}},Ss=new Set(["gpt-5.3-codex-spark"]),Od=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-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","glm-5.1","glm-5.2","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-oss-120b","grok-4.5","grok-4.6","grok-4.7"]);});function Is(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 Qf(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),sr;let e=Is(t),n=Yf[e];if(n)return no[n]??mn[n]??sr;if(no[e])return no[e];if(mn[e])return mn[e];if(Ss.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),sr;if(Od.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),sr;let r={...mn,...no};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),sr}function Zf(t,e,n,r=0,o){let s=Qf(n),i=Math.min(r,t),c=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,f=e*s.output/1e6;return c+u+f}function vd(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:Zf(e??0,n??0,o,r??0)}var Yf,sr,no,ro=x(()=>{h();bs();bs();Yf={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"},sr={input:0,cachedInput:0,output:0},no={};});function Dd(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function xd(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Pd(t){return Number.isSafeInteger(t)&&t>0}function og(t,e){return new Promise(n=>{let r;try{r=child_process.spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:Dd(u)});return}let o="",s="",i=false,d,c=setTimeout(()=>{try{r.kill();}catch{}d({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${Nd}ms`)});},Nd);d=u=>{i||(i=true,clearTimeout(c),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=>{d({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{d({status:u,stdout:o,stderr:s});});})}async function Ld(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):og(t,e)}function sg(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function ig(){return new Promise(t=>{setImmediate(t);})}function zt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return xd(n)==="ESRCH"?"not_found":xd(n)==="EPERM"?"alive":"unknown"}}function ag(t,e){let n=zt(-t,e),r=zt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Md(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??ng),i=Date.now()+o,d,c=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(f=>{d=setTimeout(f,o);});u.then(()=>{c=true;});try{for(await ig();;){let f=ag(t,e);if(f==="not_found")return f;let l=i-Date.now();if(c||l<=0)return f;await Promise.race([u,sg(Math.min(s,l))]);}}finally{d!==void 0&&clearTimeout(d);}}async function Cd(t,e,n,r,o){let s=await Md(t,e,o.hardConfirmMs??rg,{...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 Os(t,e,n={}){if(!Pd(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 Ld(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let d=i.stdout.trim();if(!d)return "not_found";let c=r==="win32"?d.toLowerCase():d;return e.filter(f=>f.trim().length>0).some(f=>{let l=r==="win32"?f.toLowerCase():f;return c.includes(l)})?"owned":"not_owned"}async function vs(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=g=>({status:"failed",pid:t,method:r,error:g});if(!Pd(t))return o("Invalid process ID");let s=e.kill??process.kill,i=zt(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 g;try{g=await Ld("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){g={status:null,stdout:"",stderr:"",error:Dd(m)};}let _=zt(t,s);return _==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(_==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let d,c=e.signal??"SIGKILL";try{s(-t,c);}catch(g){d=g;}if(c==="SIGKILL")return Cd(t,s,d,r,e);if(await Md(t,s,e.graceMs??tg,e)==="not_found")return d?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let f;try{s(-t,"SIGKILL");}catch(g){f=g;}let l=await Cd(t,s,f,r,e);return l.status==="terminated"?l:l.status==="not_found"?d?l:{status:"terminated",pid:t,method:r}:o(l.error??"Process termination failed")}var Nd,As,tg,ng,rg,Ns=x(()=>{h();Nd=3e3,As="SIGINT",tg=2e3,ng=25,rg=100;});function qd(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new exports.RepositoryError("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new exports.RepositoryError("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Ud(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new exports.RepositoryError("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new exports.RepositoryError("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>qd(r,o))}catch(r){throw r instanceof exports.RepositoryError?new exports.RepositoryError("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Fd(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new exports.RepositoryError("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new exports.RepositoryError("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new exports.RepositoryError("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Bd(t){return {taskId:t.id,source:Fd(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function fg(t){if(!Number.isInteger(t)||t<0)throw new exports.RepositoryError("VALIDATION","Task log tail limit must be a non-negative integer")}exports.TaskLogRepository=void 0;var oo=x(()=>{h();re();ue();_e();ie();fe();exports.TaskLogRepository=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?He(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:exports.tasks.id,log_storage:exports.tasks.log_storage,last_log_seq:exports.tasks.last_log_seq,log_revision:exports.tasks.log_revision,logs:exports.tasks.logs}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:exports.tasks.id,log_storage:exports.tasks.log_storage,last_log_seq:exports.tasks.last_log_seq,log_revision:exports.tasks.log_revision,logs:exports.tasks.logs}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new exports.RepositoryError("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)=>qd(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new exports.RepositoryError("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let d=this.requireStateRowInTransaction(i,e),c=Fd(d);if(c==="blob"){let g=Ud(e,d.logs);if(i.update(exports.tasks).set({logs:JSON.stringify([...g,...r]),log_revision:drizzleOrm.sql`${exports.tasks.log_revision} + 1`}).where(drizzleOrm.eq(exports.tasks.id,e)).run().changes!==1)throw new exports.RepositoryError("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let u=d.last_log_seq+1,f=d.last_log_seq+r.length;if(i.insert(ft).values(r.map((g,_)=>({task_id:e,seq:u+_,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(exports.tasks).set({last_log_seq:f,log_revision:drizzleOrm.sql`${exports.tasks.log_revision} + 1`}).where(drizzleOrm.eq(exports.tasks.id,e)).run().changes!==1)throw new exports.RepositoryError("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:d.log_revision+1,lastSeq:f}},{behavior:"immediate"})}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("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?Bd(r):void 0}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return fg(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=Bd(s);if(i.source==="blob"){let f=Ud(e,s.logs);return {...i,entries:n===void 0?f:f.slice(Math.max(0,f.length-n))}}let d=o.select({seq:ft.seq,timestamp:ft.timestamp,level:ft.level,message:ft.message}).from(ft).where(drizzleOrm.eq(ft.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(ft.seq):drizzleOrm.desc(ft.seq)),u=(n===void 0?d.all():d.limit(n).all()).map(({timestamp:f,level:l,message:g})=>({timestamp:f,level:l,message:g}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var jd=x(()=>{h();});var ae,Kt=x(()=>{h();ae=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};});var Vt,xs=x(()=>{h();Kt();Vt=class extends ae{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Ds(t){if(!so(t)||t.type!=="item.started"||!zd(t)||!Wd(t))return false;let e=t.item;return !so(e)||!zd(e)||!Wd(e)||!Cs(e.id)?false:e.type==="web_search"?e.query===""&&so(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=>so(n)&&Cs(n.path)&&Cs(n.kind)):false}function so(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Gd(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Cs(t){return typeof t=="string"&&t.trim().length>0}function Wd(t){return !Gd(t,"status")||t.status==="in_progress"}function zd(t){for(let e of ["error","errors","isError","is_error"])if(Gd(t,e))return false;return true}var Ps=x(()=>{h();});function gg(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=r.type;if(typeof o!="string")return false;let s=e?Rg[e]:void 0;return s?s(r,o):Object.values(Vd).some(i=>i(r,o))}function kn(t,e){let n=t.split(`
|
|
33
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>gg(r,e))}function We(t){return typeof t=="object"&&t!==null}function Kd(t,e){if(e==="assistant"||e==="user"){let n=t.message;return We(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||We(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?We(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function _g(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Kd(t,e)}function hg(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||We(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 We(n)&&typeof n.type=="string"}return false}function mg(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||We(t.part):e==="text"||e==="tool_use"?We(t.part):e==="result"?typeof t.result=="string":false}function kg(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||We(t.part)||e==="result"&&typeof t.result=="string")}function Tg(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?We(t.data):e==="result"?typeof t.result=="string":false}function wg(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 yg(t,e){return e==="available_commands"?We(t.tools)||We(t.commands):e==="usage"?We(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||We(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var Vd,Rg,io=x(()=>{h();Ps();Vd={claude:Kd,codex:hg,opencode:mg,copilot:Tg,gemini:wg},Rg={...Vd,claude:_g,opencode:kg,grok:yg,antigravity:()=>false};});function kt(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function Tt(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 Tn=x(()=>{h();});function bg(t){let e=Ig(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>Og(s.value)),r=Ag(e);return {result:n.length===1&&n[0].index===r?vg(n[0].line.value):null,resultPreview:Cg(e,n),hasReservedLine:n.length>0}}function nt(t,e){let n=bg(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function Ig(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
34
|
+
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
35
|
+
`?`\r
|
|
36
|
+
`: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 Ag(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Og(t){return t.trimStart().startsWith(Eg)}function vg(t){let e=t.trim();if(!e.startsWith(Jd)||!e.endsWith("]]"))return null;let n=e.slice(Jd.length,-2);if(!n)return null;try{return Ng(JSON.parse(n))}catch{return null}}function Ng(t){return xg(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function xg(t){if(!Dg(t)||Object.keys(t).some(r=>!Sg.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?Xd(t.taskId)&&Xd(t.agentId):t.isError===true}function Cg(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 Xd(t){return typeof t=="string"&&t.trim().length>0}function Dg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Jd,Eg,Sg,wn=x(()=>{h();Jd="[[crewx:delegation-result ",Eg="[[crewx:delegation-result",Sg=new Set(["schema","taskId","agentId","isError"]);});function rt(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 yn=x(()=>{h();});var Yd,ao,Ls,co=x(()=>{h();Yd=["none","minimal","low","medium","high","xhigh","max","ultra"],ao={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"]},Ls={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-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-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:[],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.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-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-6-thinking",name:"Claude Opus 4.6 Thinking",contextWindowTokens:1e6,tier:"flagship"},{id:"gpt-oss-120b",name:"GPT-OSS 120B",contextWindowTokens:128e3,tier:"balanced"}],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.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-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(Ls).map(([t,e])=>[t,e.models]));});function Ms(t){return Lg[t]??t}function Hg(t){return Mg.get(t)??t}function Hs(t){if(!t)return {};let e=Ug.get(t);return e?{...e}:{model:t}}function $s(t,e){return t==="antigravity"||t==="cli/antigravity"?Hs(e):e===void 0?{}:{model:Hg(e)}}var Pg,Lg,Mg,$g,Ug,ar=x(()=>{h();Pg=[{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]"}],Lg={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Mg=new Map(Pg.map(({baseModelId:t,catalogModelId:e})=>[t,e]));$g=[{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"}],Ug=new Map($g.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function qg(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Pt(t){return uo(t).models}function uo(t){return Bg[t]??Ls[t]??qg()}function dr(t,e){let n=uo(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=$s(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Qd(t){return uo(t).modelOverrides}function Zd(){return Pt("claude")}function ec(){return Pt("codex")}function tc(){return Pt("copilot")}function nc(){return Pt("antigravity")}var Bg,Jt=x(()=>{h();co();ro();ar();Bg={};});function rc(t){return Fg[t]??t}var Fg,oc=x(()=>{h();Jt();ar();Fg={auto:"default"};});function lo(t,e){return (ao[t]??[]).includes(e)}function Lt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return jg.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function sc(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 ic(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 ac(t){return !t||!lo("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function dc(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=rc(t);return e.has(n)?["--permission-mode",n]:[]}function cc(t){return t?lo("claude",t)?["--effort",t]:[]:[]}function uc(t){return t==="default"?[]:t&&Wg.has(t)?["--permission-mode",t]:[]}function lc(t){return t===true?["--always-approve"]:[]}function pc(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 fc(t){return t?lo("grok",t)?["--effort",t]:[]:[]}function gc(t){if(!t)return [];switch(Ms(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function _c(t){return t?lo("antigravity",t)?["--effort",t]:[]:[]}var jg,Wg,cr=x(()=>{h();oc();ar();co();jg=new Set(Yd);Wg=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function zg(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 Gg(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,d="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,c=i!==void 0?i:d??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:c}}function Kg(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),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function hc(t){let e=new Map,n;for(let s of t.split(`
|
|
37
|
+
`))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let d=i.message,c=d?.id,u=d?.usage;if(typeof c!="string"||!u)continue;let f=Number(u.input_tokens??0),l=Number(u.cache_read_input_tokens??0);e.set(c,{inputTokens:f+l,cachedInputTokens:l});let g=d?.model;typeof g=="string"&&g&&(n=g);}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 Rn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
38
|
+
`))if(r.trim())try{let o=JSON.parse(r),s=Kg(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=zg(o)??Gg(o);i&&(e=i);}catch{}return n||(e??void 0)}var ur=x(()=>{h();});function ot(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 Xt=x(()=>{h();});function mc(t){let e=t.split(`
|
|
39
|
+
`).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 Xg(t){let e=t.split(`
|
|
40
|
+
`).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 Yg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function wc(t){let e=Yg(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=Zg(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(e_(n))return `Claude rate limit: ${n}`}}function Qg(t){let e=wc(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 Zg(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
41
|
+
|
|
42
|
+
`):""}function e_(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function Tc(t){return t.replace(/\s+/g," ").trim()}function t_(t,e){let n=t?.description;if(typeof n!="string")return;let r=Tc(n);if(!r||r===Tc(e))return;if(r.length<=kc)return r;let o=r.slice(0,kc-1);return /[\uD800-\uDBFF]$/.test(o)&&(o=o.slice(0,-1)),`${o}\u2026`}function n_(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=rt(s);if(r==="Bash"&&kt(i))return Tt(t,i,o);let d=t_(s,i);return {timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i,...d?{toolTitle:d}:{}}}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(d=>d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
|
|
43
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...nt(i,r)}}return null}var Vg,Jg,po,kc,Us=x(()=>{h();xs();Kt();io();Tn();wn();yn();cr();Jt();ur();Xt();Vg=new Set(["tool_progress"]),Jg="cli/claude";po={command:"claude",meta:{displayName:"Claude",models:Zd(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Lt(e.model),s=e.effort??o,i=dc(e.mode),d=cc(s),c=r?["--model",r]:[],u=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let l=[...e.additionalArgs];return l.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...u,...i,...d,...c,...l],stdinMessage:t}:{args:["--output-format","stream-json","--verbose",...u,...i,...d,...c,...l],stdinMessage:t}}return {args:["-p","--output-format","stream-json","--verbose",...u,...i,...d,...c],stdinMessage:t}},extractText(t){let e=Xg(t);if(e?.is_error===true){let o=po.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 ae(`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,Jg,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=mc(t);if(n)return n;let r=t.trim();return kn(r,"claude")?"":r},extractPartialText(t){return mc(t)},extractFailure(t){try{let e=JSON.parse(t),n=wc(e);if(n)return new Vt(n)}catch{}return null},parseResultMeta(t){let e=t.split(`
|
|
44
|
+
`);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,d=o.modelUsage,c=d?Object.keys(d)[0]??null:null;return {usage:i,model:c}}}catch{}let n=hc(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=ot(n,e??new Date().toISOString()),s=Qg(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];let i=n.output_file,d=n.summary;if(r==="system"&&n.subtype==="task_notification"&&n.status==="completed"&&typeof i=="string"&&i.trim().length>0&&typeof d=="string"&&d.trim().length>0)return [{timestamp:o,type:"text",content:d}];if(r!=="assistant"&&r!=="user")return [];let u=n.message?.content;if(!Array.isArray(u))return [];let f=[];for(let l of u){let g=n_(o,l);g&&f.push(g);}return f},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Vg.has(r):!1}catch{return false}}};kc=200;});function yc(t){let e=t.split(`
|
|
45
|
+
`).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 r_,Bs,qs=x(()=>{h();io();ur();Tn();yn();wn();Jt();co();Xt();r_=new Set(["interactive","plan","autopilot"]);Bs={command:"copilot",meta:{displayName:"Copilot",models:tc()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&r_.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(ao.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=yc(t);if(e)return e;let n=t.trim();return kn(n,"copilot")?"":n},extractPartialText(t){return yc(t)},parseResultMeta(t){let e=Rn(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=ot(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let d=String(o.toolName||""),c=o.arguments,u=rt(c);return (d==="bash"||d==="Bash")&&kt(u)?[Tt(s,u,i)]:[{timestamp:s,type:"tool_use",toolName:d,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let d=o.error;if(d)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...nt(String(d.message||""),true)}];let c=o.result,u=String(c?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...nt(u,false)}]}if(r==="assistant.message"){let d=String(o.content||"");return d?[{timestamp:s,type:"text",content:d}]:[]}return []}};});function i_(t){let e=[],n=0,r=false,o=false,s=0;for(let d=0;d<t.length;d++){let c=t[d];if(o){o=false;continue}if(c==="\\"&&r){o=true;continue}if(c==='"'){r=!r;continue}if(!r){if(c==="{")n++;else if(c==="}"&&(n--,n===0)){let u=t.slice(s,d+1).trim();u&&e.push(u),s=d+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function a_(t){return t[0]==="exec"?t.slice(1):t}function Rc(t){let e=t.split(`
|
|
46
|
+
`).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 Mt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Sc(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Mt(t.error)}function bc(t){let e=Mt(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 d_(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Mt(n)&&Sc(n))return bc(n)}}function Ec(t,e,n,r){if(!n||t.type!=="command_execution"&&t.type!=="mcp_tool_call"||typeof t.id!="string"||!t.id.trim()||t.type==="mcp_tool_call"&&e==="item.started"&&(typeof t.server!="string"||typeof t.tool!="string"))return;let o=n.state.get("codex.pending");o||(o=new Map,n.state.set("codex.pending",o));let s=JSON.stringify([t.type,t.id]);if(e==="item.started"){let c=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,u=o.get(s)??[];return u.push(c),o.set(s,u),c}let i=o.get(s),d=i?.pop();return i?.length||o.delete(s),d}function c_(t,e,n){let r=e.type;if(r==="command_execution"){let o=String(e.command||"");return kt(o)?[Tt(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:rt(e.arguments),...n?{toolUseId:n}:{}}]:[]}function u_(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=l_(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",...nt(o,s),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let o=Mt(e.result)?e.result:void 0,i=(Array.isArray(o?.content)?o.content:[]).filter(c=>Mt(c)&&c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
|
|
47
|
+
`),d=typeof e.error=="string"?e.error:Mt(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||d,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=rt(s);return o==="Bash"&&kt(i)?Tt(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",...nt(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&&!(Mt(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(d=>String(d.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 l_(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=rt(o);return r==="Bash"&&kt(s)?Tt(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var o_,s_,Fs,js=x(()=>{h();Kt();io();ur();Tn();yn();Ps();wn();cr();Jt();Xt();o_=new Set(["turn.started","turn.completed","item.updated"]),s_="cli/codex";Fs={command:"codex",meta:{displayName:"Codex",models:ec(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Lt(e.model),s=e.effort??o,i=e.resumeSessionId?ic(e.mode):sc(e.mode),d=ac(s),c=r?["-m",r]:[],u=a_(e.additionalArgs??[]),l=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...l,...i,...d,...c,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...l,...i,...d,...c,...u],stdinMessage:t}},extractText(t){let e=d_(t);if(e)throw new ae(e,s_);let n=Rc(t);if(n)return n;let r=t.trim();return kn(r,"codex")?"":r},extractPartialText(t){return Rc(t)},parseResultMeta(t){let e=Rn(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=i_(t),s.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,d]of s.entries()){let c;try{c=JSON.parse(d);}catch{continue}if(!Mt(c))continue;let u=c.type;if(!u)continue;let f=ot(c,r);if(Sc(c)){let g=bc(c);o.push({timestamp:f,type:"error",content:g,errorMessage:g});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Ds(c))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let l=c.item;if(l){if(u==="item.started"){o.push(...c_(f,l,Ec(l,u,n,i)));continue}if(u==="item.completed"){let g=u_(f,l,Ec(l,u,n,i));g&&o.push(g);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?o_.has(r):!1}catch{return false}}};});function g_(t){return t?f_[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function fo(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Nc(t){let e=[],n=0,r=false,o=false,s=0;for(let d=0;d<t.length;d++){let c=t[d];if(o){o=false;continue}if(c==="\\"&&r){o=true;continue}if(c==='"'){r=!r;continue}if(!r){if(c==="{")n++;else if(c==="}"&&(n--,n===0)){let u=t.slice(s,d+1).trim();u&&e.push(u),s=d+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function Sn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function __(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);Sn(i)?e.push(i):n=!0;continue}catch{}let s=Nc(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 d=JSON.parse(i);Sn(d)?e.push(d):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Yt(t){if(typeof t!="string")return;let e=t.split(/\r?\n/).map(n=>n.trim()).find(n=>n&&!/^at\s+/.test(n));if(e)return e.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").replace(/(?:[A-Za-z]:[\\/]|\/)(?:[^\s"'`()\[\]{}]+[\\/])*[^\s"'`()\[\]{}]+/g,"[path]").slice(0,vc).trim()}function xc(t){let e=Sn(t.error)?t.error:void 0,n=e&&Sn(e.data)?e.data:void 0,r=Yt(e?.name),o=Yt(n?.message)??Yt(e?.message)??Yt(t.message)??Yt(t.errorMessage)??Yt(t.error),s=Yt(t.ref),i=r&&o&&r!==o?`${r}: ${o}`:r??o??Oc;return (s?`${i} (ref: ${s})`:i).slice(0,vc)}function Ic(t){let e=__(t),n=[],r=null,o=0,s=[],i,d=false;for(let c of e.events){let u=typeof c.type=="string"?c.type:void 0;if(u){if(u==="text"){let f=Sn(c.part)?c.part:void 0,l=typeof f?.text=="string"?f.text:void 0;l?.trim()&&n.push(l.trim());continue}if(u==="result"){typeof c.result=="string"&&(r=c.result);continue}if(u==="tool_use"){o++;continue}if(u==="error"){s.push(xc(c));continue}if(u==="step_finish"){d=true;let f=Sn(c.part)?c.part:void 0;i=typeof f?.reason=="string"?f.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorMessages:s,terminalReason:i,hasTerminal:d}}function Cc(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function go(){return new ae("OpenCode returned no assistant output.",En,{code:"EMPTY_OUTPUT",kind:"transient"})}function h_(){return new ae("OpenCode emitted malformed JSON output.",En,{code:"PROVIDER_CRASHED",kind:"transient"})}function Ac(t,e){switch(Cc(t)){case "length":return new ae("OpenCode stopped because the context window was exceeded.",En,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new ae("OpenCode stopped because the content filter blocked the response.",En,{code:"UNKNOWN",kind:"permanent"});case "error":return new ae(e?`OpenCode error: ${e}`:`${Oc} while generating a response.`,En,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var p_,En,Oc,vc,f_,Ws,zs=x(()=>{h();Kt();ur();yn();Xt();p_=new Set(["step_start","step_finish"]),En="cli/opencode",Oc="OpenCode provider error",vc=240,f_={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Ws={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];fo(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=g_(e.mode);fo(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!fo(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!fo(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let d;return !n&&!i&&!e.env?.OPENCODE_PERMISSION&&(d={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:d}},extractText(t){let e=Ic(t),n=e.errorMessages[0];if(n){let i=Ac("error",n);if(i)throw i}let r=Ac(e.terminalReason??"",void 0);if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0){if(!e.hasTerminal)throw go();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw go();return e.resultText}if(e.malformed)throw h_();if(!e.hasTerminal)throw go();let s=Cc(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw go()},interpretExit(t,e,n=""){if(t===0)return null;let o=Ic(n).errorMessages[0];return o?new ae(`OpenCode error: ${o}`,En,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=Rn(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=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=Nc(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let d=ot(i,n),c=i.type;if(c){if(c==="text"){let f=i.part?.text;f&&r.push({timestamp:d,type:"text",content:f});continue}if(c==="tool_use"){let u=i.part;if(!u)continue;let f=String(u.tool||""),l=String(u.callID||""),g=u.state,_=String(g?.status||""),m=g?.input,k=rt(m);if(r.push({timestamp:d,type:"tool_use",toolName:f,toolUseId:l,toolInput:k}),_==="completed"&&g?.output!==void 0){let T=g.output,E=typeof T=="string"?T:JSON.stringify(T);r.push({timestamp:d,type:"tool_result",toolUseId:l,resultPreview:E,isError:false});}else _==="error"&&r.push({timestamp:d,type:"tool_result",toolUseId:l,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(c==="error"){let u=xc(i);r.push({timestamp:d,type:"error",content:u,errorMessage:u});continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?p_.has(r):!1}catch{return false}}};});function lr(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function m_(t,e){if(!(t?Pt(Gs).some(s=>s.id===t):false)||!t)return e;let r=dr(Gs,t),o=Qd(Gs)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var Gs,Ks,Vs=x(()=>{h();Kt();ar();Jt();cr();Gs="antigravity";Ks={command:"agy",meta:{displayName:"Antigravity",models:nc(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=Lt(e.model),s=Hs(r),i=s.model,d=e.effort??o??s.effort,c=m_(i,d),u=e.additionalArgs??[],f=i&&!lr(u,"--model")?["--model",i]:[],l=lr(u,"--effort")?[]:_c(c),g=lr(u,"--mode")||lr(u,"--dangerously-skip-permissions")?[]:gc(e.mode),_=lr(u,"--print")?[]:["--print",t];return {args:[...f,...l,...g,...u,..._]}},extractText(t){let e=t.trim();if(!e)throw new ae("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"});return e},parseResultMeta(t){return {usage:null,model:null}},parseEvent(t,e){return []}};});var Dc=x(()=>{h();Tn();yn();wn();Xt();});function bn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function In(t){return bn(t)?t:void 0}function Le(t){return typeof t=="string"?t:void 0}function Zt(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function R_(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let d=t[i];if(n===-1){(d==="{"||d==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(d==="\\"&&o){s=true;continue}if(d==='"'){o=!o;continue}o||(d==="{"||d==="["?r+=1:(d==="}"||d==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function pr(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return bn(n)?[n]:[]}catch{return R_(e).flatMap(n=>{try{let r=JSON.parse(n);return bn(r)?[r]:[]}catch{return []}})}}function $c(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Qt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Qt).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
48
|
+
`):void 0}if(bn(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=Qt(t[e]);if(n!==void 0)return n}}}function E_(t){let e=i=>Array.isArray(i)&&i.every(d=>Number.isInteger(d)&&d>=0&&d<=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 d=JSON.stringify(i,(c,u)=>e(u)?`<bytes:${u.length}>`:u);return d===void 0?String(i):d},s=t.rawOutput;if(s!=null){let i=In(s);if(!i)return n(Qt(s))??o(s);let d;if(e(i.output)&&i.output.length>0&&(d=n(r(i.output))),!d&&e(i.stdout)&&i.stdout.length>0&&(d=n(r(i.stdout))),!d){let f=In(i.Result);d=n(i.output)??n(f?.output)??n(Qt(s));}let c=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(c!==void 0)if(d){let f=d.endsWith(`
|
|
49
|
+
`)||d.endsWith("\r")?"":`
|
|
50
|
+
`;d=`${d}${f}${c}`;}else d=n(c);if(d)return d;let u=n(i.summary)??n(Qt(t.content))??n(i.output_for_prompt);return u!==void 0?u:o(s)}if(t.content!==null&&t.content!==void 0)return Qt(t.content)??o(t.content);if(t.result!==null&&t.result!==void 0)return Qt(t.result)??o(t.result)}function Uc(t){let e=In(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?Bc(n):"Grok CLI reported an error."}function Bc(t){return (t.replace(y_,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Hc(t){return w_.test(t)}function S_(t){let e=In(t.modelUsage);return e?Object.keys(e)[0]??null:null}function b_(t){let e=In(t.usage);if(!e)return null;let n=Zt(e.cache_read_input_tokens);return {inputTokens:Zt(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Zt(e.output_tokens),costUsd:Zt(t.total_cost_usd)}}function I_(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
51
|
+
`).flatMap(pr)){if(i.type!=="usage")continue;let d=In(i.usage);if(!d)continue;let c=Le(i.signature);if(c&&c.length>0){let f=`signature:${c}`;if(s.has(f))continue;s.add(f);}let u=Zt(d.cache_read_input_tokens);e+=Zt(d.input_tokens)+u,n+=u,r+=Zt(d.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function A_(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,Pc)){if(!bn(s))continue;let i=Le(s.content)?.trim();if(!i)continue;let d=Le(s.status)?.trim(),c=Le(s.priority)?.trim(),u=[d?`status=${d}`:void 0,c?`priority=${c}`:void 0].filter(l=>!!l),f=u.length>0?` (${u.join(", ")})`:"";n.push(`- ${i}${f}`);}if(n.length===0)return [];e.entries.length>Pc&&n.push(Mc);let r=n.join(`
|
|
52
|
+
`),o=r.length>Lc?`${r.slice(0,Lc-1)}${Mc}`:r;return [{timestamp:t,type:"info",content:o}]}function O_(t,e){let n=Le(e.type);if(n==="thought"){let r=Le(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=Le(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return A_(t,e);if(n==="tool_call"){let r=Le(e.toolCallId),o=Le(e.toolName)??Le(e.title),s=e.rawInput===void 0?void 0:$c(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=Le(e.status);if(r!=="completed"&&r!=="failed"&&r!=="error")return [];let o=E_(e),s=r!=="completed"||e.isError===true;return [{timestamp:t,type:"tool_result",toolUseId:Le(e.toolCallId),toolName:Le(e.toolName)??Le(e.title),...o!==void 0?nt(o,s):{isError:s}}]}if(n==="error"){let r=Uc(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var _o,T_,w_,y_,Pc,Lc,Mc,Js,Xs=x(()=>{h();Kt();xs();Jt();wn();cr();Xt();_o="cli/grok",T_=new Set(["available_commands","usage","end"]),w_=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,y_=/\u001b\[[0-?]*[ -/]*[@-~]/g,Pc=20,Lc=4e3,Mc="\u2026";Js={command:"grok",createSessionId:()=>crypto.randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=Lt(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],d=n?Pt("grok").some(y=>y.id===n):false,c=n&&d?dr("grok",n):[],u=!o||c.length===0||c.includes(o)?o:void 0,f=fc(u),l=e.additionalArgs??[],g=y=>l.some(b=>b===y||b.startsWith(`${y}=`)),_=e.providerOptions,m=_?.alwaysApprove,k=_?.sandbox,T=g("--permission-mode")?[]:uc(e.mode),E=g("--always-approve")?[]:lc(m),S=g("--sandbox")?[]:pc(k),D=g("--verbatim")?[]:["--verbatim"];return {args:["--no-auto-update",...s,"--single",t,...D,"--output-format","streaming-json","--no-alt-screen",...i,...f,...T,...E,...S,...l]}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
53
|
+
`).flatMap(pr))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 pr(t))if(e.type==="error"){let n=Uc(e);return Hc($c(e))?new Vt(n,_o):new ae(n,_o)}return null},interpretExit(t,e){if(t===0)return null;let n=Bc(e)||`Grok CLI exited with code ${t}.`;return Hc(e)?new Vt(n,_o):new ae(n,_o)},parseResultMeta(t){let n=t.split(`
|
|
54
|
+
`).flatMap(pr).find(r=>r.type==="end");return n?{usage:b_(n),model:S_(n)}:{usage:I_(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return pr(t).flatMap(r=>O_(ot(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return bn(n)&&typeof n.type=="string"?T_.has(n.type):!1}catch{return false}}};});var qc,Fc=x(()=>{h();Us();qs();js();zs();Vs();Dc();Xs();Us();qs();js();zs();Vs();Xs();Tn();qc={codex:Fs,claude:po,opencode:Ws,antigravity:Ks,copilot:Bs,grok:Js};});function jc(t){if(t.startsWith("cli/"))return qc[t.slice(4)]}var Wc=x(()=>{h();jd();Fc();});function ho(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function v_(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function mo(t){if(typeof t.provider!="string"||t.provider.length===0)return;let n=t.taskLogRepository.readLogs(t.taskId)?.entries.filter(g=>g.level==="stdout").map(g=>g.message).join(`
|
|
55
|
+
`)??"";if(!n.trim())return;let r=jc(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=v_(o?.model,t.model),i=o?.usage;if(!i)return {stdout:n,adapter:r};let d=ho(i.inputTokens),c=ho(i.outputTokens),u=ho(i.cachedInputTokens),f=vd(ho(i.costUsd),d,c,u,s);return d!==0||c!==0||u!==0||f!==0?{stdout:n,adapter:r,usage:{inputTokens:d,outputTokens:c,cachedInputTokens:u,costUsd:f,model:s}}:{stdout:n,adapter:r}}var Ys=x(()=>{h();Wc();ro();});function To(t){let e=new Set;for(let n of t)for(let r of x_.get(n)??[n])e.add(r);return [...e]}function Qs(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"&&C_.has(n)?n:void 0}catch{return}}function wt(t){let e=Qs(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(exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS.stopped.test(t.error))return "user_stop";if(exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS.runnerLost.test(t.error))return "runner_lost"}}function st(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=Qs(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function D_(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function On(t){let e=st(t);return t.status==="runner_lost"&&Qs(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...D_(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}function P_(t){return st(t)==="failed"&&wt(t)!=="runner_lost"}exports.TASK_TERMINAL_STATUSES=void 0;exports.TASK_TERMINAL_STORED_STATUSES=void 0;var x_;exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS=void 0;var C_,fr=x(()=>{h();exports.TASK_TERMINAL_STATUSES=["success","failed","stopped"],exports.TASK_TERMINAL_STORED_STATUSES=["success","completed","done","failed","error","stopped","runner_lost"],x_=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);exports.LEGACY_TASK_TERMINAL_ERROR_PATTERNS={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},C_=new Set(["user_stop","runner_lost","launch_failed"]);});function ri(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 yo(){return ri("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function en(){return ri("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function gr(){return ri("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Nn(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 M_(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 zc(t,e){return !!t.stop_requested_at&&Nn(t.stop_requested_epoch)===Nn(e)}function Zs(t,e){let n=Nn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=M_(t.getTask(e.taskId));return !o||o.status!=="running"||Nn(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function Gc(t,e){let n=exports.taskHeartbeatRegistry.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),exports.taskHeartbeatRegistry.delete(t),true)}function Kc(t,e){let n=exports.taskHeartbeatRegistry.get(t);return !n||e!==void 0&&n.runEpoch!==Nn(e)?false:Gc(t,n)}function H_(t,e){let n=Nn(e.runEpoch);Kc(e.taskId);let r=true,o=null;try{let u=Zs(t,{...e,runEpoch:n});r=u.accepted,o=u.row;}catch(u){wo(u);}if(!r)return false;let s=yo(),i=Math.min(s,1e3),d=setInterval(()=>{let u=exports.taskHeartbeatRegistry.get(e.taskId);if(!(!u||u.timer!==d))try{u.heartbeatElapsedMs+=i;let f=u.heartbeatElapsedMs>=s,l=Zs(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:f});if(!l.accepted){Gc(e.taskId,u);return}f&&(u.heartbeatElapsedMs%=s,u.lastHeartbeatAt=Date.now()),l.row&&zc(l.row,n)&&!u.stopRequested&&(u.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(l.row)).catch(wo));}catch(f){wo(f);}},i),c={timer:d,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return exports.taskHeartbeatRegistry.set(e.taskId,c),typeof d=="object"&&d!==null&&"unref"in d&&d.unref(),o&&zc(o,n)&&e.onStopRequested&&(c.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(wo)),true}exports.TASK_HEARTBEAT_INTERVAL_MS=void 0;exports.TASK_HEARTBEAT_STALE_MS=void 0;exports.TASK_HEARTBEAT_HARD_STALE_MS=void 0;exports.TASK_STOP_POLL_INTERVAL_MS=void 0;exports.taskHeartbeatRegistry=void 0;var _r=x(()=>{h();exports.TASK_HEARTBEAT_INTERVAL_MS=1e4,exports.TASK_HEARTBEAT_STALE_MS=3e4,exports.TASK_HEARTBEAT_HARD_STALE_MS=18e5,exports.TASK_STOP_POLL_INTERVAL_MS=1e3;exports.taskHeartbeatRegistry=new Map;});function ci(t,e=Date.now(),n=exports.TASK_STOP_DEFAULT_GRACE_MS){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=di(n,exports.TASK_STOP_DEFAULT_GRACE_MS,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function di(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function tu(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function $_(t){if(!t)return;let e=tu(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function yt(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=$_(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function nu(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 Se(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 oi(t,e){return Se(t,exports.INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED,e)}function U_(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=en():false}function B_(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function q_(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=tu(t.metadata),r=n.ownership==="runner"&&typeof n.providerPid=="number"&&Number.isSafeInteger(n.providerPid)&&n.providerPid>0?n.providerPid:void 0;return [...new Set([e,r].filter(o=>o!==void 0))]}function F_(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return yt(r,n)}async function j_(t,e,n,r){let o=Date.now()+n;for(;;){let s=F_(t,e);if(s)return s;let i=o-Date.now();if(i<=0)return;await new Promise(d=>{setTimeout(d,Math.min(r,i));});}}async function Vc(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 D=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),y=t.getTask(e);if(D||!y||y.status!=="running")return yt(y);if(s=t.requestTaskStop({id:e,requestedAt:r,...o}),!s.accepted&&s.status!=="running"||!s.accepted&&!s.alreadyRequestedAt)return yt(t.getTask(e))}else if(!(s.status==="running"&&s.alreadyRequestedAt))return yt(i)}let d=s.runEpoch,c=di(n.graceMs,exports.TASK_STOP_DEFAULT_GRACE_MS,0),u=di(n.pollMs,exports.TASK_STOP_DEFAULT_POLL_MS,1),f=await j_(t,e,c,u);if(f)return f;let l=t.getTask(e);if(!l||l.status!=="running")return yt(l);let g=q_(l),_=g[0];if(!_){let D=t.finalizeTaskStop({id:e,runEpoch:d,method:"forced"}),y=t.getTask(e);return D||y?.status!=="running"?yt(y):Se(y,"Failed to finalize task stop")}let m=B_(n),k="unknown";if(!U_(l,Date.now())){let D=n.processControl?.checkProcessOwnershipAsync??Os;try{k=await D(_,n.ownershipMarkers??exports.TASK_STOP_OWNED_PROCESS_MARKERS,m);}catch{k="unknown";}if(k!=="owned")return nu(l)}let T=n.processControl?.terminateProcessTree??vs;for(let D of g){let y;try{y=await T(D,{...m,signal:As});}catch(b){y={status:"failed",pid:D,method:m.platform==="win32"?"taskkill":"process-group",error:b instanceof Error?b.message:String(b)};}if(y.status==="failed")return Se(t.getTask(e),y.error??"Failed to terminate process tree")}let E=t.finalizeTaskStop({id:e,runEpoch:d,method:"forced"}),S=t.getTask(e);return E||S?.status!=="running"?yt(S,_):Se(S,"Task changed before stop was finalized")}function Jc(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Xc(t){return Number.isSafeInteger(t)&&t>=0}function si(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function W_(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}async function ru(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return oi(n,Jc(e.targetPid)?e.targetPid:void 0);if(!Xc(e.sourceRunEpoch)||!Xc(e.settleRunEpoch)||si(n.run_epoch)!==e.settleRunEpoch)return Se(n,exports.INSTRUCTION_STOP_EPOCH_MISMATCH,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return Se(n,exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH,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 Se(n,exports.INSTRUCTION_STOP_REQUEST_FAILED,e.targetPid)}let s=t.getTask(e.taskId);if(!s||s.status!=="running")return oi(s,e.targetPid);if(o.runEpoch!==e.settleRunEpoch||si(s.run_epoch)!==e.settleRunEpoch)return Se(s,exports.INSTRUCTION_STOP_EPOCH_MISMATCH,e.targetPid);if(e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId)return Se(s,exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH,e.targetPid);if(!Jc(e.targetPid))return Se(s,exports.INSTRUCTION_STOP_TARGET_PID_MISSING);let i=W_(e),d=e.processControl?.checkProcessOwnershipAsync??Os,c="unknown";try{c=await d(e.targetPid,e.ownershipMarkers??exports.TASK_STOP_OWNED_PROCESS_MARKERS,i);}catch{c="unknown";}if(c!=="owned")return nu(s,e.targetPid);let u=t.getTask(e.taskId);if(!u||u.status!=="running")return oi(u,e.targetPid);if(si(u.run_epoch)!==e.settleRunEpoch)return Se(u,exports.INSTRUCTION_STOP_EPOCH_MISMATCH,e.targetPid);if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId)return Se(u,exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH,e.targetPid);let f=e.processControl?.terminateProcessTree??vs,l;try{l=await f(e.targetPid,{...i,signal:As});}catch{return Se(t.getTask(e.taskId),exports.INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED,e.targetPid)}if(l.status==="failed")return Se(t.getTask(e.taskId),exports.INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return Se(t.getTask(e.taskId),exports.INSTRUCTION_STOP_SETTLE_CAS_FAILED,e.targetPid)}return g?yt(t.getTask(e.taskId),e.targetPid):Se(t.getTask(e.taskId),exports.INSTRUCTION_STOP_SETTLE_CAS_FAILED,e.targetPid)}function li(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(xn(),ou)).then(({TaskRepository:s})=>Vc(new s,r,o))}return Vc(t,e,n)}exports.TASK_STOP_DEFAULT_GRACE_MS=void 0;exports.TASK_STOP_DEFAULT_POLL_MS=void 0;exports.TASK_STOP_OWNED_PROCESS_MARKERS=void 0;exports.INSTRUCTION_STOP_TARGET_PID_MISSING=void 0;exports.INSTRUCTION_STOP_EPOCH_MISMATCH=void 0;exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH=void 0;exports.INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED=void 0;exports.INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED=void 0;exports.INSTRUCTION_STOP_SETTLE_CAS_FAILED=void 0;exports.INSTRUCTION_STOP_REQUEST_FAILED=void 0;var pi=x(()=>{h();Ns();_r();exports.TASK_STOP_DEFAULT_GRACE_MS=5e3,exports.TASK_STOP_DEFAULT_POLL_MS=250;exports.TASK_STOP_OWNED_PROCESS_MARKERS=["crewx","claude","codex","opencode","grok","node"],exports.INSTRUCTION_STOP_TARGET_PID_MISSING="INSTRUCTION_STOP_TARGET_PID_MISSING",exports.INSTRUCTION_STOP_EPOCH_MISMATCH="INSTRUCTION_STOP_EPOCH_MISMATCH",exports.INSTRUCTION_STOP_WORKSPACE_MISMATCH="INSTRUCTION_STOP_WORKSPACE_MISMATCH",exports.INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",exports.INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",exports.INSTRUCTION_STOP_SETTLE_CAS_FAILED="INSTRUCTION_STOP_SETTLE_CAS_FAILED",exports.INSTRUCTION_STOP_REQUEST_FAILED="INSTRUCTION_STOP_REQUEST_FAILED";});var ou={};ql(ou,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>exports.DEFAULT_TASK_REAPER_TICK_INTERVAL_MS,HOST_SHUTDOWN_TERMINAL_ERROR:()=>du,PENDING_ADOPT_GRACE_MS:()=>uu,PID_NULL_REAP_GRACE_MS:()=>yi,RATED_TASK_EXCERPT_MAX_CHARS:()=>exports.RATED_TASK_EXCERPT_MAX_CHARS,RATED_TASK_LIST_MAX_LIMIT:()=>exports.RATED_TASK_LIST_MAX_LIMIT,TASK_HEARTBEAT_HARD_STALE_MS:()=>exports.TASK_HEARTBEAT_HARD_STALE_MS,TASK_HEARTBEAT_INTERVAL_MS:()=>exports.TASK_HEARTBEAT_INTERVAL_MS,TASK_HEARTBEAT_STALE_MS:()=>exports.TASK_HEARTBEAT_STALE_MS,TASK_RATINGS:()=>exports.TASK_RATINGS,TaskRatingError:()=>exports.TaskRatingError,TaskRepository:()=>exports.TaskRepository,buildRatedTasksCountQuery:()=>gu,buildRatedTasksQuery:()=>pu,countRatedTasks:()=>_u,hasRecordedUsage:()=>Mn,listRatedTasks:()=>fu,mergeTerminalReason:()=>vo,resolveTaskHeartbeatHardStaleMs:()=>gr,resolveTaskHeartbeatIntervalMs:()=>yo,resolveTaskHeartbeatStaleMs:()=>en,setTaskRating:()=>lu});function at(t){return On(t)}function gi(t){return On(t)}function hi(t=exports.tasks.model,e=exports.tasks.metadata){let n=drizzleOrm.sql`
|
|
56
|
+
CASE
|
|
57
|
+
WHEN ${t} LIKE 'claude-%' OR ${t} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
58
|
+
WHEN ${t} LIKE 'gpt-%' OR ${t} LIKE 'codex-%' THEN 'codex'
|
|
59
|
+
WHEN ${t} LIKE 'gemini-%' THEN 'gemini'
|
|
60
|
+
WHEN ${t} LIKE 'grok-%' THEN 'grok'
|
|
61
|
+
WHEN ${t} LIKE 'zai-%' OR ${t} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
62
|
+
WHEN ${t} LIKE 'minimax/%' THEN 'minimax'
|
|
63
|
+
WHEN ${t} LIKE 'qwen%' THEN 'qwen'
|
|
64
|
+
ELSE 'unknown'
|
|
65
|
+
END
|
|
66
|
+
`,r=drizzleOrm.sql`json_extract(${e}, '$.provider')`,o=drizzleOrm.sql`trim(${r})`,s=drizzleOrm.sql`substr(${o}, 1, instr(${o}, '/') - 1)`,i=drizzleOrm.sql`
|
|
67
|
+
CASE
|
|
68
|
+
WHEN instr(${o}, '/') > 0
|
|
69
|
+
AND ${s} IN ('cli', 'acp', 'api', 'plugin', 'remote')
|
|
70
|
+
THEN substr(${o}, instr(${o}, '/') + 1)
|
|
71
|
+
ELSE ${o}
|
|
72
|
+
END
|
|
73
|
+
`;return drizzleOrm.sql`
|
|
74
|
+
CASE
|
|
75
|
+
WHEN ${e} IS NULL THEN ${n}
|
|
76
|
+
WHEN json_valid(${e}) = 0 THEN 'unknown'
|
|
77
|
+
WHEN json_type(${e}, '$') IS NOT 'object' THEN 'unknown'
|
|
78
|
+
WHEN json_type(${e}, '$.provider') IS NULL THEN ${n}
|
|
79
|
+
WHEN json_type(${e}, '$.provider') IS NOT 'text' THEN 'unknown'
|
|
80
|
+
WHEN ${o} = '' THEN 'unknown'
|
|
81
|
+
WHEN trim(${i}) = '' THEN 'unknown'
|
|
82
|
+
ELSE ${i}
|
|
83
|
+
END
|
|
84
|
+
`}function Q_(t){let e={status:t.status,metadata:t.metadata},n=st(e);return n==="stopped"||n==="failed"&&wt(e)==="runner_lost"}function Tr(t){return drizzleOrm.sql`${t} NOT IN (${drizzleOrm.sql.join(Z_.map(e=>drizzleOrm.sql`${e}`),drizzleOrm.sql`, `)})`}function bo(t){let e=drizzleOrm.sql`
|
|
85
|
+
CASE
|
|
86
|
+
WHEN json_valid(${t}) = 1
|
|
87
|
+
THEN json_extract(${t}, '$.usageAccounting')
|
|
88
|
+
ELSE NULL
|
|
89
|
+
END
|
|
90
|
+
`;return drizzleOrm.sql`
|
|
91
|
+
COALESCE(SUM(
|
|
92
|
+
CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
|
|
93
|
+
), 0)
|
|
94
|
+
`}function Ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function he(t){if(!t)return {};try{let e=JSON.parse(t);return Ln(e)?{...e}:{}}catch{return {}}}function Oo(t){return t==null||t===""}function ki(t,e){return Oo(t)&&!Oo(e)?e:t}function eh(t,e){let n=he(t);if(!e)return n;for(let[r,o]of Object.entries(e))Oo(n[r])&&!Oo(o)&&(n[r]=o);return n}function Io(t,e){let n=t.origin&&cu.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 th(t){let e=he(t).stopRequest;if(Ln(e)&&!(typeof e.origin!="string"||!cu.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function iu(){return drizzleOrm.or(drizzleOrm.isNull(exports.tasks.stop_requested_at),drizzleOrm.ne(drizzleOrm.sql`COALESCE(${exports.tasks.stop_requested_epoch}, 0)`,drizzleOrm.sql`COALESCE(${exports.tasks.run_epoch}, 0)`))}function vo(t,e){let n=he(t??null);return n.terminalReason=e,JSON.stringify(n)}function Ti(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==su&&(n[Y_]=e),{error:su,metadata:n}}function be(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Mn(t){return be(t.input_tokens)!==0||be(t.output_tokens)!==0||be(t.cached_input_tokens)!==0||be(t.cost_usd)!==0}function X(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function au(t){return {inputTokens:be(t.inputTokens??0),outputTokens:be(t.outputTokens??0),cachedInputTokens:be(t.cachedInputTokens??0),costUsd:be(t.costUsd??0)}}function nh(t){if(Ln(t))return {inputTokens:be(t.inputTokens),outputTokens:be(t.outputTokens),cachedInputTokens:be(t.cachedInputTokens),costUsd:be(t.costUsd)}}function rh(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=nh(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Ao(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}function $n(t,e){if(typeof t!="string"||t.length===0)throw new exports.RepositoryError("VALIDATION",`${e} is required`);return t}function bi(t,e){let n=Date.parse(t);if(!Number.isFinite(n))throw new exports.RepositoryError("VALIDATION",`${e} is not a valid ISO time: ${t}`);return new Date(n).toISOString()}function lu(t,e){let n=$n(e.workspaceId,"workspaceId"),r=$n(e.taskId,"taskId"),o=e.rating;if(o!==null&&!exports.TASK_RATINGS.includes(o))throw new exports.RepositoryError("VALIDATION","rating must be 'up', 'down' or null");let s=e.now===void 0?new Date().toISOString():bi(e.now,"now");try{return t.transaction(i=>{let d=drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,r),drizzleOrm.eq(exports.tasks.workspace_id,n),drizzleOrm.inArray(exports.tasks.status,[...exports.TASK_TERMINAL_STORED_STATUSES])),c=i.update(exports.tasks).set({rating:o,rated_at:o===null?null:s}).where(drizzleOrm.and(d,drizzleOrm.sql`${exports.tasks.rating} IS NOT ${o}`)).returning({rating:exports.tasks.rating,ratedAt:exports.tasks.rated_at}).all();if(c.length>0)return {taskId:r,rating:c[0].rating,ratedAt:c[0].ratedAt,changed:!0};let u=i.select({status:exports.tasks.status,rating:exports.tasks.rating,rated_at:exports.tasks.rated_at}).from(exports.tasks).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,r),drizzleOrm.eq(exports.tasks.workspace_id,n))).limit(1).get();if(!u)throw new exports.TaskRatingError("TASK_NOT_FOUND",r);if(!sh.has(u.status))throw new exports.TaskRatingError("TASK_RATING_NOT_TERMINAL",r);return {taskId:r,rating:u.rating,ratedAt:u.rated_at,changed:!1}},{behavior:"immediate"})}catch(i){throw i instanceof exports.RepositoryError?i:new exports.RepositoryError("DB_ERROR","Failed to set task rating",i)}}function pu(t){let e=drizzleOrm.sql`
|
|
95
|
+
SELECT id, rated_at FROM tasks
|
|
96
|
+
WHERE workspace_id = ${t.workspaceId}
|
|
97
|
+
AND rating IS NOT NULL
|
|
98
|
+
${t.agentId!==void 0?drizzleOrm.sql`AND agent_id = ${t.agentId}`:drizzleOrm.sql``}
|
|
99
|
+
${t.sinceIso!==void 0?drizzleOrm.sql`AND rated_at >= ${t.sinceIso}`:drizzleOrm.sql``}
|
|
100
|
+
ORDER BY rated_at DESC, id DESC
|
|
101
|
+
LIMIT ${t.limit}
|
|
102
|
+
`;return drizzleOrm.sql`
|
|
103
|
+
SELECT t.id AS taskId, t.agent_id AS agentId, t.thread_id AS threadId, t.status AS status,
|
|
104
|
+
substr(t.error, 1, ${oh}) AS errorHead,
|
|
105
|
+
CASE WHEN json_valid(t.metadata) THEN json_extract(t.metadata, '$.terminalReason') END AS terminalReason,
|
|
106
|
+
t.rating AS rating, t.rated_at AS ratedAt,
|
|
107
|
+
NULLIF(substr(t.prompt, 1, ${exports.RATED_TASK_EXCERPT_MAX_CHARS}), '') AS promptExcerpt,
|
|
108
|
+
NULLIF(substr(t.result, 1, ${exports.RATED_TASK_EXCERPT_MAX_CHARS}), '') AS resultExcerpt
|
|
109
|
+
FROM (${e}) AS page
|
|
110
|
+
JOIN tasks t ON t.id = page.id
|
|
111
|
+
ORDER BY page.rated_at DESC, page.id DESC
|
|
112
|
+
`}function fu(t,e){let n=$n(e.workspaceId,"workspaceId");if(e.agentId!==void 0&&$n(e.agentId,"agentId"),!Number.isFinite(e.limit)||Math.trunc(e.limit)<1)throw new exports.RepositoryError("VALIDATION","limit must be a positive integer");let r=Math.min(Math.trunc(e.limit),exports.RATED_TASK_LIST_MAX_LIMIT),o=e.sinceIso===void 0?void 0:bi(e.sinceIso,"sinceIso");try{return t.all(pu({workspaceId:n,agentId:e.agentId,sinceIso:o,limit:r})).map(i=>({taskId:i.taskId,agentId:i.agentId,threadId:i.threadId,status:st({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 exports.RepositoryError?s:new exports.RepositoryError("DB_ERROR","Failed to list rated tasks",s)}}function gu(t){return drizzleOrm.sql`
|
|
113
|
+
SELECT COUNT(*) AS total FROM tasks
|
|
114
|
+
WHERE workspace_id = ${t.workspaceId}
|
|
115
|
+
AND rating IS NOT NULL
|
|
116
|
+
${t.agentId!==void 0?drizzleOrm.sql`AND agent_id = ${t.agentId}`:drizzleOrm.sql``}
|
|
117
|
+
${t.sinceIso!==void 0?drizzleOrm.sql`AND rated_at >= ${t.sinceIso}`:drizzleOrm.sql``}
|
|
118
|
+
`}function _u(t,e){let n=$n(e.workspaceId,"workspaceId");e.agentId!==void 0&&$n(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:bi(e.sinceIso,"sinceIso");try{return t.all(gu({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to count rated tasks",o)}}var _i,Cn,J_,Dn,Pn,X_,mi,kr,dt,su,du,Y_,Z_,cu,yi,uu;exports.DEFAULT_TASK_REAPER_TICK_INTERVAL_MS=void 0;exports.TaskRepository=void 0;exports.TASK_RATINGS=void 0;exports.RATED_TASK_EXCERPT_MAX_CHARS=void 0;exports.RATED_TASK_LIST_MAX_LIMIT=void 0;var oh;exports.TaskRatingError=void 0;var sh,xn=x(()=>{h();re();ue();_e();ie();fe();ro();Ns();oo();ws();Ys();fr();_r();pi();_r();_i=40,Cn="2026-05-09",J_="0.8.9-rc.13",Dn=10,Pn=parseInt(J_.split("rc.")[1]);X_=new Set(["workflow","mcp"]),mi="usageByEpoch",kr="lateUsage",dt="usageAccounting",su="Stopped by user",du="Stopped by app shutdown",Y_="terminalErrorOriginal";Z_=["pending","running"];cu=new Set(["http","cli","instruction","workflow","internal"]);yi=600*1e3,uu=600*1e3,exports.DEFAULT_TASK_REAPER_TICK_INTERVAL_MS=300*1e3,exports.TaskRepository=class extends exports.BaseSqliteRepository{dbPath;clock;taskLogRepository;lastReaperTickAt;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new exports.TaskLogRepository({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?He(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=X(e.runEpoch),o=r===0?drizzleOrm.or(drizzleOrm.eq(exports.tasks.run_epoch,0),drizzleOrm.isNull(exports.tasks.run_epoch)):drizzleOrm.eq(exports.tasks.run_epoch,r);return n.db.update(exports.tasks).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e.id),o,drizzleOrm.eq(exports.tasks.status,"running"))).run().changes>0}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("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:exports.tasks.id,status:exports.tasks.status,run_epoch:exports.tasks.run_epoch,stop_requested_at:exports.tasks.stop_requested_at,stop_requested_epoch:exports.tasks.stop_requested_epoch,metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e.id)).limit(1).get();if(!s)return;let i=X(s.run_epoch);if(s.status!=="running"){r={accepted:!1,status:s.status,runEpoch:i};return}let d=s.stop_requested_at!==null&&X(s.stop_requested_epoch)===i,c=d?s.stop_requested_at:e.requestedAt,u=he(s.metadata),f=d?th(s.metadata)??Io({origin:e.origin,at:c,callerPid:e.callerPid,callerTaskId:e.callerTaskId},c):Io({origin:e.origin,at:c,callerPid:e.callerPid,callerTaskId:e.callerTaskId},c);if(o.update(exports.tasks).set({stop_requested_at:e.requestedAt,stop_requested_epoch:drizzleOrm.sql`${exports.tasks.run_epoch}`,metadata:JSON.stringify({...u,stopRequest:f})}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e.id),drizzleOrm.eq(exports.tasks.status,"running"),iu())).run().changes===0){let m=o.select({status:exports.tasks.status,run_epoch:exports.tasks.run_epoch,stop_requested_at:exports.tasks.stop_requested_at,stop_requested_epoch:exports.tasks.stop_requested_epoch}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:X(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:X(m.run_epoch),...m.stop_requested_at&&X(m.stop_requested_epoch)===X(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:s.status,runEpoch:i};let g=new Set([e.id]),_=(m,k)=>{if(k>=8)return;let T=o.select({id:exports.tasks.id,status:exports.tasks.status,metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.parent_task_id,m),drizzleOrm.eq(exports.tasks.status,"running"))).all();for(let E of T)g.has(E.id)||(g.add(E.id),o.update(exports.tasks).set({stop_requested_at:c,stop_requested_epoch:drizzleOrm.sql`${exports.tasks.run_epoch}`,metadata:JSON.stringify({...he(E.metadata),stopRequest:f})}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,E.id),drizzleOrm.eq(exports.tasks.status,"running"),iu())).run(),_(E.id,k+1));};_(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("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:exports.tasks.id,status:exports.tasks.status,run_epoch:exports.tasks.run_epoch,workspace_id:exports.tasks.workspace_id,stop_requested_at:exports.tasks.stop_requested_at,stop_requested_epoch:exports.tasks.stop_requested_epoch,metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e.id)).limit(1).get();if(!s)return;let i=X(s.run_epoch),d=X(e.sourceRunEpoch),c=X(e.settleRunEpoch);if(s.status!=="running"||i!==c||e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId){r={accepted:!1,status:s.status,runEpoch:i};return}let u=c===0?drizzleOrm.or(drizzleOrm.eq(exports.tasks.run_epoch,0),drizzleOrm.isNull(exports.tasks.run_epoch)):drizzleOrm.eq(exports.tasks.run_epoch,c),f=drizzleOrm.or(drizzleOrm.isNull(exports.tasks.stop_requested_at),drizzleOrm.isNull(exports.tasks.stop_requested_epoch),drizzleOrm.ne(exports.tasks.stop_requested_epoch,d)),l=Io({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),g=T=>o.update(exports.tasks).set({stop_requested_at:e.requestedAt,stop_requested_epoch:d,metadata:JSON.stringify({...he(s.metadata),stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e.id),drizzleOrm.eq(exports.tasks.status,"running"),u,T,f)).run();if((e.workspaceId===void 0?g():e.workspaceId===null?g(drizzleOrm.isNull(exports.tasks.workspace_id)):g(drizzleOrm.eq(exports.tasks.workspace_id,e.workspaceId))).changes>0){r={accepted:!0,status:s.status,runEpoch:c};return}let m=o.select({status:exports.tasks.status,run_epoch:exports.tasks.run_epoch,stop_requested_at:exports.tasks.stop_requested_at,stop_requested_epoch:exports.tasks.stop_requested_epoch}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:X(m?.run_epoch)};return}let k=X(m.run_epoch);r={accepted:!1,status:m.status,runEpoch:k,...m.stop_requested_at&&X(m.stop_requested_epoch)===d?{alreadyRequestedAt:m.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("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:exports.tasks.status,run_epoch:exports.tasks.run_epoch,stop_requested_at:exports.tasks.stop_requested_at,stop_requested_epoch:exports.tasks.stop_requested_epoch,started_at:exports.tasks.started_at,duration_ms:exports.tasks.duration_ms,metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e.id)).limit(1).get();if(!i||i.status!=="running"||X(i.run_epoch)!==X(e.runEpoch))return;let d=i.stop_requested_at!==null&&X(i.stop_requested_epoch)===X(e.runEpoch),c=he(i.metadata),u=d?Ti(c,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...c}:{...c,terminalReason:e.terminalReason}},f={...u.metadata,stopMethod:e.method},l=i.duration_ms??e.durationMs??Ao(i.started_at,r,void 0),g=i.run_epoch===null?drizzleOrm.isNull(exports.tasks.run_epoch):drizzleOrm.eq(exports.tasks.run_epoch,i.run_epoch);o=s.update(exports.tasks).set({status:"stopped",error:u.error,completed_at:r,duration_ms:l,metadata:JSON.stringify(f)}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e.id),drizzleOrm.eq(exports.tasks.status,"running"),g)).run().changes>0;},{behavior:"immediate"}),o}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("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=X(e.expectedRunEpoch),s="not_running";return n.db.transaction(i=>{let d=i.select({status:exports.tasks.status,run_epoch:exports.tasks.run_epoch,workspace_id:exports.tasks.workspace_id,started_at:exports.tasks.started_at,duration_ms:exports.tasks.duration_ms,metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e.id)).limit(1).get();if(!d||d.status!=="running"){s="not_running";return}if(X(d.run_epoch)!==o){s="epoch_mismatch";return}if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId){s="workspace_mismatch";return}let u=d.run_epoch===null?drizzleOrm.isNull(exports.tasks.run_epoch):drizzleOrm.eq(exports.tasks.run_epoch,d.run_epoch),f=e.workspaceId===void 0?void 0:e.workspaceId===null?drizzleOrm.isNull(exports.tasks.workspace_id):drizzleOrm.eq(exports.tasks.workspace_id,e.workspaceId),l={...he(d.metadata),terminalReason:"runner_lost"},g=d.duration_ms??Ao(d.started_at,r,void 0);s=i.update(exports.tasks).set({status:"failed",error:du,completed_at:r,duration_ms:g,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e.id),drizzleOrm.eq(exports.tasks.status,"running"),u,f)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),s}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return li(this,e,n)}async stopTaskGenerationForInstruction(e){return ru({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:exports.tasks.id}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.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,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,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=d=>{n.db.insert(exports.tasks).values(d).onConflictDoUpdate({target:exports.tasks.id,set:{status:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN 'running' ELSE ${exports.tasks.status} END`,pid:drizzleOrm.sql`COALESCE(excluded.pid, ${exports.tasks.pid})`,actor_kind:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} IN ('pending', 'running') AND ${exports.tasks.pid} IS NULL AND ${exports.tasks.actor_kind} IS NULL AND COALESCE(${exports.tasks.run_epoch}, 0) = 0 THEN excluded.actor_kind ELSE ${exports.tasks.actor_kind} END`,actor_id:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} IN ('pending', 'running') AND ${exports.tasks.pid} IS NULL AND ${exports.tasks.actor_kind} IS NULL AND COALESCE(${exports.tasks.run_epoch}, 0) = 0 THEN excluded.actor_id ELSE ${exports.tasks.actor_id} END`,command:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN excluded.command ELSE ${exports.tasks.command} END`,metadata:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN excluded.metadata ELSE ${exports.tasks.metadata} END`,workspace_id:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN COALESCE(${exports.tasks.workspace_id}, excluded.workspace_id) ELSE ${exports.tasks.workspace_id} END`,cwd:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN COALESCE(${exports.tasks.cwd}, excluded.cwd) ELSE ${exports.tasks.cwd} END`,project_id:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN COALESCE(${exports.tasks.project_id}, excluded.project_id) ELSE ${exports.tasks.project_id} END`,crewx_version:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN excluded.crewx_version ELSE ${exports.tasks.crewx_version} END`,model:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN excluded.model ELSE ${exports.tasks.model} END`,rendered_prompt:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN excluded.rendered_prompt ELSE ${exports.tasks.rendered_prompt} END`,security_key:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN excluded.security_key ELSE ${exports.tasks.security_key} END`,coding_agent_command:drizzleOrm.sql`CASE WHEN ${exports.tasks.status} = 'pending' AND ${exports.tasks.pid} IS NULL THEN excluded.coding_agent_command ELSE ${exports.tasks.coding_agent_command} END`},setWhere:drizzleOrm.or(drizzleOrm.eq(exports.tasks.status,"running"),drizzleOrm.and(drizzleOrm.eq(exports.tasks.status,"pending"),drizzleOrm.isNull(exports.tasks.pid)))}).run();};try{i(s);}catch(d){let c=d instanceof Error?d.message:typeof d=="object"&&d!==null&&"message"in d?String(d.message):String(d);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|cwd|actor_kind|actor_id/i.test(c)||!/no such column|no column named/i.test(c))throw d;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(Mr=>Mr.name)),f=u.has("cwd"),l=u.has("user_id"),g=u.has("actor_kind"),_=u.has("actor_id"),m=u.has("log_storage"),k=f?", cwd":"",T=f?", ?":"",E=f?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",S=m?", log_storage":"",D=m?", ?":"",y=l?", user_id":"",b=l?", ?":"",O=g?", actor_kind":"",ne=g?", ?":"",se=_?", actor_id":"",Et=_?", ?":"",ce=m?`,
|
|
119
|
+
log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
|
|
120
|
+
id, agent_id, prompt, mode, status, started_at, pid,
|
|
121
|
+
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
122
|
+
workspace_id${k}, project_id, platform, crewx_version, thread_id,
|
|
123
|
+
model, rendered_prompt, coding_agent_command${y}${O}${se}${S}
|
|
124
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${T}${b}${ne}${Et}${D})
|
|
125
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
126
|
+
status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
|
|
127
|
+
pid = COALESCE(excluded.pid, tasks.pid),
|
|
128
|
+
command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.command ELSE tasks.command END,
|
|
129
|
+
metadata = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.metadata ELSE tasks.metadata END,
|
|
130
|
+
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${E},
|
|
131
|
+
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,
|
|
132
|
+
crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
|
|
133
|
+
model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
|
|
134
|
+
rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
|
|
135
|
+
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${ce}
|
|
136
|
+
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,...f?[s.cwd]:[],s.project_id,s.platform,s.crewx_version,s.thread_id,s.model,s.rendered_prompt,s.coding_agent_command,...l?[s.user_id]:[],...g?[s.actor_kind]:[],..._?[s.actor_id]:[],...m?[s.log_storage]:[]]);}r&&!o&&new exports.AgentSendHistoryRepository({dbPath:this.resolveDbPath()}).recordAccepted({workspaceId:e.workspaceId,actorId:e.actorId,actorKind:e.actorKind,agentId:e.agentId});}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to start task",r)}finally{n.close();}}updateTaskOwnership(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:exports.tasks.status,run_epoch:exports.tasks.run_epoch,metadata:exports.tasks.metadata,model:exports.tasks.model,rendered_prompt:exports.tasks.rendered_prompt,coding_agent_command:exports.tasks.coding_agent_command}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e.id)).limit(1).get();if(!r||r.status!=="running"||X(r.run_epoch)!==X(e.runEpoch))return !1;let o=eh(r.metadata,e.runtime?.metadata);o.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0&&(o.providerPid=e.providerPid);let s=r.run_epoch===null?drizzleOrm.isNull(exports.tasks.run_epoch):drizzleOrm.eq(exports.tasks.run_epoch,r.run_epoch),i=n.db.update(exports.tasks).set({metadata:JSON.stringify(o),model:ki(r.model,e.runtime?.model),rendered_prompt:ki(r.rendered_prompt,e.runtime?.renderedPrompt),coding_agent_command:ki(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e.id),drizzleOrm.eq(exports.tasks.status,"running"),s)).run();return i.changes>0&&X(e.runEpoch)>0&&n.db.update(exports.tasks).set({stop_requested_at:null,stop_requested_epoch:null}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e.id),drizzleOrm.eq(exports.tasks.status,"running"),s,drizzleOrm.sql`${exports.tasks.stop_requested_at} IS NOT NULL
|
|
137
|
+
AND COALESCE(${exports.tasks.stop_requested_epoch}, 0) <> COALESCE(${exports.tasks.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(exports.tasks).set({status:"running"}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e),drizzleOrm.eq(exports.tasks.status,"pending"),drizzleOrm.isNull(exports.tasks.pid))).run().changes===1}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("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(exports.tasks).set({status:"failed",error:n,completed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e),drizzleOrm.eq(exports.tasks.status,"pending"))).run().changes>0}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("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(d=>{let c=d.select({metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e),drizzleOrm.eq(exports.tasks.status,"pending"))).limit(1).get();if(!c)return;let u=Ti(he(c.metadata),n),f={...u.metadata,stopMethod:"cooperative",stopRequest:Io(o,r)};i=d.update(exports.tasks).set({status:"stopped",error:u.error,completed_at:r,metadata:JSON.stringify(f)}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e),drizzleOrm.eq(exports.tasks.status,"pending"))).run().changes===1;},{behavior:"immediate"}),i}catch(i){throw i instanceof exports.RepositoryError?i:new exports.RepositoryError("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(exports.taskRowColumns).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.project_id,e)).orderBy(drizzleOrm.desc(exports.tasks.started_at)).all().map(at)}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("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:exports.tasks.status,run_epoch:exports.tasks.run_epoch,stop_requested_at:exports.tasks.stop_requested_at,stop_requested_epoch:exports.tasks.stop_requested_epoch,started_at:exports.tasks.started_at,duration_ms:exports.tasks.duration_ms,result:exports.tasks.result,exit_code:exports.tasks.exit_code,error:exports.tasks.error,metadata:exports.tasks.metadata,model:exports.tasks.model,input_tokens:exports.tasks.input_tokens,output_tokens:exports.tasks.output_tokens,cached_input_tokens:exports.tasks.cached_input_tokens,cost_usd:exports.tasks.cost_usd}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e.id)).limit(1).get();if(!i)return;let d=X(i.run_epoch),c=X(e.runEpoch),u=i.status==="running"&&d===c,f=i.stop_requested_at!==null&&X(i.stop_requested_epoch)===d,l=u&&f,g=i.status==="stopped"&&d===c&&f,_=he(i.metadata),m=Ln(_[kr])?_[kr]:{},k=String(c),T=Q_(i),E=T&&d===c&&!Mn(i)&&!Object.prototype.hasOwnProperty.call(m,k),S=T&&d===c&&!Object.prototype.hasOwnProperty.call(m,k),D=d>0||c>0||e.runEpoch!==void 0&&e.runEpoch!==null||d!==c,y={},b;if(i.status!=="running"&&(r=i.status,o=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),D&&(i.status==="running"||S)){b=he(i.metadata);let O=Ln(b[mi])?{...b[mi]}:{};O[String(c)]=au(e),b[mi]=O;let ne=rh(O),se=ne.inputTokens!==0||ne.outputTokens!==0||ne.cachedInputTokens!==0||ne.costUsd!==0;se&&_[dt]==="unavailable"?b[dt]="recorded":i.status!=="running"&&!se&&_[dt]===void 0&&(b[dt]="unavailable"),y.metadata=JSON.stringify(b),y.input_tokens=ne.inputTokens,y.output_tokens=ne.outputTokens,y.cached_input_tokens=ne.cachedInputTokens,y.cost_usd=ne.costUsd;}else if(u||E)if(u)y.input_tokens=be(e.inputTokens??0),y.output_tokens=be(e.outputTokens??0),y.cached_input_tokens=be(e.cachedInputTokens??0),y.cost_usd=be(e.costUsd??0);else {let O=au(e),ne=O.inputTokens!==0||O.outputTokens!==0||O.cachedInputTokens!==0||O.costUsd!==0;ne&&(y.input_tokens=O.inputTokens,y.output_tokens=O.outputTokens,y.cached_input_tokens=O.cachedInputTokens,y.cost_usd=O.costUsd),b={..._};let se=Ln(_[kr])?{..._[kr]}:{};se[k]={at:e.completedAt},b[kr]=se,b[dt]===void 0?b[dt]=ne?"recorded":"unavailable":ne&&b[dt]==="unavailable"&&(b[dt]="recorded"),y.metadata=JSON.stringify(b);}if((u||E)&&e.model!==void 0&&e.model!==null&&(!E||i.model===null)&&(y.model=e.model),l){b??=he(i.metadata);let O=Ti(b,e.error);b={...O.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:ci(i.stop_requested_at,e.completedAt)},y.status="stopped",y.result=e.result??i.result,y.error=O.error,y.completed_at=e.completedAt,y.duration_ms=i.duration_ms??e.durationMs??Ao(i.started_at,e.completedAt,void 0),y.exit_code=e.exitCode??i.exit_code,y.metadata=JSON.stringify(b);}else if(u)e.partialResultRecovered===!0&&(b??=he(i.metadata),b.partialResultRecovered=!0,y.metadata=JSON.stringify(b)),y.status=e.status,y.result=e.result??null,y.error=e.error??null,y.completed_at=e.completedAt,y.duration_ms=d>0?Ao(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,y.exit_code=e.exitCode??null;else if(g){let O=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(y.result=e.result,O=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(y.exit_code=e.exitCode),e.partialResultRecovered===!0&&(b??=he(i.metadata),b.partialResultRecovered=!0,y.metadata=JSON.stringify(b)),O&&(r=void 0,o=void 0);}Object.keys(y).length>0&&s.update(exports.tasks).set(y).where(drizzleOrm.eq(exports.tasks.id,e.id)).run();},{behavior:"immediate"});}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("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
|
|
138
|
+
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e.id),drizzleOrm.eq(exports.tasks.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:exports.tasks.metadata}).from(exports.tasks).where(r).limit(1).get(),i=he(s?.metadata??null);i.terminalReason=e.terminalReason,o.metadata=JSON.stringify(i);}n.db.update(exports.tasks).set(o).where(r).run();}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("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(exports.taskRowColumns).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.status,"running")).orderBy(drizzleOrm.desc(exports.tasks.started_at)).all().map(at)}catch(n){throw new exports.RepositoryError("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(exports.taskRowColumns).from(exports.tasks).where(drizzleOrm.inArray(exports.tasks.status,["pending","running"])).orderBy(drizzleOrm.desc(exports.tasks.started_at)).all().map(at)}catch(n){throw new exports.RepositoryError("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(exports.taskRowColumns).from(exports.tasks).orderBy(drizzleOrm.desc(exports.tasks.started_at)).limit(100).all().map(at)}catch(n){throw new exports.RepositoryError("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:exports.tasks.security_key}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e)).limit(1).get()?.security_key??null}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to read task security key",r)}finally{n.close();}}recordProviderInput(e){if(!this.dbExists())return false;let n=X(e.runEpoch);if(n===0)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 d=i.select({run_epoch:exports.tasks.run_epoch}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e.id)).limit(1).get();if(!d||X(d.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 exports.RepositoryError?s:new exports.RepositoryError("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:exports.tasks.run_epoch}).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e)).limit(1).get();if(!o)return [];let s=X(o.run_epoch),i=r.db.select({run_epoch:bt.run_epoch,key_wrap_skipped:bt.key_wrap_skipped}).from(bt).where(drizzleOrm.eq(bt.task_id,e)).all(),d=new Map(i.map(u=>[u.run_epoch,u])),c=[];for(let u=1;u<=s;u++){let f=d.get(u);f?c.push({runEpoch:u,available:!0,...f.key_wrap_skipped===1?{keyWrapSkipped:!0}:{}}):c.push({runEpoch:u,available:!1,reason:n.archivedRunEpochs?.has(u)?"pruned":"absent"});}return c}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("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(drizzleOrm.and(drizzleOrm.eq(bt.task_id,e),drizzleOrm.eq(bt.run_epoch,X(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 exports.RepositoryError("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(exports.taskRowColumns).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.id,e)).limit(1).get();return r?at(r):void 0}catch(r){throw new exports.RepositoryError("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={}){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=n.db.select({id:exports.tasks.id,status:exports.tasks.status,pid:exports.tasks.pid,platform:exports.tasks.platform,run_epoch:exports.tasks.run_epoch,heartbeat_at:exports.tasks.heartbeat_at,started_at:exports.tasks.started_at,metadata:exports.tasks.metadata,model:exports.tasks.model,input_tokens:exports.tasks.input_tokens,output_tokens:exports.tasks.output_tokens,cached_input_tokens:exports.tasks.cached_input_tokens,cost_usd:exports.tasks.cost_usd}).from(exports.tasks).where(drizzleOrm.or(drizzleOrm.eq(exports.tasks.status,"running"),drizzleOrm.eq(exports.tasks.status,"pending"))).all(),o=this.clock(),s=Math.max(1,Math.trunc(e.tickIntervalMs??exports.DEFAULT_TASK_REAPER_TICK_INTERVAL_MS)),i=this.lastReaperTickAt,d=i===void 0?Number.POSITIVE_INFINITY:o-i,c=i!==void 0&&d>=0&&d<=s*2;this.lastReaperTickAt=o;let u=en(),f=gr(),l=new Date(o-uu).toISOString(),g=new Date(o).toISOString(),_=new Set,m=0,k=(T,E)=>{let S=he(vo(T.metadata,"runner_lost")),D=typeof S.provider=="string"?S.provider:void 0,y;try{y=mo({taskLogRepository:this.taskLogRepository,taskId:T.id,provider:D,model:T.model})?.usage;}catch{}let b={status:"failed",error:E,completed_at:g};y?(b.input_tokens=y.inputTokens,b.output_tokens=y.outputTokens,b.cached_input_tokens=y.cachedInputTokens,b.cost_usd=y.costUsd,T.model===null&&y.model!==null&&(b.model=y.model),S[dt]="recorded"):!Mn(T)&&S[dt]!=="recorded"&&(S[dt]="unavailable"),b.metadata=JSON.stringify(S);let O=T.run_epoch===null?drizzleOrm.isNull(exports.tasks.run_epoch):drizzleOrm.eq(exports.tasks.run_epoch,T.run_epoch),ne=T.heartbeat_at===null?drizzleOrm.isNull(exports.tasks.heartbeat_at):drizzleOrm.eq(exports.tasks.heartbeat_at,T.heartbeat_at),se=n.db.update(exports.tasks).set(b).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,T.id),drizzleOrm.eq(exports.tasks.status,"running"),O,ne)).run();return se.changes>0&&m++,se.changes>0};for(let T of r){if(T.status==="pending"){if(T.pid!==null||T.started_at>=l)continue;let y=vo(T.metadata,"launch_failed");n.db.update(exports.tasks).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:g,metadata:y}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,T.id),drizzleOrm.eq(exports.tasks.status,"pending"),drizzleOrm.isNull(exports.tasks.pid),drizzleOrm.lt(exports.tasks.started_at,l))).run().changes>0&&m++;continue}if(X_.has(T.platform??"cli"))continue;if(T.pid===null){let y=`${T.id}:${T.run_epoch??0}`;_.add(y);let b=this.pidNullObservedSince.get(y);if(b===void 0){this.pidNullObservedSince.set(y,o);continue}o-b>=yi&&k(T,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(y);continue}if(T.heartbeat_at===null){zt(T.pid)==="not_found"&&k(T,"Reaped: process not found (orphaned task)");continue}let E=Date.parse(T.heartbeat_at),S=Number.isFinite(E)?o-E:Number.POSITIVE_INFINITY;if(S<=u)continue;zt(T.pid)==="not_found"?k(T,"Reaped: process not found (orphaned task)"):S>f&&c&&k(T,"Reaped: heartbeat stale beyond hard limit (orphaned task)");}for(let T of Array.from(this.pidNullObservedSince.keys()))_.has(T)||this.pidNullObservedSince.delete(T);return m}finally{n.close();}}reapRunningWorkflowTasks(e=yi){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),o=drizzleOrm.and(drizzleOrm.eq(exports.tasks.status,"running"),drizzleOrm.eq(exports.tasks.platform,"workflow"),drizzleOrm.isNull(exports.tasks.pid),drizzleOrm.lt(exports.tasks.started_at,r),drizzleOrm.or(drizzleOrm.isNull(exports.tasks.metadata),drizzleOrm.and(drizzleOrm.notLike(exports.tasks.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(exports.tasks.metadata,'%"kind":"workflow_ui_instance"%')))),s=n.db.select({id:exports.tasks.id,metadata:exports.tasks.metadata}).from(exports.tasks).where(o).all(),i=new Date().toISOString(),d=0;for(let c of s){let u=he(c.metadata);u.terminalReason="runner_lost";let f=n.db.update(exports.tasks).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:i,metadata:JSON.stringify(u)}).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,c.id),drizzleOrm.eq(exports.tasks.status,"running"))).run();d+=f.changes??0;}return d}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let o of r){if(!Sd.existsSync(o))continue;let s=N(o);try{let i=n?drizzleOrm.eq(exports.tasks.workspace_id,n):void 0,d=i?drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e),i):drizzleOrm.eq(exports.tasks.id,e),c=s.db.select(exports.taskRowColumns).from(exports.tasks).where(d).limit(1).get()??void 0;if(!c){let u=i?drizzleOrm.and(drizzleOrm.eq(exports.tasks.thread_id,e),i):drizzleOrm.eq(exports.tasks.thread_id,e);c=s.db.select(exports.taskRowColumns).from(exports.tasks).where(u).orderBy(drizzleOrm.desc(exports.tasks.started_at)).limit(1).get()??void 0;}if(c)return at(c)}catch(i){throw new exports.RepositoryError("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(!Sd.existsSync(i))continue;let d=N(i);try{let c=n?drizzleOrm.and(drizzleOrm.eq(exports.tasks.parent_task_id,e),drizzleOrm.eq(exports.tasks.workspace_id,n)):drizzleOrm.eq(exports.tasks.parent_task_id,e),u=d.db.select(exports.taskRowColumns).from(exports.tasks).where(c).orderBy(drizzleOrm.asc(exports.tasks.started_at)).all();for(let f of u)o.has(f.id)||(o.add(f.id),s.push(at(f)));}catch(c){throw new exports.RepositoryError("DB_ERROR","Failed to find child tasks",c)}finally{d.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?drizzleOrm.sql`
|
|
12
139
|
SELECT
|
|
13
140
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
14
141
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -16,7 +143,7 @@ ${n.join(`
|
|
|
16
143
|
COALESCE(SUM(cost_usd), 0) AS cost_usd,
|
|
17
144
|
COUNT(*) AS task_count
|
|
18
145
|
FROM tasks
|
|
19
|
-
WHERE workspace_id = ${
|
|
146
|
+
WHERE workspace_id = ${e}
|
|
20
147
|
GROUP BY workspace_id
|
|
21
148
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
22
149
|
`:drizzleOrm.sql`
|
|
@@ -29,103 +156,45 @@ ${n.join(`
|
|
|
29
156
|
FROM tasks
|
|
30
157
|
GROUP BY workspace_id
|
|
31
158
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
32
|
-
`)}catch(
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
t.
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
ORDER BY (
|
|
60
|
-
COALESCE(SUM(
|
|
61
|
-
COALESCE(t.input_tokens, 0)
|
|
62
|
-
+ CASE
|
|
63
|
-
WHEN t.started_at >= ${X}
|
|
64
|
-
AND (
|
|
65
|
-
t.crewx_version IS NULL
|
|
66
|
-
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
67
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${J}) AS INTEGER) < ${Q})
|
|
68
|
-
)
|
|
69
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
70
|
-
ELSE 0
|
|
71
|
-
END
|
|
72
|
-
), 0)
|
|
73
|
-
+ COALESCE(SUM(t.output_tokens), 0)
|
|
74
|
-
) DESC
|
|
75
|
-
`:drizzleOrm.sql`
|
|
76
|
-
SELECT
|
|
77
|
-
t.agent_id,
|
|
78
|
-
t.workspace_id,
|
|
79
|
-
COUNT(*) AS total_tasks,
|
|
80
|
-
COALESCE(SUM(
|
|
81
|
-
COALESCE(t.input_tokens, 0)
|
|
82
|
-
+ CASE
|
|
83
|
-
WHEN t.started_at >= ${X}
|
|
84
|
-
AND (
|
|
85
|
-
t.crewx_version IS NULL
|
|
86
|
-
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
87
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${J}) AS INTEGER) < ${Q})
|
|
88
|
-
)
|
|
89
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
90
|
-
ELSE 0
|
|
91
|
-
END
|
|
92
|
-
), 0) AS input_tokens,
|
|
93
|
-
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
94
|
-
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
95
|
-
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
96
|
-
FROM tasks t
|
|
97
|
-
WHERE t.status IN ('completed', 'success')
|
|
98
|
-
AND t.started_at >= ${t}
|
|
99
|
-
AND t.started_at < ${e}
|
|
100
|
-
GROUP BY t.agent_id, t.workspace_id
|
|
101
|
-
ORDER BY (
|
|
102
|
-
COALESCE(SUM(
|
|
103
|
-
COALESCE(t.input_tokens, 0)
|
|
104
|
-
+ CASE
|
|
105
|
-
WHEN t.started_at >= ${X}
|
|
106
|
-
AND (
|
|
107
|
-
t.crewx_version IS NULL
|
|
108
|
-
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
109
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${J}) AS INTEGER) < ${Q})
|
|
110
|
-
)
|
|
111
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
112
|
-
ELSE 0
|
|
113
|
-
END
|
|
114
|
-
), 0)
|
|
115
|
-
+ COALESCE(SUM(t.output_tokens), 0)
|
|
116
|
-
) DESC
|
|
117
|
-
`).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 d("DB_ERROR","Failed to get agent usage",o)}finally{r.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?drizzleOrm.sql`
|
|
159
|
+
`)}catch(r){throw new exports.RepositoryError("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,d=0;for(let c of r){if(!Sd.existsSync(c))continue;let u=N(c);try{let f=drizzleOrm.eq(exports.tasks.thread_id,e),l=n?drizzleOrm.and(f,drizzleOrm.eq(exports.tasks.workspace_id,n)):f,g=u.db.select({id:exports.tasks.id,input_tokens:exports.tasks.input_tokens,output_tokens:exports.tasks.output_tokens,cost_usd:exports.tasks.cost_usd}).from(exports.tasks).where(l).all();for(let _ of g)o.has(_.id)||(o.add(_.id),s+=_.input_tokens??0,i+=_.output_tokens??0,d+=_.cost_usd??0);}catch(f){throw new exports.RepositoryError("DB_ERROR","Failed to get thread token usage",f)}finally{u.close();}}return {inputTokens:s,outputTokens:i,costUsd:d}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],d=r?.projection==="activity-log";for(let c of o){if(!Sd.existsSync(c))continue;let u=N(c);try{let f=drizzleOrm.eq(exports.tasks.thread_id,e),l=n?drizzleOrm.and(f,drizzleOrm.eq(exports.tasks.workspace_id,n)):f,g=d?u.db.select({id:exports.tasks.id,thread_id:exports.tasks.thread_id,agent_id:exports.tasks.agent_id,parent_task_id:exports.tasks.parent_task_id,started_at:exports.tasks.started_at,completed_at:exports.tasks.completed_at}).from(exports.tasks).where(l).orderBy(drizzleOrm.asc(exports.tasks.started_at)).all():u.db.select(exports.taskRowColumns).from(exports.tasks).where(l).orderBy(drizzleOrm.asc(exports.tasks.started_at)).all().map(at);for(let _ of g)s.has(_.id)||(s.add(_.id),i.push(_));}catch(f){throw new exports.RepositoryError("DB_ERROR","Failed to find tasks by thread",f)}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(!Sd.existsSync(n))continue;let r=N(n);try{e.push(...r.db.select({id:exports.tasks.id,agent_id:exports.tasks.agent_id,thread_id:exports.tasks.thread_id,workspace_id:exports.tasks.workspace_id,platform:exports.tasks.platform,status:exports.tasks.status,error:exports.tasks.error,completed_at:exports.tasks.completed_at,duration_ms:exports.tasks.duration_ms,started_at:exports.tasks.started_at,metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.platform,"workflow"),drizzleOrm.inArray(exports.tasks.status,["running","pending"]),drizzleOrm.or(drizzleOrm.like(exports.tasks.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(exports.tasks.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(drizzleOrm.desc(exports.tasks.started_at)).all().map(gi));}catch(o){throw new exports.RepositoryError("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(!Sd.existsSync(o))continue;let s=N(o);try{let i=s.db.select({id:exports.tasks.id,agent_id:exports.tasks.agent_id,thread_id:exports.tasks.thread_id,workspace_id:exports.tasks.workspace_id,platform:exports.tasks.platform,status:exports.tasks.status,error:exports.tasks.error,completed_at:exports.tasks.completed_at,duration_ms:exports.tasks.duration_ms,started_at:exports.tasks.started_at,metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.platform,"workflow"),drizzleOrm.eq(exports.tasks.workspace_id,e))).orderBy(drizzleOrm.desc(exports.tasks.started_at),drizzleOrm.desc(exports.tasks.id)).all();for(let d of i){let c=this.parseWorkflowCardMetadata(d.metadata);if(c.kind!=="workflow_card"&&c.kind!=="workflow_ui_instance"||typeof c.workflowRunId!="string")continue;let u=c.kind,f=r.get(u)??new Set;f.has(c.workflowRunId)||(f.add(c.workflowRunId),r.set(u,f),n.push(gi(d)));}}catch(i){throw new exports.RepositoryError("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(!Sd.existsSync(n))continue;let r=N(n);try{let o=r.db.select({id:exports.tasks.id,agent_id:exports.tasks.agent_id,thread_id:exports.tasks.thread_id,workspace_id:exports.tasks.workspace_id,platform:exports.tasks.platform,status:exports.tasks.status,error:exports.tasks.error,completed_at:exports.tasks.completed_at,duration_ms:exports.tasks.duration_ms,started_at:exports.tasks.started_at,metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.platform,"workflow"),drizzleOrm.eq(exports.tasks.workspace_id,e.workspaceId))).orderBy(drizzleOrm.desc(exports.tasks.started_at),drizzleOrm.desc(exports.tasks.id)).all();for(let s of o){let i=this.parseWorkflowCardMetadata(s.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return gi(s)}}catch(o){throw new exports.RepositoryError("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?drizzleOrm.eq(exports.tasks.workspace_id,n):void 0,d=(c,u)=>{if(!c)return;let f=s.get(c);if(f&&u.started_at<=f)return;let l=this.parseWorkflowCardMetadata(u.metadata);l.kind!=="workflow_card"&&l.kind!=="workflow_ui_instance"||(s.set(c,u.started_at),r.set(c,{taskId:u.id,workflowRunId:l.workflowRunId,raw:u.result??void 0}));};for(let c of this.resolveDbPaths()){if(!Sd.existsSync(c))continue;let u=N(c);try{let f=drizzleOrm.and(drizzleOrm.inArray(exports.tasks.thread_id,e),drizzleOrm.or(drizzleOrm.like(exports.tasks.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(exports.tasks.metadata,'%"kind":"workflow_ui_instance"%'))),l=u.db.select({id:exports.tasks.id,thread_id:exports.tasks.thread_id,metadata:exports.tasks.metadata,result:exports.tasks.result,started_at:exports.tasks.started_at}).from(exports.tasks).where(i?drizzleOrm.and(f,i):f).all();for(let m of l)d(m.thread_id,m);let g=drizzleOrm.and(drizzleOrm.isNull(exports.tasks.thread_id),drizzleOrm.or(drizzleOrm.like(exports.tasks.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(exports.tasks.metadata,'%"kind":"workflow_ui_instance"%'))),_=u.db.select({id:exports.tasks.id,command:exports.tasks.command,metadata:exports.tasks.metadata,result:exports.tasks.result,started_at:exports.tasks.started_at}).from(exports.tasks).where(i?drizzleOrm.and(g,i):g).all();for(let m of _){let k=this.extractThreadIdFromCommand(m.command);!k||!o.has(k)||d(k,m);}}catch(f){throw new exports.RepositoryError("DB_ERROR","Failed to batch fetch workflow cards",f)}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(drizzleOrm.eq(exports.tasks.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(drizzleOrm.inArray(exports.tasks.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(drizzleOrm.inArray(exports.tasks.status,To(s)));let i=e.q??e.search;i&&r.push(drizzleOrm.like(exports.tasks.prompt,`%${i}%`)),e.from&&r.push(drizzleOrm.gte(exports.tasks.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(exports.tasks.started_at,e.to));let d=r.length>0?drizzleOrm.and(...r):void 0,c=n.db.select({count:drizzleOrm.sql`count(*)`}).from(exports.tasks).where(d).get(),u=(e.sortDir??"DESC")==="ASC"?drizzleOrm.asc(exports.tasks.started_at):drizzleOrm.desc(exports.tasks.started_at);return {rows:n.db.select(exports.taskRowColumns).from(exports.tasks).where(d).orderBy(u).limit(e.limit).offset(e.offset).all().map(at),total:c?.count??0}}catch(r){throw new exports.RepositoryError("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=hi(drizzleOrm.sql.raw("t.model"),drizzleOrm.sql.raw("t.metadata")),i=Tr(drizzleOrm.sql.raw("t.status")),d=bo(drizzleOrm.sql.raw("t.metadata")),c=drizzleOrm.sql`
|
|
160
|
+
COALESCE(t.input_tokens, 0)
|
|
161
|
+
+ CASE
|
|
162
|
+
WHEN t.started_at >= ${Cn}
|
|
163
|
+
AND (
|
|
164
|
+
t.crewx_version IS NULL
|
|
165
|
+
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
166
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Dn}) AS INTEGER) < ${Pn})
|
|
167
|
+
)
|
|
168
|
+
THEN COALESCE(t.cached_input_tokens, 0)
|
|
169
|
+
ELSE 0
|
|
170
|
+
END
|
|
171
|
+
`,u=r?drizzleOrm.sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.workspace_id = ${r} AND t.agent_id != 'workflow'`:drizzleOrm.sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.agent_id != 'workflow'`,f=o.db.all(drizzleOrm.sql`
|
|
172
|
+
SELECT
|
|
173
|
+
t.agent_id,
|
|
174
|
+
t.workspace_id,
|
|
175
|
+
${s} AS provider,
|
|
176
|
+
COUNT(*) AS total_tasks,
|
|
177
|
+
${d} AS unavailable_task_count,
|
|
178
|
+
COALESCE(SUM(${c}), 0) AS input_tokens,
|
|
179
|
+
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
180
|
+
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
181
|
+
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
182
|
+
FROM tasks t
|
|
183
|
+
${u}
|
|
184
|
+
GROUP BY t.agent_id, t.workspace_id, ${s}
|
|
185
|
+
`),l=new Map;for(let m of f){let k=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",T={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},E=m.workspace_id??null,S=JSON.stringify([m.agent_id,E]),D=l.get(S);if(!D){l.set(S,{agentId:m.agent_id,workspaceId:E,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:[T]});continue}D.totalTasks+=m.total_tasks,D.unavailableTaskCount=(D.unavailableTaskCount??0)+m.unavailable_task_count,D.inputTokens+=m.input_tokens,D.outputTokens+=m.output_tokens,D.cachedInputTokens+=m.cached_input_tokens,D.costUsd+=m.cost_usd,D.totalTokens+=m.input_tokens+m.output_tokens;let y=D.providers.find(b=>b.provider===k);y?(y.inputTokens+=T.inputTokens,y.outputTokens+=T.outputTokens,y.cachedInputTokens+=T.cachedInputTokens,y.totalTokens+=T.totalTokens,y.costUsd+=T.costUsd,y.totalTasks+=T.totalTasks,y.unavailableTaskCount+=T.unavailableTaskCount):D.providers.push(T);}let g=[...l.values()];for(let m of g)m.providers.sort((k,T)=>k.provider===T.provider?0:k.provider==="unknown"?1:T.provider==="unknown"?-1:k.totalTokens!==T.totalTokens?T.totalTokens-k.totalTokens:k.provider<T.provider?-1:1);let _=(m,k)=>m===k?0:m<k?-1:1;return g.sort((m,k)=>{if(m.totalTokens!==k.totalTokens)return k.totalTokens-m.totalTokens;let T=_(m.agentId,k.agentId);return T!==0?T:m.workspaceId===k.workspaceId?0:m.workspaceId===null?1:k.workspaceId===null?-1:_(m.workspaceId,k.workspaceId)}),g}catch(s){throw new exports.RepositoryError("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=Tr(drizzleOrm.sql.raw("t.status")),i=bo(drizzleOrm.sql.raw("t.metadata"));return o.db.all(r?drizzleOrm.sql`
|
|
118
186
|
SELECT
|
|
119
187
|
date(t.started_at) AS date,
|
|
120
188
|
t.agent_id,
|
|
189
|
+
${i} AS unavailable_task_count,
|
|
121
190
|
COALESCE(SUM(
|
|
122
191
|
COALESCE(t.input_tokens, 0)
|
|
123
192
|
+ CASE
|
|
124
|
-
WHEN t.started_at >= ${
|
|
193
|
+
WHEN t.started_at >= ${Cn}
|
|
125
194
|
AND (
|
|
126
195
|
t.crewx_version IS NULL
|
|
127
196
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
128
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
197
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Dn}) AS INTEGER) < ${Pn})
|
|
129
198
|
)
|
|
130
199
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
131
200
|
ELSE 0
|
|
@@ -135,24 +204,26 @@ ${n.join(`
|
|
|
135
204
|
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
136
205
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
137
206
|
FROM tasks t
|
|
138
|
-
WHERE
|
|
139
|
-
AND t.started_at >= ${
|
|
140
|
-
AND t.started_at < ${
|
|
141
|
-
AND t.workspace_id = ${
|
|
207
|
+
WHERE ${s}
|
|
208
|
+
AND t.started_at >= ${e}
|
|
209
|
+
AND t.started_at < ${n}
|
|
210
|
+
AND t.workspace_id = ${r}
|
|
211
|
+
AND t.agent_id != 'workflow'
|
|
142
212
|
GROUP BY date(t.started_at), t.agent_id
|
|
143
213
|
ORDER BY date(t.started_at) ASC
|
|
144
214
|
`:drizzleOrm.sql`
|
|
145
215
|
SELECT
|
|
146
216
|
date(t.started_at) AS date,
|
|
147
217
|
t.agent_id,
|
|
218
|
+
${i} AS unavailable_task_count,
|
|
148
219
|
COALESCE(SUM(
|
|
149
220
|
COALESCE(t.input_tokens, 0)
|
|
150
221
|
+ CASE
|
|
151
|
-
WHEN t.started_at >= ${
|
|
222
|
+
WHEN t.started_at >= ${Cn}
|
|
152
223
|
AND (
|
|
153
224
|
t.crewx_version IS NULL
|
|
154
225
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
155
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
226
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Dn}) AS INTEGER) < ${Pn})
|
|
156
227
|
)
|
|
157
228
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
158
229
|
ELSE 0
|
|
@@ -162,144 +233,470 @@ ${n.join(`
|
|
|
162
233
|
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
163
234
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
164
235
|
FROM tasks t
|
|
165
|
-
WHERE
|
|
166
|
-
AND t.started_at >= ${
|
|
167
|
-
AND t.started_at < ${
|
|
236
|
+
WHERE ${s}
|
|
237
|
+
AND t.started_at >= ${e}
|
|
238
|
+
AND t.started_at < ${n}
|
|
239
|
+
AND t.agent_id != 'workflow'
|
|
168
240
|
GROUP BY date(t.started_at), t.agent_id
|
|
169
241
|
ORDER BY date(t.started_at) ASC
|
|
170
|
-
`).map(
|
|
171
|
-
|
|
172
|
-
WHEN ${s.model} LIKE 'claude-%' OR ${s.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
173
|
-
WHEN ${s.model} LIKE 'gpt-%' OR ${s.model} LIKE 'codex-%' THEN 'codex'
|
|
174
|
-
WHEN ${s.model} LIKE 'gemini-%' THEN 'gemini'
|
|
175
|
-
WHEN ${s.model} LIKE 'zai-%' OR ${s.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
176
|
-
WHEN ${s.model} LIKE 'minimax/%' THEN 'minimax'
|
|
177
|
-
WHEN ${s.model} LIKE 'qwen%' THEN 'qwen'
|
|
178
|
-
ELSE 'unknown'
|
|
179
|
-
END
|
|
180
|
-
`,i=drizzleOrm.sql`
|
|
181
|
-
COALESCE(${s.input_tokens}, 0)
|
|
242
|
+
`).map(c=>({date:c.date,agentId:c.agent_id,unavailableTaskCount:c.unavailable_task_count,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens}))}catch(s){throw new exports.RepositoryError("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(exports.taskRowColumns).from(exports.tasks).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e),drizzleOrm.eq(exports.tasks.workspace_id,n))).limit(1).get();return o?at(o):void 0}catch(o){throw new exports.RepositoryError("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:exports.tasks.id,thread_id:exports.tasks.thread_id,status:exports.tasks.status,result:exports.tasks.result,error:exports.tasks.error,started_at:exports.tasks.started_at,completed_at:exports.tasks.completed_at,metadata:exports.tasks.metadata}).from(exports.tasks).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.agent_id,e.agentId),drizzleOrm.eq(exports.tasks.workspace_id,e.workspaceId),drizzleOrm.sql`${exports.tasks.metadata} IS NOT NULL AND json_valid(${exports.tasks.metadata}) AND json_extract(${exports.tasks.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(drizzleOrm.desc(exports.tasks.started_at)).limit(1).get()??null}catch(r){throw new exports.RepositoryError("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 d=new Date().toISOString(),c=r?drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e),drizzleOrm.eq(exports.tasks.status,"running"),drizzleOrm.eq(exports.tasks.workspace_id,r)):drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,e),drizzleOrm.eq(exports.tasks.status,"running")),u=i.db.select({metadata:exports.tasks.metadata}).from(exports.tasks).where(c).limit(1).get();if(!u)return;let f={status:o,error:n,completed_at:d};if(s){let l=he(u.metadata);l.terminalReason=s,f.metadata=JSON.stringify(l);}i.db.update(exports.tasks).set(f).where(c).run();}catch(d){throw d instanceof exports.RepositoryError?d:new exports.RepositoryError("DB_ERROR","Failed to mark task failed",d)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!Sd.existsSync(i))continue;let d=N(i);try{let c=n?drizzleOrm.and(drizzleOrm.like(exports.tasks.prompt,`%${e}%`),drizzleOrm.eq(exports.tasks.workspace_id,n)):drizzleOrm.like(exports.tasks.prompt,`%${e}%`),u=d.db.select(exports.taskRowColumns).from(exports.tasks).where(c).orderBy(drizzleOrm.asc(exports.tasks.started_at)).all();for(let f of u)o.has(f.id)||(o.add(f.id),s.push(at(f)));}catch(c){throw new exports.RepositoryError("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{d.close();}}return s}getProviderUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=hi(),i=Tr(exports.tasks.status),d=bo(exports.tasks.metadata),c=drizzleOrm.sql`
|
|
243
|
+
COALESCE(${exports.tasks.input_tokens}, 0)
|
|
182
244
|
+ CASE
|
|
183
|
-
WHEN ${
|
|
245
|
+
WHEN ${exports.tasks.started_at} >= ${Cn}
|
|
184
246
|
AND (
|
|
185
|
-
${
|
|
186
|
-
OR (${
|
|
187
|
-
OR (${
|
|
247
|
+
${exports.tasks.crewx_version} IS NULL
|
|
248
|
+
OR (${exports.tasks.crewx_version} LIKE '0.8.%' AND ${exports.tasks.crewx_version} NOT LIKE '0.8.9%')
|
|
249
|
+
OR (${exports.tasks.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${exports.tasks.crewx_version}, ${Dn}) AS INTEGER) < ${Pn})
|
|
188
250
|
)
|
|
189
|
-
THEN COALESCE(${
|
|
251
|
+
THEN COALESCE(${exports.tasks.cached_input_tokens}, 0)
|
|
190
252
|
ELSE 0
|
|
191
253
|
END
|
|
192
|
-
`,
|
|
254
|
+
`,u=r?drizzleOrm.sql`WHERE ${i} AND ${exports.tasks.started_at} >= ${e} AND ${exports.tasks.started_at} < ${n} AND ${exports.tasks.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${i} AND ${exports.tasks.started_at} >= ${e} AND ${exports.tasks.started_at} < ${n}`;return o.db.all(drizzleOrm.sql`
|
|
193
255
|
SELECT
|
|
194
|
-
${
|
|
256
|
+
${s} AS provider,
|
|
195
257
|
COUNT(*) AS total_tasks,
|
|
196
|
-
|
|
197
|
-
COALESCE(SUM(${
|
|
198
|
-
COALESCE(SUM(${
|
|
199
|
-
COALESCE(SUM(${
|
|
200
|
-
COALESCE(SUM(${
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
${
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
WHEN ${s.model} LIKE 'gpt-%' OR ${s.model} LIKE 'codex-%' THEN 'codex'
|
|
210
|
-
WHEN ${s.model} LIKE 'gemini-%' THEN 'gemini'
|
|
211
|
-
WHEN ${s.model} LIKE 'zai-%' OR ${s.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
212
|
-
WHEN ${s.model} LIKE 'minimax/%' THEN 'minimax'
|
|
213
|
-
WHEN ${s.model} LIKE 'qwen%' THEN 'qwen'
|
|
214
|
-
ELSE 'unknown'
|
|
215
|
-
END
|
|
216
|
-
`,i=drizzleOrm.sql`
|
|
217
|
-
COALESCE(${s.input_tokens}, 0)
|
|
258
|
+
${d} AS unavailable_task_count,
|
|
259
|
+
COALESCE(SUM(${c}), 0) AS input_tokens,
|
|
260
|
+
COALESCE(SUM(${exports.tasks.output_tokens}), 0) AS output_tokens,
|
|
261
|
+
COALESCE(SUM(${exports.tasks.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
262
|
+
COALESCE(SUM(${exports.tasks.cost_usd}), 0) AS cost_usd,
|
|
263
|
+
COALESCE(SUM(${exports.tasks.duration_ms}), 0) AS active_duration_ms,
|
|
264
|
+
MAX(${exports.tasks.completed_at}) AS last_active_at
|
|
265
|
+
FROM ${exports.tasks}
|
|
266
|
+
${u}
|
|
267
|
+
GROUP BY ${s}
|
|
268
|
+
ORDER BY (COALESCE(SUM(${c}), 0) + COALESCE(SUM(${exports.tasks.output_tokens}), 0)) DESC
|
|
269
|
+
`).map(l=>({provider:l.provider,totalTasks:l.total_tasks,unavailableTaskCount:l.unavailable_task_count,inputTokens:l.input_tokens,outputTokens:l.output_tokens,cachedInputTokens:l.cached_input_tokens,costUsd:l.cost_usd,totalTokens:l.input_tokens+l.output_tokens,activeDurationMs:l.active_duration_ms??0,lastActiveAt:l.last_active_at??null}))}catch(s){throw new exports.RepositoryError("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=hi(),i=Tr(exports.tasks.status),d=bo(exports.tasks.metadata),c=drizzleOrm.sql`
|
|
270
|
+
COALESCE(${exports.tasks.input_tokens}, 0)
|
|
218
271
|
+ CASE
|
|
219
|
-
WHEN ${
|
|
272
|
+
WHEN ${exports.tasks.started_at} >= ${Cn}
|
|
220
273
|
AND (
|
|
221
|
-
${
|
|
222
|
-
OR (${
|
|
223
|
-
OR (${
|
|
274
|
+
${exports.tasks.crewx_version} IS NULL
|
|
275
|
+
OR (${exports.tasks.crewx_version} LIKE '0.8.%' AND ${exports.tasks.crewx_version} NOT LIKE '0.8.9%')
|
|
276
|
+
OR (${exports.tasks.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${exports.tasks.crewx_version}, ${Dn}) AS INTEGER) < ${Pn})
|
|
224
277
|
)
|
|
225
|
-
THEN COALESCE(${
|
|
278
|
+
THEN COALESCE(${exports.tasks.cached_input_tokens}, 0)
|
|
226
279
|
ELSE 0
|
|
227
280
|
END
|
|
228
|
-
`,
|
|
281
|
+
`,u=r?drizzleOrm.sql`WHERE ${i} AND ${exports.tasks.started_at} >= ${e} AND ${exports.tasks.started_at} < ${n} AND ${exports.tasks.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${i} AND ${exports.tasks.started_at} >= ${e} AND ${exports.tasks.started_at} < ${n}`,f=o.db.all(drizzleOrm.sql`
|
|
229
282
|
SELECT
|
|
230
|
-
${
|
|
231
|
-
${
|
|
283
|
+
${exports.tasks.model} AS model,
|
|
284
|
+
${s} AS provider,
|
|
232
285
|
COUNT(*) AS total_tasks,
|
|
233
|
-
|
|
234
|
-
COALESCE(SUM(${
|
|
235
|
-
COALESCE(SUM(${
|
|
236
|
-
COALESCE(SUM(${
|
|
237
|
-
COALESCE(SUM(${
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
${
|
|
241
|
-
|
|
242
|
-
|
|
286
|
+
${d} AS unavailable_task_count,
|
|
287
|
+
COALESCE(SUM(${c}), 0) AS input_tokens,
|
|
288
|
+
COALESCE(SUM(${exports.tasks.output_tokens}), 0) AS output_tokens,
|
|
289
|
+
COALESCE(SUM(${exports.tasks.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
290
|
+
COALESCE(SUM(${exports.tasks.cost_usd}), 0) AS cost_usd,
|
|
291
|
+
COALESCE(SUM(${exports.tasks.duration_ms}), 0) AS active_duration_ms,
|
|
292
|
+
MAX(${exports.tasks.completed_at}) AS last_active_at
|
|
293
|
+
FROM ${exports.tasks}
|
|
294
|
+
${u}
|
|
295
|
+
GROUP BY ${exports.tasks.model}, ${s}
|
|
296
|
+
`),l=new Map;for(let g of f){let _=Is(g.model??""),m=JSON.stringify([g.provider,_]),k=l.get(m);k?(k.totalTasks+=g.total_tasks,k.unavailableTaskCount=(k.unavailableTaskCount??0)+g.unavailable_task_count,k.inputTokens+=g.input_tokens,k.outputTokens+=g.output_tokens,k.cachedInputTokens+=g.cached_input_tokens,k.costUsd+=g.cost_usd,k.totalTokens+=g.input_tokens+g.output_tokens,k.activeDurationMs+=g.active_duration_ms??0,g.last_active_at&&(!k.lastActiveAt||g.last_active_at>k.lastActiveAt)&&(k.lastActiveAt=g.last_active_at)):l.set(m,{model:_,provider:g.provider,totalTasks:g.total_tasks,unavailableTaskCount:g.unavailable_task_count,inputTokens:g.input_tokens,outputTokens:g.output_tokens,cachedInputTokens:g.cached_input_tokens,costUsd:g.cost_usd,totalTokens:g.input_tokens+g.output_tokens,activeDurationMs:g.active_duration_ms??0,lastActiveAt:g.last_active_at??null});}return Array.from(l.values()).sort((g,_)=>_.costUsd-g.costUsd)}catch(s){throw new exports.RepositoryError("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?drizzleOrm.sql`WHERE ${exports.tasks.started_at} >= ${e} AND ${exports.tasks.started_at} < ${n} AND ${exports.tasks.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${exports.tasks.started_at} >= ${e} AND ${exports.tasks.started_at} < ${n}`;return o.db.all(drizzleOrm.sql`
|
|
297
|
+
SELECT
|
|
298
|
+
${exports.tasks.thread_id} AS thread_id,
|
|
299
|
+
${exports.tasks.agent_id} AS agent_id,
|
|
300
|
+
${exports.tasks.started_at} AS started_at,
|
|
301
|
+
${exports.tasks.status} AS status,
|
|
302
|
+
${exports.tasks.error} AS error,
|
|
303
|
+
${exports.tasks.exit_code} AS exit_code,
|
|
304
|
+
${exports.tasks.metadata} AS metadata
|
|
305
|
+
FROM ${exports.tasks}
|
|
306
|
+
${s}
|
|
307
|
+
ORDER BY ${exports.tasks.started_at} ASC
|
|
308
|
+
`).map(d=>({threadId:d.thread_id,agentId:d.agent_id,startedAt:d.started_at,status:d.status,error:d.error,exitCode:d.exit_code,terminalReason:wt({status:d.status,error:d.error,metadata:d.metadata})??null}))}catch(s){throw new exports.RepositoryError("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=drizzleOrm.sql`
|
|
309
|
+
COALESCE(${exports.tasks.input_tokens}, 0)
|
|
310
|
+
+ CASE
|
|
311
|
+
WHEN ${exports.tasks.started_at} >= ${Cn}
|
|
312
|
+
AND (
|
|
313
|
+
${exports.tasks.crewx_version} IS NULL
|
|
314
|
+
OR (${exports.tasks.crewx_version} LIKE '0.8.%' AND ${exports.tasks.crewx_version} NOT LIKE '0.8.9%')
|
|
315
|
+
OR (${exports.tasks.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${exports.tasks.crewx_version}, ${Dn}) AS INTEGER) < ${Pn})
|
|
316
|
+
)
|
|
317
|
+
THEN COALESCE(${exports.tasks.cached_input_tokens}, 0)
|
|
318
|
+
ELSE 0
|
|
319
|
+
END
|
|
320
|
+
`,i=Tr(exports.tasks.status),d=r?drizzleOrm.sql`WHERE ${i} AND ${exports.tasks.started_at} >= ${e} AND ${exports.tasks.started_at} < ${n} AND ${exports.tasks.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${i} AND ${exports.tasks.started_at} >= ${e} AND ${exports.tasks.started_at} < ${n}`,c=o.db.all(drizzleOrm.sql`
|
|
243
321
|
SELECT
|
|
244
|
-
${
|
|
245
|
-
${
|
|
246
|
-
|
|
247
|
-
${s
|
|
248
|
-
${
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
${
|
|
252
|
-
ORDER BY ${
|
|
253
|
-
|
|
254
|
-
SELECT 1 FROM tasks parent
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
322
|
+
${exports.tasks.caller_agent_id} AS caller_agent_id,
|
|
323
|
+
${exports.tasks.agent_id} AS agent_id,
|
|
324
|
+
COUNT(*) AS task_count,
|
|
325
|
+
COALESCE(SUM(${s}), 0) AS input_tokens,
|
|
326
|
+
COALESCE(SUM(${exports.tasks.output_tokens}), 0) AS output_tokens
|
|
327
|
+
FROM ${exports.tasks}
|
|
328
|
+
${d}
|
|
329
|
+
GROUP BY ${exports.tasks.caller_agent_id}, ${exports.tasks.agent_id}
|
|
330
|
+
ORDER BY task_count DESC, ${exports.tasks.caller_agent_id} ASC, ${exports.tasks.agent_id} ASC
|
|
331
|
+
LIMIT ${_i+1}
|
|
332
|
+
`),u=c.length>_i;return {edges:c.slice(0,_i).map(l=>({callerAgentId:l.caller_agent_id??null,agentId:l.agent_id,taskCount:l.task_count,totalTokens:l.input_tokens+l.output_tokens,outputTokens:l.output_tokens})),truncated:u}}catch(s){throw new exports.RepositoryError("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(drizzleOrm.eq(exports.tasks.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(drizzleOrm.inArray(exports.tasks.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(drizzleOrm.inArray(exports.tasks.status,To(e.statuses))),e.from&&r.push(drizzleOrm.gte(exports.tasks.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(exports.tasks.started_at,e.to));let o=r.length>0?drizzleOrm.and(...r):void 0,s=(e.order??"DESC")==="ASC"?drizzleOrm.asc(exports.tasks.started_at):drizzleOrm.desc(exports.tasks.started_at),i={id:exports.tasks.id,agent_id:exports.tasks.agent_id,status:exports.tasks.status,prompt:exports.tasks.prompt,started_at:exports.tasks.started_at,completed_at:exports.tasks.completed_at,thread_id:exports.tasks.thread_id,error:exports.tasks.error,metadata:exports.tasks.metadata};return (e.limit?n.db.select(i).from(exports.tasks).where(o).orderBy(s).limit(e.limit).all():n.db.select(i).from(exports.tasks).where(o).orderBy(s).all()).map(({error:c,metadata:u,...f})=>({...f,status:st({status:f.status,error:c,metadata:u}),terminalReason:wt({status:f.status,error:c,metadata:u})??null}))}catch(r){throw new exports.RepositoryError("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=[drizzleOrm.isNotNull(exports.tasks.thread_id),drizzleOrm.isNull(exports.tasks.parent_task_id),drizzleOrm.isNull(exports.tasks.caller_agent_id),drizzleOrm.or(drizzleOrm.isNull(exports.tasks.platform),drizzleOrm.ne(exports.tasks.platform,"workflow")),drizzleOrm.or(drizzleOrm.isNull(exports.tasks.metadata),drizzleOrm.and(drizzleOrm.notLike(exports.tasks.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(exports.tasks.metadata,'%"kind":"workflow_ui_instance"%'))),drizzleOrm.or(drizzleOrm.isNull(exports.tasks.metadata),drizzleOrm.notLike(exports.tasks.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(drizzleOrm.eq(exports.tasks.workspace_id,e.workspaceId)),e.from&&s.push(drizzleOrm.gte(exports.tasks.started_at,e.from)),e.to&&s.push(drizzleOrm.lt(exports.tasks.started_at,e.to));let i=n.db.select({id:exports.tasks.id,agent_id:exports.tasks.agent_id,status:exports.tasks.status,prompt:exports.tasks.prompt,started_at:exports.tasks.started_at,completed_at:exports.tasks.completed_at,thread_id:exports.tasks.thread_id}).from(exports.tasks).where(drizzleOrm.and(...s)).orderBy(drizzleOrm.asc(exports.tasks.started_at),drizzleOrm.asc(exports.tasks.id)).all(),d=new Map;for(let u of i){if(!u.thread_id)continue;let f={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},l=d.get(u.thread_id);l?l.push(f):d.set(u.thread_id,[f]);}let c=[];for(let[u,f]of d){let l=f.filter(g=>g.agentId===e.targetAgentId).length;l<2||c.push({threadId:u,targetAgentTurnCount:l,turns:f});}return c.sort((u,f)=>{let l=u.turns[u.turns.length-1].startedAt,g=f.turns[f.turns.length-1].startedAt;return l<g?1:l>g?-1:0}),c.slice(0,r).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}},exports.TASK_RATINGS=["up","down"],exports.RATED_TASK_EXCERPT_MAX_CHARS=1e3,exports.RATED_TASK_LIST_MAX_LIMIT=200,oh=64,exports.TaskRatingError=class extends exports.RepositoryError{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;}},sh=new Set(exports.TASK_TERMINAL_STORED_STATUSES);});h();re();ie();h();re();ue();_e();ie();fe();ps();var ee=class extends exports.RepositoryError{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},id="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function gf(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=id[n%id.length];return e.slice(0,12)}function gs(){return `c_${gf()}`}function _f(t){return typeof t=="string"&&exports.COMMON_CODE_GROUPS.includes(t)}function hf(t){return typeof t=="string"&&exports.COMMON_CODE_COLORS.includes(t)}function fn(t){if(!_f(t))throw new ee("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function ad(t){if(!hf(t))throw new ee("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function dd(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new ee("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function gn(t){if(typeof t!="string"||t.trim().length===0)throw new ee("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Qr(t){if(typeof t!="string"||t.trim().length===0)throw new ee("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function Dt(t,e){return drizzleOrm.and(drizzleOrm.eq(C.code_group,t),drizzleOrm.or(drizzleOrm.isNull(C.workspace_id),drizzleOrm.eq(C.workspace_id,e)))}var _s=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");e&&Sd.mkdirSync(Ae.dirname(n),{recursive:true});let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(fn(e),gn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(C).where(drizzleOrm.and(Dt(e,n),drizzleOrm.eq(C.is_archived,0))).orderBy(drizzleOrm.asc(C.sort_order),drizzleOrm.asc(C.code)).all()}catch(o){throw new exports.RepositoryError("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(fn(e),gn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(C).where(Dt(e,n)).orderBy(drizzleOrm.asc(C.sort_order),drizzleOrm.asc(C.code)).all()}catch(o){throw new exports.RepositoryError("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(fn(n),gn(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new ee("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)Qr(o);if(new Set(e.codes).size!==e.codes.length)throw new ee("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new ee("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(C).where(Dt(n,e.workspaceId)).all(),i=s.filter(_=>_.is_archived===0),d=new Set(s.map(_=>_.code)),c=new Set(i.map(_=>_.code)),u=e.codes.find(_=>!d.has(_));if(u)throw new ee("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${u}`);if(e.codes.length!==i.length||e.codes.some(_=>!c.has(_)))throw new ee("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let f=new Map(i.map(_=>[_.code,_])),l=e.codes.map(_=>{let m=f.get(_);if(!m)throw new ee("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${_}`);return m}),g;for(let[_,m]of l.entries())m.sort_order!==_&&(g??=new Date().toISOString(),o.update(C).set({sort_order:_,updated_at:g}).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,n),drizzleOrm.eq(C.code,m.code))).run());return o.select().from(C).where(Dt(n,e.workspaceId)).orderBy(drizzleOrm.asc(C.sort_order),drizzleOrm.asc(C.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(fn(e),Qr(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).limit(1).get()??null}catch(o){throw new exports.RepositoryError("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){gn(e.workspaceId);let n=dd(e.name);ad(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:C.code}).from(C).where(drizzleOrm.and(Dt("THREAD_STATE",e.workspaceId),drizzleOrm.eq(C.is_archived,0),drizzleOrm.eq(C.code_name,n))).limit(1).get())throw new ee("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:drizzleOrm.sql`max(${C.sort_order})`}).from(C).where(Dt("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),c=gs();for(;o.select({code:C.code}).from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,"THREAD_STATE"),drizzleOrm.eq(C.code,c))).limit(1).get();)c=gs();o.insert(C).values({code_group:"THREAD_STATE",code:c,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:d,updated_at:d}).run();let u=o.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,"THREAD_STATE"),drizzleOrm.eq(C.code,c))).limit(1).get();if(!u)throw new exports.RepositoryError("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(fn(e.group),Qr(e.code),gn(e.workspaceId),e.name===void 0&&e.color===void 0)throw new ee("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:dd(e.name);e.color!==void 0&&ad(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e.group),drizzleOrm.eq(C.code,e.code))).limit(1).get();if(!s)throw new ee("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 ee("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let c=drizzleOrm.and(Dt(e.group,e.workspaceId),drizzleOrm.eq(C.is_archived,0));if(o.select({code:C.code}).from(C).where(drizzleOrm.and(c,drizzleOrm.eq(C.code_name,n),drizzleOrm.sql`${C.code} <> ${e.code}`)).limit(1).get())throw new ee("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(C).set(i).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e.group),drizzleOrm.eq(C.code,e.code))).run();let d=o.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e.group),drizzleOrm.eq(C.code,e.code))).limit(1).get();if(!d)throw new exports.RepositoryError("DB_ERROR","Updated common code could not be read back");return d},{behavior:"immediate"})}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(fn(e),Qr(n),gn(r),typeof o!="boolean")throw new ee("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let d=i.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).limit(1).get();if(!d)throw new ee("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(d.is_builtin===1)throw new ee("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(d,r),!o&&d.code_name!==null&&i.select({code:C.code}).from(C).where(drizzleOrm.and(Dt(e,r),drizzleOrm.eq(C.is_archived,0),drizzleOrm.eq(C.code_name,d.code_name),drizzleOrm.ne(C.code,n))).limit(1).get())throw new ee("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${d.code_name}`);i.update(C).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).run();let c=i.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).limit(1).get();if(!c)throw new exports.RepositoryError("DB_ERROR","Archived common code could not be read back");return c},{behavior:"immediate"})}catch(i){throw i instanceof exports.RepositoryError?i:new exports.RepositoryError("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 ee("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};h();re();ue();_e();ie();fe();h();function hs(t){let e=Ae__namespace.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 cd(t){let e=hs(t);return crypto.createHash("sha256").update(e).digest("hex")}function Zr(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Ts=class extends exports.BaseSqliteRepository{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?Ae.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{cn(r.db);}catch(o){throw r.close(),o}return r}resolveSlug(e,n,r){let o=Zr(Ae.basename(r)),i=`${Zr(Ae.basename(Ae.dirname(r)))}-${o}`,d=[o,i];try{let c=u=>e.select({id:P.id}).from(P).where(drizzleOrm.and(drizzleOrm.eq(P.slug,u),drizzleOrm.ne(P.id,n))).limit(1).all().length>0;for(let u of d)if(!c(u))return u;for(let u=2;u<1e3;u+=1){let f=`${i}-${u}`;if(!c(f))return f}}catch{}return o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let n=e.db.select({id:P.id,slug:P.slug}).from(P).all(),r=0;for(let o of n)if(o.slug.includes("/")){let s=Zr(o.slug.replace(/\//g,"-"));e.db.update(P).set({slug:s,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(P.id,o.id)).run(),r+=1;}return {updated:r,checked:n.length}}catch(n){throw new exports.RepositoryError("DB_ERROR","Failed to normalize legacy slugs",n)}finally{e.close();}}ensureRow(e,n){let{id:r,slug:o,name:s,workspacePath:i}=n,d=new Date().toISOString();e.insert(P).values({id:r,slug:o,name:s,workspace_path:i,is_active:1,created_at:d,updated_at:d}).onConflictDoNothing().run(),e.update(P).set({workspace_path:i,updated_at:d}).where(drizzleOrm.and(drizzleOrm.eq(P.id,r),drizzleOrm.isNull(P.workspace_path))).run();}registerWorkspace(e){let n=hs(e),r=this.openHandle(true);try{let o=cd(n),s=Ae.basename(n),i=this.resolveSlug(r.db,o,n);return this.ensureRow(r.db,{id:o,slug:i,name:s,workspacePath:n}),{id:o,slug:i}}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to register workspace",o)}finally{r.close();}}listProjects(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=e.isActive!==void 0?drizzleOrm.eq(P.is_active,e.isActive?1:0):void 0,o=n.db.select({count:drizzleOrm.sql`count(*)`}).from(P).where(r).get();return {rows:n.db.select().from(P).where(r).orderBy(drizzleOrm.desc(P.updated_at)).limit(e.limit).offset(e.offset).all(),total:o?.count??0}}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to list projects",r)}finally{n.close();}}findById(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(P).where(drizzleOrm.eq(P.id,e)).limit(1).get()??void 0}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to find workspace",r)}finally{n.close();}}toggleStar(e){let n=this.openHandle(true);try{let r=n.db.select({starred:P.starred}).from(P).where(drizzleOrm.eq(P.id,e)).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(P).set({starred:o}).where(drizzleOrm.eq(P.id,e)).run(),{starred:!!o}}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to toggle workspace star",r)}finally{n.close();}}findAgentsByProject(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${e} AND agent_id IS NOT NULL ORDER BY agent_id`).map(o=>o.agent_id)}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to find agents by project",r)}finally{n.close();}}findThreadsByProject(e,n){if(!this.dbExists())return {rows:[],total:0};let r=this.openHandle(false);try{let o=r.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);return {rows:r.db.all(drizzleOrm.sql`SELECT t.*,
|
|
333
|
+
(SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
|
|
334
|
+
FROM threads t
|
|
335
|
+
WHERE t.workspace_id = ${e}
|
|
336
|
+
ORDER BY t.updated_at DESC
|
|
337
|
+
LIMIT ${n.limit} OFFSET ${n.offset}`),total:o?.count??0}}catch(o){throw new exports.RepositoryError("DB_ERROR","Failed to find threads by project",o)}finally{r.close();}}findBySlug(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(P).where(drizzleOrm.eq(P.slug,e)).limit(1).get()??void 0}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to find workspace by slug",r)}finally{n.close();}}slugExists(e,n){if(!this.dbExists())return false;let r=this.openHandle(false);try{let o=n?drizzleOrm.and(drizzleOrm.eq(P.slug,e),drizzleOrm.ne(P.id,n)):drizzleOrm.eq(P.slug,e);return !!r.db.select({id:P.id}).from(P).where(o).limit(1).get()}catch(o){throw new exports.RepositoryError("DB_ERROR","Failed to check slug",o)}finally{r.close();}}insert(e,n,r,o){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(P).values({id:e,slug:n,name:r,workspace_path:o,is_active:1,created_at:i,updated_at:i}).run();let d=s.db.select().from(P).where(drizzleOrm.eq(P.id,e)).limit(1).get();if(!d)throw new exports.RepositoryError("DB_ERROR","Insert did not return a row");return d}catch(i){throw i instanceof exports.RepositoryError?i:new exports.RepositoryError("DB_ERROR","Failed to insert workspace",i)}finally{s.close();}}update(e,n,r){let o=this.openHandle(true);try{o.runRaw(`UPDATE workspaces SET ${n.join(", ")} WHERE id = ?`,r);let s=o.db.select().from(P).where(drizzleOrm.eq(P.id,e)).limit(1).get();if(!s)throw new exports.RepositoryError("NOT_FOUND",`Workspace ${e} not found`);return s}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("DB_ERROR","Failed to update workspace",s)}finally{o.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let e=this.openHandle(true);try{let n=e.db.select({id:P.id,workspace_path:P.workspace_path}).from(P).where(drizzleOrm.and(drizzleOrm.eq(P.is_active,1),drizzleOrm.isNotNull(P.workspace_path))).all(),r=0;for(let o of n){let s=o.workspace_path;Sd.existsSync(Ae.join(s,"crewx.yaml"))||Sd.existsSync(Ae.join(s,"crewx.yml"))||(e.db.update(P).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(P.id,o.id)).run(),r+=1);}return {softDeleted:r,checked:n.length}}catch(n){throw new exports.RepositoryError("DB_ERROR","Failed to cleanup orphan workspaces",n)}finally{e.close();}}delete(e){let n=this.openHandle(true);try{n.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${e}`),n.db.delete(P).where(drizzleOrm.eq(P.id,e)).run();}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to delete workspace",r)}finally{n.close();}}};ws();h();re();ue();_e();ie();h();var ys="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Af(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=ys[o%62]);}for(;n.length<t;)n+=ys[crypto.randomBytes(1)[0]%62];return n}function je(t){return `${t}_${Af(8)}`}function gd(t,e){let{createHash:n}=St("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+=ys[i%62];return `${t}_${s}`}fe();var Es=["outcome_plan","contract_check","feature_link","use_verify","result_review"],Pf=new Set(Es),wd=Object.freeze(Es.map(t=>({key:t,labelOverride:null}))),Lf=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),Mf=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),Hf=new Set(["pending","verifying","passed","failed"]),$f=new Set(["user","project_manager","system"]),Uf=new Set(["task","wi","url"]),Bf=/^\d{4}-\d{2}-\d{2}$/;function Z(t){throw new exports.RepositoryError("VALIDATION",t)}function Xe(t){throw new exports.RepositoryError("NOT_FOUND",t)}function me(t,e){(typeof t!="string"||t.trim().length===0)&&Z(`${e} is required`);}function qf(t){if(t==null)return;Bf.test(t)||Z("dueDate must use YYYY-MM-DD");let e=new Date(`${t}T00:00:00.000Z`);(Number.isNaN(e.getTime())||e.toISOString().slice(0,10)!==t)&&Z("dueDate must be a valid calendar date");}function yd(t){let e=t??wd;(!Array.isArray(e)||e.length===0)&&Z("stages must contain at least one stage");let n=new Set;return e.map(r=>{(!r||typeof r!="object"||Array.isArray(r))&&Z("stage must be an object");let o=r;return me(o.key,"stage.key"),o.labelOverride!==null&&typeof o.labelOverride!="string"&&Z("stage.labelOverride must be a string or null"),o.labelOverride!==null&&me(o.labelOverride,"stage.labelOverride"),typeof o.key!="string"&&Z("stage.key is required"),!Pf.has(o.key)&&o.labelOverride===null&&Z(`custom stage requires a labelOverride: ${o.key}`),n.has(o.key)&&Z(`duplicate stage key: ${o.key}`),n.add(o.key),{key:o.key,labelOverride:o.labelOverride}})}function Ff(t){Array.isArray(t)||Z("criteria must be an array");for(let e of t)me(e,"criterion.statement");}function hn(t={}){let e=t.actorType??"system";$f.has(e)||Z(`invalid actorType: ${String(e)}`);let n=t.actorId??null;return (e==="user"||e==="project_manager")&&(!n||n.trim().length===0)&&Z(`actorId is required for ${e}`),{actorType:e,actorId:n}}function Rd(t,e){let n=t??{};if((n===null||typeof n!="object"||Array.isArray(n))&&Z("event payload must be a JSON object"),e==="accepted")for(let r of ["remainingRisks","nextPlan","lessons","evidenceRefs"])(!Object.prototype.hasOwnProperty.call(n,r)||n[r]===void 0)&&Z(`accepted payload requires ${r}`);try{return JSON.stringify(n)}catch(r){throw new exports.RepositoryError("VALIDATION","event payload must be JSON serializable",r)}}function jf(t){return Array.isArray(t)||Z("evidence must be an array"),t.map(e=>((!e||typeof e!="object")&&Z("evidence item must be an object"),Uf.has(e.kind)||Z(`invalid evidence kind: ${String(e.kind)}`),me(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&Z("evidence.label must be a string"),e.label===void 0?{kind:e.kind,ref:e.ref}:{kind:e.kind,ref:e.ref,label:e.label}))}function Td(t){let e;try{e=JSON.parse(t);}catch(n){throw new exports.RepositoryError("DB_ERROR","Project stages JSON is invalid",n)}try{if(!Array.isArray(e))throw new exports.RepositoryError("DB_ERROR","Project stages JSON is invalid");return yd(e)}catch(n){throw new exports.RepositoryError("DB_ERROR","Project stages JSON is invalid",n)}}function Ed(t){return me(t.projectId,"projectId"),me(t.title,"title"),Lf.has(t.type)||Z(`invalid project event type: ${String(t.type)}`),{...hn(t),payloadJson:Rd(t.payload,t.type)}}function Wt(t,e,n){let r=Ed(e);t.select({id:G.id}).from(G).where(drizzleOrm.eq(G.id,e.projectId)).get()||Xe(`Project ${e.projectId} not found`);let s=t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${et.seq}), 0)`}).from(et).where(drizzleOrm.eq(et.project_id,e.projectId)).get()?.maxSeq??0,i=je("pje");t.insert(et).values({id:i,project_id:e.projectId,seq:s+1,actor_type:r.actorType,actor_id:r.actorId,type:e.type,title:e.title,summary:e.summary??null,payload_json:r.payloadJson,created_at:n}).run();let d=t.select().from(et).where(drizzleOrm.eq(et.id,i)).get();if(!d)throw new exports.RepositoryError("DB_ERROR","Event insert did not return a row");return d}var Rs=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}getDetailFromHandle(e,n){let r=e.db.select().from(G).where(drizzleOrm.eq(G.id,n)).get();if(!r)return;let o=e.db.select().from(qe).where(drizzleOrm.eq(qe.project_id,n)).orderBy(drizzleOrm.asc(qe.position)).all();return {...r,stages:Td(r.stages_json),criteria:o}}getDetailOrThrow(e){let n=this.getProject(e);return n||Xe(`Project ${e} not found`),n}createProject(e){me(e.workspaceId,"workspaceId"),me(e.name,"name"),me(e.outcome,"outcome"),qf(e.dueDate);let n=yd(e.stages);Ff(e.criteria);let r=je("prj"),o=new Date().toISOString(),s=this.openHandle(true);try{s.db.transaction(i=>{i.insert(G).values({id:r,workspace_id:e.workspaceId,name:e.name,outcome:e.outcome,due_date:e.dueDate??null,scene:"planning",stages_json:JSON.stringify(n),stage_index:1,created_at:o,updated_at:o,accepted_at:null,archived_at:null}).run(),e.criteria.forEach((d,c)=>{i.insert(qe).values({id:je("pjc"),project_id:r,position:c+1,statement:d,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:o,updated_at:o}).run();}),Wt(i,{projectId:r,actorType:"system",type:"created",title:"Project created",payload:{}},o);});}catch(i){throw i instanceof exports.RepositoryError?i:new exports.RepositoryError("DB_ERROR","Failed to create project",i)}finally{s.close();}return this.getDetailOrThrow(r)}getProject(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return this.getDetailFromHandle(n,e)}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to get project",r)}finally{n.close();}}listProjectsByWorkspace(e,n={}){if(me(e,"workspaceId"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=n.includeArchived?drizzleOrm.eq(G.workspace_id,e):drizzleOrm.and(drizzleOrm.eq(G.workspace_id,e),drizzleOrm.isNull(G.archived_at));return r.db.select({id:G.id}).from(G).where(o).orderBy(drizzleOrm.desc(G.updated_at),drizzleOrm.desc(G.created_at)).all().map(i=>this.getDetailFromHandle(r,i.id)).filter(i=>i!==void 0)}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to list projects",o)}finally{r.close();}}archiveProject(e){me(e,"projectId");let n=this.openHandle(true);try{n.db.update(G).set({archived_at:new Date().toISOString()}).where(drizzleOrm.eq(G.id,e)).run().changes===0&&Xe(`Project ${e} not found`);}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to archive project",r)}finally{n.close();}return this.getDetailOrThrow(e)}setScene(e,n,r={}){me(e,"projectId"),Mf.has(n)||Z(`invalid project scene: ${String(n)}`);let o=hn(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let c=d.select().from(G).where(drizzleOrm.eq(G.id,e)).get();c||Xe(`Project ${e} not found`),d.update(G).set({scene:n,updated_at:s}).where(drizzleOrm.eq(G.id,e)).run(),Wt(d,{projectId:e,...o,type:"scene_changed",title:"Project scene changed",payload:{before:c.scene,after:n}},s);});}catch(d){throw d instanceof exports.RepositoryError?d:new exports.RepositoryError("DB_ERROR","Failed to set project scene",d)}finally{i.close();}return this.getDetailOrThrow(e)}setStageIndex(e,n,r={}){me(e,"projectId"),Number.isInteger(n)||Z("stage index must be an integer");let o=hn(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let c=d.select().from(G).where(drizzleOrm.eq(G.id,e)).get();c||Xe(`Project ${e} not found`);let u=Td(c.stages_json);(n<1||n>u.length)&&Z("stage index is outside the project stages"),d.update(G).set({stage_index:n,updated_at:s}).where(drizzleOrm.eq(G.id,e)).run(),Wt(d,{projectId:e,...o,type:"stage_advanced",title:"Project stage advanced",payload:{before:c.stage_index,after:n}},s);});}catch(d){throw d instanceof exports.RepositoryError?d:new exports.RepositoryError("DB_ERROR","Failed to set project stage",d)}finally{i.close();}return this.getDetailOrThrow(e)}setCriterionVerify(e,n,r,o={}){let s=typeof e=="string"?{projectId:typeof r=="string"?e:void 0,criterionId:typeof r=="string"?n:e,verifyStatus:typeof r=="string"?r:n,...typeof r=="string"?o:r}:e,i=s.verifyStatus??s.status;(!i||!Hf.has(i))&&Z(`invalid criterion status: ${String(i)}`),me(s.criterionId,"criterionId");let d=hn(s),c=new Date().toISOString(),u=this.openHandle(true),f;try{u.db.transaction(g=>{let _=g.select().from(qe).where(drizzleOrm.eq(qe.id,s.criterionId)).get();_||Xe(`Criterion ${s.criterionId} not found`),f=_.project_id,s.projectId&&s.projectId!==_.project_id&&Xe(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(qe).set({verify_status:i,verified_at:i==="passed"?c:null,updated_at:c}).where(drizzleOrm.eq(qe.id,s.criterionId)).run(),Wt(g,{projectId:_.project_id,...d,type:"criterion_verified",title:"Criterion verification updated",payload:{criterionId:s.criterionId,status:i}},c);});}catch(g){throw g instanceof exports.RepositoryError?g:new exports.RepositoryError("DB_ERROR","Failed to set criterion verification",g)}finally{u.close();}let l=f?this.getProject(f)?.criteria.find(g=>g.id===s.criterionId):void 0;return l||Xe(`Criterion ${s.criterionId} not found`),l}setCriterionEvidence(e,n,r,o={}){let s=typeof e=="string"?{projectId:Array.isArray(r)?e:void 0,criterionId:Array.isArray(r)?n:e,evidence:Array.isArray(r)?r:n,...Array.isArray(r)?o:r}:e;me(s.criterionId,"criterionId");let i=jf(s.evidence),d=hn(s),c=new Date().toISOString(),u=this.openHandle(true),f;try{u.db.transaction(g=>{let _=g.select().from(qe).where(drizzleOrm.eq(qe.id,s.criterionId)).get();_||Xe(`Criterion ${s.criterionId} not found`),f=_.project_id,s.projectId&&s.projectId!==_.project_id&&Xe(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(qe).set({evidence_json:JSON.stringify(i),updated_at:c}).where(drizzleOrm.eq(qe.id,s.criterionId)).run(),Wt(g,{projectId:_.project_id,...d,type:"criterion_verified",title:"Criterion evidence updated",payload:{criterionId:s.criterionId,evidence:i}},c);});}catch(g){throw g instanceof exports.RepositoryError?g:new exports.RepositoryError("DB_ERROR","Failed to set criterion evidence",g)}finally{u.close();}let l=f?this.getProject(f)?.criteria.find(g=>g.id===s.criterionId):void 0;return l||Xe(`Criterion ${s.criterionId} not found`),l}appendEvent(e,n){let r=typeof e=="string"?{...n,projectId:e}:e;Ed(r);let o=new Date().toISOString(),s=this.openHandle(true),i;try{s.db.transaction(d=>{i=Wt(d,r,o);});}catch(d){throw d instanceof exports.RepositoryError?d:new exports.RepositoryError("DB_ERROR","Failed to append project event",d)}finally{s.close();}if(!i)throw new exports.RepositoryError("DB_ERROR","Event append did not return a row");return i}listEvents(e,n={}){if(me(e,"projectId"),n.afterSeq!==void 0&&(!Number.isInteger(n.afterSeq)||n.afterSeq<0)&&Z("afterSeq must be a non-negative integer"),n.limit!==void 0&&(!Number.isInteger(n.limit)||n.limit<1)&&Z("limit must be a positive integer"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=[drizzleOrm.eq(et.project_id,e)];n.afterSeq!==void 0&&o.push(drizzleOrm.gt(et.seq,n.afterSeq));let s=r.db.select().from(et).where(drizzleOrm.and(...o)).orderBy(drizzleOrm.asc(et.seq));return n.limit!==void 0&&(s=s.limit(n.limit)),s.all()}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to list project events",o)}finally{r.close();}}acceptProject(e,n){me(e,"projectId");let r=hn(n),o={remainingRisks:n.remainingRisks,nextPlan:n.nextPlan,lessons:n.lessons,evidenceRefs:n.evidenceRefs};Rd(o,"accepted");let s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{d.select({id:G.id}).from(G).where(drizzleOrm.eq(G.id,e)).get()||Xe(`Project ${e} not found`),d.update(G).set({scene:"accepted",accepted_at:s,updated_at:s}).where(drizzleOrm.eq(G.id,e)).run(),Wt(d,{projectId:e,...r,type:"accepted",title:"Project accepted",payload:o},s);});}catch(d){throw d instanceof exports.RepositoryError?d:new exports.RepositoryError("DB_ERROR","Failed to accept project",d)}finally{i.close();}return this.getDetailOrThrow(e)}};ue();_e();h();_e();fe();var Id=[P,exports.tasks,w,Ea,It,gt,Je,xa];function Gf(){return Ae__namespace.default.join(aa__default.default.homedir(),".crewx","crewx.db")}function Kf(t){if(!Sd__namespace.default.existsSync(t))return null;let e=Math.floor(Date.now()/1e3),n=`${t}.bak-${e}`;return Sd__namespace.default.copyFileSync(t,n),n}function Ad(t){let e=t.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(e.map(n=>n.name))}function Vf(t){return t==null||typeof t=="object"&&"queryChunks"in t?null:typeof t=="number"?String(t):typeof t=="boolean"?t?"1":"0":typeof t=="string"?`'${t.replace(/'/g,"''")}'`:String(t)}function Jf(t){let e=t.getSQLType(),n=`"${t.name}" ${e}`,r=Vf(t.default);return r!==null&&(n+=` DEFAULT ${r}`),t.notNull&&(n+=" NOT NULL"),n}function Xf(t,e){let n=e?.dbPath??Gf(),r=e?.force??false,o=e?.dryRun??false,s=o?null:Kf(n);if(r&&!o)try{t.run("DELETE FROM __drizzle_migrations");}catch{}let i=Ad(t);if(!o)try{cn(t);}catch(l){let g=l instanceof Error?`${l.message} ${l.cause?.message??""}`:"";if(!r||!g.includes("duplicate column"))throw l}let d,c;o?(d=Id.map(g=>sqliteCore.getTableConfig(g).name).filter(g=>!i.has(g)),c=i):(c=Ad(t),d=[...c].filter(l=>!i.has(l)));let u=[],f=[];for(let l of Id){let g=sqliteCore.getTableConfig(l),_=g.name;if(!c.has(_))continue;let m=t.all(`PRAGMA table_info("${_}")`),k=new Set(m.map(E=>E.name)),T=new Set(g.columns.map(E=>E.name));for(let E of g.columns)if(!k.has(E.name)){if(!o){let S=Jf(E);t.run(`ALTER TABLE "${_}" ADD COLUMN ${S}`);}u.push({table:_,column:E.name});}for(let E of m)T.has(E.name)||f.push(`${_}.${E.name} exists in DB but not in schema (untouched)`);}return {created:d,altered:u,warnings:f,backupPath:s}}fe();fe();xn();xn();pi();_r();fr();xn();h();re();h();var Tu=["success","failed","completed"],Po=10*1024*1024*1024,wu=256,fh=new Set(Tu),Ie=class extends Error{constructor(n,r,o="metadata"){super(r);this.taskId=n;this.kind=o;this.name="MigrationTaskError";}taskId;kind};function Lo(t){return t||(process.env.CREWX_DB?process.env.CREWX_DB:Ae.join(aa.homedir(),".crewx","crewx.db"))}function gh(){return St("better-sqlite3")}function yu(t,e){let n=t===":memory:";if(!n&&!Sd.existsSync(t))throw new Error(`Database not found: ${t}`);let r=new(gh())(t,{readonly:e,fileMustExist:!n,timeout:5e3});return r.pragma("foreign_keys = ON"),r.pragma("busy_timeout = 5000"),r}function Bn(t,e,n=[]){return t.prepare(e).all(...n)}function Un(t,e,n=[]){return t.prepare(e).get(...n)}function _h(t,e,n=[]){return t.prepare(e).run(...n)}function hh(t,e,n=[]){return t.prepare(e).iterate(...n)}function mh(t){return typeof t=="string"&&t.length>0?t:"<unknown>"}function Ru(t){return typeof t=="string"&&fh.has(t)}function hu(t,e){t.set(e,(t.get(e)??0)+1);}function mu(t){return Object.fromEntries([...t.entries()].sort(([e],[n])=>e.localeCompare(n)))}function kh(t){let e=new Set(Bn(t,"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('tasks', 'task_log_events')").map(i=>i.name)),n=["tasks","task_log_events"].filter(i=>!e.has(i));if(n.length>0)throw new Error(`Database schema is missing required table(s): ${n.join(", ")}`);let r=new Set(Bn(t,"PRAGMA table_info('tasks')").map(i=>i.name)),s=["id","status","logs","log_storage","last_log_seq","log_revision"].filter(i=>!r.has(i));if(s.length>0)throw new Error(`Database schema is missing required tasks column(s): ${s.join(", ")}`)}function Eu(t,e){if(e==null)return {entries:[]};if(typeof e!="string")throw new Ie(t,"Malformed task logs: tasks.logs must be JSON text or null","malformed");if(e.trim()==="")return {entries:[]};let n;try{n=JSON.parse(e);}catch(o){let s=o instanceof Error?o.message:String(o);throw new Ie(t,`Malformed JSON in tasks.logs (${s})`,"malformed")}if(!Array.isArray(n))throw new Ie(t,"Malformed task logs: expected a JSON array","malformed");let r=[];for(let[o,s]of n.entries()){if(s===null||typeof s!="object"||typeof s.timestamp!="string"||typeof s.level!="string"||typeof s.message!="string")throw new Ie(t,`Malformed task logs: entry ${o} must contain string timestamp, level, and message fields`,"malformed");let i=s;r.push({timestamp:i.timestamp,level:i.level,message:i.message});}return {entries:r}}function Oi(t,e){if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new Ie(t.id,"Invalid last_log_seq metadata","metadata");if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new Ie(t.id,"Invalid log_revision metadata","metadata");if(e==="blob"&&t.last_log_seq!==0)throw new Ie(t.id,"Blob source must have last_log_seq=0","metadata")}function Th(t){let e=Bn(t,`SELECT task_id, COUNT(*) AS event_count
|
|
338
|
+
FROM task_log_events GROUP BY task_id`);return new Map(e.map(n=>[n.task_id,n.event_count]))}function wh(t){let e=Th(t),n=new Map,r=[],o=[],s=[],i=new Map,d=new Map,c=0,u=0,f=0,l=0,g=0,_=0;for(let m of hh(t,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
339
|
+
FROM tasks ORDER BY id`)){let k=m,T=mh(k.status);if(hu(i,T),n.set(k.id,{id:k.id,status:k.status,log_storage:k.log_storage,last_log_seq:k.last_log_seq,log_revision:k.log_revision}),c+=1,k.log_storage==="events"){l+=1;try{Oi(k,"events");}catch(y){s.push(vi(y,k.id));}k.logs!==null&&s.push({taskId:k.id,reason:"Event source still has a non-null tasks.logs blob",kind:"mixed-source"});continue}if(k.log_storage!=="blob"){s.push({taskId:k.id,reason:`Unknown log_storage value: ${k.log_storage}`,kind:"invalid-source"});continue}u+=1;let E=Ru(k.status);E||(f+=1,hu(d,T)),typeof k.logs=="string"?_+=Buffer.byteLength(k.logs,"utf8"):Buffer.isBuffer(k.logs)&&(_+=k.logs.byteLength);let S=e.get(k.id)??0;S>0&&s.push({taskId:k.id,reason:`Blob source already has ${S} task_log_events row(s)`,kind:"mixed-source"});let D;try{D=Eu(k.id,k.logs),g+=D.entries.length,Oi(k,"blob");}catch(y){let b=vi(y,k.id);s.push(b),b.kind==="malformed"&&o.push(b);continue}S>0||E&&r.push(k.id);}return {taskCount:c,candidateTaskCount:u,eligibleTaskCount:r.length,eventSourceTasks:l,statusCounts:mu(i),deferredTaskCount:f,deferredStatusCounts:mu(d),entryCount:g,sourceBytes:_,candidateIds:r,malformedRows:o,failures:s,tasks:n}}function vi(t,e){return t instanceof Ie?{taskId:t.taskId,reason:t.message,kind:t.kind}:{taskId:e,reason:t instanceof Error?t.message:String(t),kind:"metadata"}}function yh(t){return Un(t,"SELECT COUNT(*) AS count FROM tasks WHERE status IN ('pending', 'running')")?.count??0}function Rh(t){return Un(t,"SELECT COUNT(*) AS count FROM tasks WHERE log_storage = 'blob'")?.count??0}function Eh(t){if(t===":memory:")return 0;let e=n=>{try{return Sd.statSync(n).size}catch{return 0}};return e(t)+e(`${t}-wal`)}function Sh(t,e){return Eh(t)+e*wu}function Su(t,e){return Number.isFinite(t)&&Number.isFinite(e)&&t>=e+Po}function ku(t){let e=Ae.dirname(Ae.resolve(t));for(;!Sd.existsSync(e);){let n=Ae.dirname(e);if(n===e)break;e=n;}return e}function bu(t,e,n){let r=[...new Set([ku(t),...n?[ku(n)]:[]])],o=[],s=Number.POSITIVE_INFINITY;for(let c of r)try{let u=Sd.statfsSync(c);s=Math.min(s,u.bavail*u.bsize);}catch(u){s=0,o.push(`Unable to inspect free space for ${c}: ${u instanceof Error?u.message:String(u)}`);}let i=Sh(t,e),d=i+Po;return {estimatedFreeSpaceBytes:i,requiredFreeSpaceBytes:d,availableFreeSpaceBytes:Number.isFinite(s)?Math.floor(s):0,minimumFreeSpaceReserveBytes:Po,freeSpaceGatePassed:Su(Number.isFinite(s)?Math.floor(s):0,i),warnings:o}}function Iu(t){return new Set(t.map(e=>e.taskId)).size}function wr(t){try{let e=t.pragma("wal_checkpoint(TRUNCATE)"),n=Array.isArray(e)?e[0]:e,r=n!==null&&typeof n=="object"&&"busy"in n?Number(n.busy):0;return r>0?`WAL checkpoint(TRUNCATE) busy (${r}); continuing without failing migration`:void 0}catch(e){return `WAL checkpoint(TRUNCATE) warning; continuing without failing migration: ${e instanceof Error?e.message:String(e)}`}}function Co(t,e,n,r,o=bu(e,n.entryCount)){let s=r.failures??n.failures,i=r.malformedRows??n.malformedRows,{ok:d,...c}=r;return {mode:t,ok:d,dbPath:e,activeTaskCount:r.activeTaskCount??0,taskCount:n.taskCount,candidateTaskCount:n.candidateTaskCount,eligibleTaskCount:n.eligibleTaskCount,statusCounts:n.statusCounts,deferredTaskCount:n.deferredTaskCount,deferredStatusCounts:n.deferredStatusCounts,entryCount:n.entryCount,sourceBytes:n.sourceBytes,estimatedFreeSpaceBytes:o.estimatedFreeSpaceBytes,requiredFreeSpaceBytes:o.requiredFreeSpaceBytes,availableFreeSpaceBytes:o.availableFreeSpaceBytes,minimumFreeSpaceReserveBytes:o.minimumFreeSpaceReserveBytes,freeSpaceGatePassed:o.freeSpaceGatePassed,migratedTasks:r.migratedTasks??0,migratedEntries:r.migratedEntries??0,skippedTasks:r.skippedTasks??n.eventSourceTasks,failedTasks:r.failedTasks??Iu(s),malformedRows:i,failures:s,logicalSourceBytesRemoved:r.logicalSourceBytesRemoved??0,warnings:r.warnings??o.warnings,remainingTaskCount:r.remainingTaskCount??n.candidateTaskCount,...c}}function bh(t,e){return t.length!==e.length?false:t.every((n,r)=>{let o=e[r];return n.seq===r+1&&n.timestamp===o.timestamp&&n.level===o.level&&n.message===o.message})}function Ih(t,e){return t.transaction(()=>{let r=Un(t,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
340
|
+
FROM tasks WHERE id = ?`,[e]);if(!r)throw new Ie(e,"Task disappeared before migration","metadata");if(r.log_storage==="events")return {status:"skipped",entryCount:0,sourceBytes:0};if(r.log_storage!=="blob")throw new Ie(e,`Unknown log_storage value: ${r.log_storage}`,"invalid-source");if(!Ru(r.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=r.logs,s=Eu(e,o);Oi(r,"blob");let i=Un(t,"SELECT COUNT(*) AS count FROM task_log_events WHERE task_id = ?",[e])?.count??0;if(i!==0)throw new Ie(e,`Blob source already has ${i} task_log_events row(s)`,"mixed-source");let d=t.prepare(`INSERT INTO task_log_events (task_id, seq, timestamp, level, message)
|
|
341
|
+
VALUES (?, ?, ?, ?, ?)`);for(let[l,g]of s.entries.entries())d.run(e,l+1,g.timestamp,g.level,g.message);let c=Bn(t,`SELECT seq, timestamp, level, message
|
|
342
|
+
FROM task_log_events WHERE task_id = ? ORDER BY seq`,[e]);if(!bh(c,s.entries))throw new Ie(e,"Event parity check failed before source clear","metadata");if(_h(t,`UPDATE tasks
|
|
343
|
+
SET log_storage = 'events', last_log_seq = ?, log_revision = log_revision + 1, logs = NULL
|
|
344
|
+
WHERE id = ? AND log_storage = 'blob' AND logs IS ?`,[s.entries.length,e,o]).changes!==1)throw new Ie(e,"Task changed while migration was in progress","metadata");let f=Un(t,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
345
|
+
FROM tasks WHERE id = ?`,[e]);if(!f||f.log_storage!=="events"||f.logs!==null||f.last_log_seq!==s.entries.length||f.log_revision!==r.log_revision+1)throw new Ie(e,"Final task metadata parity check failed","metadata");return {status:"migrated",entryCount:s.entries.length,sourceBytes:typeof o=="string"?Buffer.byteLength(o,"utf8"):Buffer.isBuffer(o)?o.byteLength:0}}).immediate()}function Au(t){let e=new Date().toISOString().replace(/[-:.TZ]/g,"").slice(0,14),n=crypto.randomBytes(6).toString("hex");return `${t}.task-log-backup-${e}-${n}.sqlite`}async function Ah(t,e,n){let r=n??Au(e);if(Ae.resolve(r)===Ae.resolve(e))throw new Error("Backup path must be different from the source database");if(Sd.existsSync(r))throw new Error(`Refusing to overwrite existing backup: ${r}`);if(Sd.mkdirSync(Ae.dirname(r),{recursive:true}),await t.backup(r),!Sd.existsSync(r))throw new Error(`SQLite backup was not created: ${r}`);let o=yu(r,true);try{let s=o.pragma("integrity_check",{simple:!0});if(s!=="ok")throw new Error(`Backup integrity check failed: ${s}`)}finally{o.close();}return r}function Oh(t){let e=Bn(t,`SELECT task_id AS taskId,
|
|
346
|
+
COUNT(*) AS eventCount,
|
|
347
|
+
COUNT(DISTINCT seq) AS distinctSeqCount,
|
|
348
|
+
MIN(seq) AS minSeq,
|
|
349
|
+
MAX(seq) AS maxSeq
|
|
350
|
+
FROM task_log_events GROUP BY task_id`),n=e.reduce((r,o)=>r+o.eventCount,0);return {rows:e,eventCount:n}}function vt(t,e,n,r={}){return {taskId:t,kind:e,reason:n,...r}}function vh(t,e,n){let r=[];for(let l of n.failures)l.kind==="malformed"?r.push(vt(l.taskId,"malformed-blob",l.reason)):l.kind==="mixed-source"?r.push(vt(l.taskId,"mixed-source",l.reason)):r.push(vt(l.taskId,"source-invariant",l.reason));let o=Oh(t),s=new Map(o.rows.map(l=>[l.taskId,l]));for(let l of o.rows){let g=n.tasks.get(l.taskId);if(!g){r.push(vt(null,"orphan-event",`Event rows reference missing task ${l.taskId}`,{actual:l.eventCount}));continue}(l.minSeq===null||l.minSeq<1||l.distinctSeqCount!==l.maxSeq)&&r.push(vt(g.id,"seq-gap","Task event sequence has a gap or invalid starting sequence",{expected:l.maxSeq??0,actual:l.distinctSeqCount})),g.log_storage==="events"&&g.last_log_seq!==l.eventCount&&r.push(vt(g.id,"count-mismatch","last_log_seq does not match task_log_events row count",{expected:g.last_log_seq??0,actual:l.eventCount}));}for(let l of n.tasks.values())l.log_storage==="events"&&!s.has(l.id)&&l.last_log_seq!==0&&r.push(vt(l.id,"count-mismatch","Event-source task has no rows for its last_log_seq",{expected:l.last_log_seq??0,actual:0}));for(let l of Bn(t,`SELECT task_id AS taskId, seq, COUNT(*) AS duplicateCount
|
|
351
|
+
FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))r.push(vt(l.taskId,"duplicate-seq",`Duplicate task event sequence ${l.seq}`,{actual:l.duplicateCount,seq:l.seq}));let i=Un(t,`SELECT COUNT(*) AS count FROM task_log_events
|
|
352
|
+
WHERE seq IS NULL OR seq < 1 OR timestamp IS NULL OR level IS NULL OR message IS NULL`)?.count??0;i>0&&r.push(vt(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:i}));let d=new Set(r.flatMap(l=>l.taskId?[l.taskId]:[])),c=r.map(l=>({taskId:l.taskId??"(orphan)",reason:l.reason,kind:l.kind==="malformed-blob"?"malformed":l.kind==="mixed-source"?"mixed-source":"metadata"})),u=c.filter(l=>l.kind==="malformed"),f={checkedTasks:n.taskCount,eventSourceTasks:n.eventSourceTasks,blobSourceTasks:n.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:r.filter(l=>l.kind==="orphan-event").length,failedTasks:d.size,issues:r};return Co("verify",e,n,{ok:r.length===0,migratedTasks:n.eventSourceTasks,migratedEntries:o.eventCount,skippedTasks:n.candidateTaskCount,failedTasks:d.size,malformedRows:u,failures:c,remainingTaskCount:n.candidateTaskCount,verification:f})}function Nh(t){if(t.mode!=="apply"&&t.batchTasks!==void 0)throw new Error("--batch-tasks is only valid with --apply");if(t.batchTasks!==void 0&&(!Number.isInteger(t.batchTasks)||t.batchTasks<1))throw new Error("--batch-tasks must be a positive integer")}async function xh(t){Nh(t);let e=Lo(t.dbPath),n=yu(e,t.mode!=="apply");try{kh(n);let r=wh(n),o=yh(n);if(t.mode==="verify")return {...vh(n,e,r),activeTaskCount:o};if(t.mode==="dry-run")return Co("dry-run",e,r,{ok:r.failures.length===0,activeTaskCount:o,skippedTasks:r.eventSourceTasks,remainingTaskCount:r.candidateTaskCount});let s=t.backupPath??Au(e),i=bu(e,r.entryCount,s);if(!i.freeSpaceGatePassed)return Co("apply",e,r,{ok:!1,activeTaskCount:o,blockedReason:`Apply blocked: available free space (${i.availableFreeSpaceBytes} bytes) is below the required ${i.requiredFreeSpaceBytes} bytes (including a ${i.minimumFreeSpaceReserveBytes} byte reserve)`,skippedTasks:r.eventSourceTasks,remainingTaskCount:r.candidateTaskCount},i);let d=await Ah(n,e,s),c=[...r.failures],u=t.batchTasks===void 0?r.candidateIds:r.candidateIds.slice(0,t.batchTasks),f=t.batchTasks??Math.max(u.length,1),l=0,g=0,_=0,m=[...i.warnings];for(let[k,T]of u.entries()){try{let E=Ih(n,T);E.status==="migrated"&&(l+=1,g+=E.entryCount,_+=E.sourceBytes);}catch(E){c.push(vi(E,T));}if((k+1)%f===0||k===u.length-1){let E=wr(n);E&&m.push(E);}}return Co("apply",e,r,{ok:c.length===0,activeTaskCount:o,backupPath:d,backupMethod:"sqlite-online-backup",migratedTasks:l,migratedEntries:g,logicalSourceBytesRemoved:_,failedTasks:Iu(c),failures:c,malformedRows:r.malformedRows,remainingTaskCount:Rh(n),skippedTasks:r.eventSourceTasks,warnings:m},i)}finally{n.close();}}function Ch(t){return Ae.basename(t)}oo();xn();Ys();var Ho=["success","failed","completed"],xu=1440*60*1e3,Cu=1,Mh=2048,Ni=64*1024*1024,Pi=[{key:"usageBackfill",field:"metadata.usageBackfill",before:"before_usage_backfill",after:"after_usage_backfill"},{key:"usageAccounting",field:"metadata.usageAccounting",before:"before_usage_accounting",after:"after_usage_accounting"},{key:"usageAccountingReason",field:"metadata.usageAccountingReason",before:"before_usage_accounting_reason",after:"after_usage_accounting_reason"}],Ou=["run_epoch","completed_at","input_tokens","output_tokens","cached_input_tokens","cost_usd","model",...Pi.map(t=>t.field)],Hh=20,$h=["pre-instrumentation","provider-no-usage","suppressed-by-adapter","not-captured"];function Du(){return St("better-sqlite3")}function Li(t,e){let n=He(t),r=t===":memory:";if(!r&&!Sd.existsSync(n))throw new Error(`Database not found: ${n}`);let o=new(Du())(n,{readonly:e,fileMustExist:!r,timeout:5e3});return o.pragma("foreign_keys = ON"),o.pragma("busy_timeout = 5000"),o}function yr(t,e,n=[]){return t.prepare(e).all(...n)}function nn(t,e,n=[]){return t.prepare(e).get(...n)}function Ut(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function rn(t){if(!t)return {};try{let e=JSON.parse(t);return Ut(e)?{...e}:{}}catch{return {}}}function Pu(t){let e=t.provider;if(!(typeof e!="string"||e.trim().length===0))return e.trim()}function Lu(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Uh(t){return t??"unknown"}function Bh(t){return Ho.includes(t)}function qh(t){return t==="plugin/mock"}function Mu(t,e,n){return Bh(t.status)&&!Mn(t)&&t.agent_id!=="workflow"&&t.platform!=="workflow"&&t.platform!=="mcp"&&t.agent_id!=="direct"&&n.direct_call!==true&&!qh(e)}function Fh(t,e){let n=t.usageBackfill;return Ut(n)&&Object.prototype.hasOwnProperty.call(n,String(e))}function jh(t){return typeof t=="string"&&$h.includes(t)}function Hu(t,e){return t.usageAccounting==="recorded"||t.usageAccounting==="unavailable"&&jh(t.usageAccountingReason)?true:Fh(t,e)}function Wh(t){return yr(t,`SELECT id, agent_id, status, completed_at, metadata, model, platform, run_epoch,
|
|
353
|
+
input_tokens, output_tokens, cached_input_tokens, cost_usd
|
|
354
|
+
FROM tasks
|
|
355
|
+
WHERE status IN (?, ?, ?)
|
|
356
|
+
ORDER BY completed_at ASC, id ASC`,[...Ho])}function xi(t){let e=Wh(t),n=e.flatMap(d=>{let c=rn(d.metadata),u=Pu(c);return Mu(d,u,c)?[{...d,metadataObject:c,provider:u,epoch:Lu(d.run_epoch)}]:[]}),r=n.filter(d=>!Hu(d.metadataObject,d.epoch)),o=yr(t,`SELECT COUNT(*) AS count
|
|
357
|
+
FROM tasks
|
|
358
|
+
WHERE json_valid(metadata) = 1
|
|
359
|
+
AND json_type(metadata, '$') = 'object'
|
|
360
|
+
AND json_extract(metadata, '$.usageAccounting') IN ('recorded', 'unavailable')`)[0]?.count??0,s=nn(t,"SELECT COUNT(*) AS count FROM tasks")?.count??0,i=nn(t,"SELECT COUNT(*) AS count FROM tasks WHERE status IN (?, ?, ?)",[...Ho])?.count??e.length;return {scannedTasks:s,terminalTasks:i,rawTargetRows:n,candidates:r,accountingTasks:o}}function $u(t){return !t||t==="unknown"||t==="cli/unknown"?"pre-instrumentation":t==="cli/antigravity"||t.startsWith("acp/")||t.startsWith("remote/")?"provider-no-usage":t==="cli/codex"||t==="cli/opencode"?"suppressed-by-adapter":"not-captured"}function zh(t){let e=t instanceof Date?t.getTime():t===void 0?Date.now():new Date(t).getTime();if(!Number.isFinite(e))throw new Error("Usage backfill clock must be a valid date");return e}function Gh(t,e){if(!t)return false;let n=Date.parse(t);return Number.isFinite(n)&&n>=e-xu}function Kh(t,e,n){let r=$u(t.provider),o;try{o=mo({taskLogRepository:e,taskId:t.id,provider:t.provider,model:t.model})?.usage;}catch{o=void 0;}return o?{candidate:t,outcome:"recovered",usage:o}:Gh(t.completed_at,n)?{candidate:t,outcome:"deferred",reason:r}:{candidate:t,outcome:"unavailable",reason:r}}function Vh(t,e,n){let r=Uh(e),o=t[r]??{candidates:0,recovered:0,unavailable:0,deferred:0};o.candidates+=1,o[n]+=1,t[r]=o;}function Jh(t,e){e&&(t[e]+=1);}function Xh(){return {"pre-instrumentation":0,"provider-no-usage":0,"suppressed-by-adapter":0,"not-captured":0}}function Yh(t){return Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))}function vu(t,e,n,r,o){let s=rn(t),i=Ut(s.usageBackfill)?{...s.usageBackfill}:{};return i[String(e)]={at:n},s.usageBackfill=i,s.usageAccounting=r,r==="unavailable"&&o?s.usageAccountingReason=o:delete s.usageAccountingReason,JSON.stringify(s)}function Qh(t,e){let n=rn(t.metadata),r=Pu(n);return Mu(t,r,n)&&t.id===e.id&&r===e.provider&&Lu(t.run_epoch)===e.epoch&&t.completed_at===e.completed_at&&!Hu(n,e.epoch)}function Zh(t,e,n){if(e.outcome!=="deferred"){if(e.outcome==="unavailable")return {...t,metadata:vu(t.metadata,e.candidate.epoch,n,"unavailable",e.reason)};if(e.usage)return {...t,input_tokens:e.usage.inputTokens,output_tokens:e.usage.outputTokens,cached_input_tokens:e.usage.cachedInputTokens,cost_usd:e.usage.costUsd,metadata:vu(t.metadata,e.candidate.epoch,n,"recorded"),model:t.model===null&&e.usage.model?e.usage.model:t.model}}}function em(t,e,n,r){return t.transaction(()=>{let s=nn(t,`SELECT id, agent_id, status, completed_at, metadata, model, platform, run_epoch,
|
|
361
|
+
input_tokens, output_tokens, cached_input_tokens, cost_usd
|
|
362
|
+
FROM tasks WHERE id = ?`,[n.candidate.id]);if(!s||!Qh(s,n.candidate)||n.outcome==="deferred")return "skipped";let i=Zh(s,n,r);return i?(sm(e,rm(s,i)),n.outcome==="unavailable"?t.prepare("UPDATE tasks SET metadata = ? WHERE id = ?").run(i.metadata,s.id).changes===1?"changed":"skipped":t.prepare(`UPDATE tasks
|
|
363
|
+
SET input_tokens = ?, output_tokens = ?, cached_input_tokens = ?, cost_usd = ?,
|
|
364
|
+
metadata = ?, model = ?
|
|
365
|
+
WHERE id = ?`).run(i.input_tokens,i.output_tokens,i.cached_input_tokens,i.cost_usd,i.metadata,i.model,s.id).changes===1?"changed":"skipped"):"skipped"}).immediate()}function Nu(t){let e=Ae.dirname(Ae.resolve(t));for(;!Sd.existsSync(e);){let n=Ae.dirname(e);if(n===e)break;e=n;}return e}function tm(t,e,n){let r=[...new Set([Nu(t),...n?[Nu(n)]:[]])],o=Number.POSITIVE_INFINITY,s=[];for(let c of r)try{let u=Sd.statfsSync(c);o=Math.min(o,u.bavail*u.bsize);}catch(u){o=0,s.push(`Unable to inspect free space for ${c}: ${u instanceof Error?u.message:String(u)}`);}let i=e*Mh,d=Number.isFinite(o)?Math.floor(o):0;return {estimatedFreeSpaceBytes:i,requiredFreeSpaceBytes:i+Ni,availableFreeSpaceBytes:d,minimumFreeSpaceReserveBytes:Ni,freeSpaceGatePassed:Number.isFinite(d)&&d>=i+Ni,warnings:s}}function Uu(t){let e=new Date().toISOString().replace(/[-:.TZ]/g,"").slice(0,14),n=crypto.randomBytes(6).toString("hex");return `${t}.usage-undo-${e}-${n}.sqlite`}function qn(t,e){if(!Object.prototype.hasOwnProperty.call(t,e))return null;let n=JSON.stringify(t[e]);return n===void 0?null:n}function nm(t){if(t!==null)try{return JSON.parse(t)}catch{throw new Error("Usage undo snapshot contains invalid metadata JSON")}}function Di(t,e){if(Object.is(t,e))return true;if(Array.isArray(t)||Array.isArray(e))return !Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?false:t.every((n,r)=>Di(n,e[r]));if(Ut(t)||Ut(e)){if(!Ut(t)||!Ut(e))return false;let n=Object.keys(t).sort(),r=Object.keys(e).sort();return n.length===r.length&&n.every((o,s)=>o===r[s]&&Di(t[o],e[o]))}return false}function rm(t,e){let n=rn(t.metadata),r=rn(e.metadata);return {id:t.id,before_run_epoch:t.run_epoch,after_run_epoch:e.run_epoch,before_completed_at:t.completed_at,after_completed_at:e.completed_at,before_input_tokens:t.input_tokens,after_input_tokens:e.input_tokens,before_output_tokens:t.output_tokens,after_output_tokens:e.output_tokens,before_cached_input_tokens:t.cached_input_tokens,after_cached_input_tokens:e.cached_input_tokens,before_cost_usd:t.cost_usd,after_cost_usd:e.cost_usd,before_model:t.model,after_model:e.model,before_usage_backfill:qn(n,"usageBackfill"),after_usage_backfill:qn(r,"usageBackfill"),before_usage_accounting:qn(n,"usageAccounting"),after_usage_accounting:qn(r,"usageAccounting"),before_usage_accounting_reason:qn(n,"usageAccountingReason"),after_usage_accounting_reason:qn(r,"usageAccountingReason")}}function om(t,e,n,r){let o=e??Uu(t);if(o===":memory:")throw new Error("Usage undo snapshot path must be a file");if(Ae.resolve(o)===Ae.resolve(t))throw new Error("Undo snapshot path must be different from the source database");if(Sd.existsSync(o))throw new Error(`Refusing to overwrite existing undo snapshot: ${o}`);Sd.mkdirSync(Ae.dirname(o),{recursive:true});let s=He(o),i=new(Du())(s,{readonly:false,fileMustExist:false,timeout:5e3});try{return i.pragma("foreign_keys = ON"),i.pragma("busy_timeout = 5000"),i.exec(`
|
|
366
|
+
CREATE TABLE usage_undo_meta (
|
|
367
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
368
|
+
source_db_path TEXT NOT NULL,
|
|
369
|
+
created_at TEXT NOT NULL,
|
|
370
|
+
schema_version INTEGER NOT NULL,
|
|
371
|
+
plan_summary TEXT NOT NULL
|
|
372
|
+
);
|
|
373
|
+
CREATE TABLE usage_undo_rows (
|
|
374
|
+
id TEXT PRIMARY KEY,
|
|
375
|
+
before_run_epoch INTEGER,
|
|
376
|
+
after_run_epoch INTEGER,
|
|
377
|
+
before_completed_at TEXT,
|
|
378
|
+
after_completed_at TEXT,
|
|
379
|
+
before_input_tokens INTEGER NOT NULL,
|
|
380
|
+
after_input_tokens INTEGER NOT NULL,
|
|
381
|
+
before_output_tokens INTEGER NOT NULL,
|
|
382
|
+
after_output_tokens INTEGER NOT NULL,
|
|
383
|
+
before_cached_input_tokens INTEGER NOT NULL,
|
|
384
|
+
after_cached_input_tokens INTEGER NOT NULL,
|
|
385
|
+
before_cost_usd REAL NOT NULL,
|
|
386
|
+
after_cost_usd REAL NOT NULL,
|
|
387
|
+
before_model TEXT,
|
|
388
|
+
after_model TEXT,
|
|
389
|
+
before_usage_backfill TEXT,
|
|
390
|
+
after_usage_backfill TEXT,
|
|
391
|
+
before_usage_accounting TEXT,
|
|
392
|
+
after_usage_accounting TEXT,
|
|
393
|
+
before_usage_accounting_reason TEXT,
|
|
394
|
+
after_usage_accounting_reason TEXT
|
|
395
|
+
);
|
|
396
|
+
`),i.prepare(`INSERT INTO usage_undo_meta (id, source_db_path, created_at, schema_version, plan_summary)
|
|
397
|
+
VALUES (1, ?, ?, ?, ?)`).run(Ae.resolve(t),n,Cu,JSON.stringify(r)),{path:o,db:i}}catch(d){throw i.close(),d}}function sm(t,e){t.db.prepare(`INSERT INTO usage_undo_rows (
|
|
398
|
+
id, before_run_epoch, after_run_epoch, before_completed_at, after_completed_at,
|
|
399
|
+
before_input_tokens, after_input_tokens, before_output_tokens, after_output_tokens,
|
|
400
|
+
before_cached_input_tokens, after_cached_input_tokens, before_cost_usd, after_cost_usd,
|
|
401
|
+
before_model, after_model, before_usage_backfill, after_usage_backfill,
|
|
402
|
+
before_usage_accounting, after_usage_accounting,
|
|
403
|
+
before_usage_accounting_reason, after_usage_accounting_reason
|
|
404
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.id,e.before_run_epoch,e.after_run_epoch,e.before_completed_at,e.after_completed_at,e.before_input_tokens,e.after_input_tokens,e.before_output_tokens,e.after_output_tokens,e.before_cached_input_tokens,e.after_cached_input_tokens,e.before_cost_usd,e.after_cost_usd,e.before_model,e.after_model,e.before_usage_backfill,e.after_usage_backfill,e.before_usage_accounting,e.after_usage_accounting,e.before_usage_accounting_reason,e.after_usage_accounting_reason);}function im(t){let e=yr(t,"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").map(n=>n.name);if(e.length!==2||e[0]!=="usage_undo_meta"||e[1]!=="usage_undo_rows")throw new Error("Invalid usage undo snapshot: expected usage_undo_meta and usage_undo_rows tables")}function Bu(t){let e=Li(t,true);try{let n=e.pragma("integrity_check",{simple:!0});if(n!=="ok")throw new Error(`Undo snapshot integrity check failed: ${n}`);im(e);}finally{e.close();}}function am(t,e){if(!Sd.existsSync(t))throw new Error(`Usage undo snapshot not found: ${t}`);Bu(t);let n=Li(t,true);try{let r=nn(n,"SELECT source_db_path, created_at, schema_version, plan_summary FROM usage_undo_meta WHERE id = 1");if(!r)throw new Error("Usage undo snapshot metadata is missing");if(Ae.resolve(r.source_db_path)!==Ae.resolve(e))throw new Error(`Usage undo snapshot source database ${r.source_db_path} does not match restore target ${Ae.resolve(e)}`);if(r.schema_version!==Cu)throw new Error(`Unsupported usage undo snapshot schema version: ${r.schema_version}`);try{let o=JSON.parse(r.plan_summary);if(!Ut(o))throw new Error("plan summary is not an object")}catch(o){throw new Error(`Usage undo snapshot plan summary is invalid: ${o instanceof Error?o.message:String(o)}`)}return {path:t,rows:yr(n,`SELECT id, before_run_epoch, after_run_epoch, before_completed_at, after_completed_at,
|
|
405
|
+
before_input_tokens, after_input_tokens, before_output_tokens, after_output_tokens,
|
|
406
|
+
before_cached_input_tokens, after_cached_input_tokens, before_cost_usd, after_cost_usd,
|
|
407
|
+
before_model, after_model, before_usage_backfill, after_usage_backfill,
|
|
408
|
+
before_usage_accounting, after_usage_accounting,
|
|
409
|
+
before_usage_accounting_reason, after_usage_accounting_reason
|
|
410
|
+
FROM usage_undo_rows ORDER BY rowid ASC`)}}finally{n.close();}}function qu(t,e,n){let r=t[n==="before"?e.before:e.after];return nm(r)}function dm(t,e){return Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0}function cm(t,e){let n=[];Object.is(t.run_epoch,e.after_run_epoch)||n.push("run_epoch"),Object.is(t.completed_at,e.after_completed_at)||n.push("completed_at"),Object.is(t.input_tokens,e.after_input_tokens)||n.push("input_tokens"),Object.is(t.output_tokens,e.after_output_tokens)||n.push("output_tokens"),Object.is(t.cached_input_tokens,e.after_cached_input_tokens)||n.push("cached_input_tokens"),Object.is(t.cost_usd,e.after_cost_usd)||n.push("cost_usd"),Object.is(t.model,e.after_model)||n.push("model");let r=rn(t.metadata);for(let o of Pi){let s=qu(e,o,"after");Di(dm(r,o.key),s)||n.push(o.field);}return n}function um(t,e){let n=rn(t);for(let r of Pi){let o=qu(e,r,"before");o===void 0?delete n[r.key]:n[r.key]=o;}return JSON.stringify(n)}function lm(t,e){return t.transaction(()=>{let r=nn(t,`SELECT id, agent_id, status, completed_at, metadata, model, platform, run_epoch,
|
|
411
|
+
input_tokens, output_tokens, cached_input_tokens, cost_usd
|
|
412
|
+
FROM tasks WHERE id = ?`,[e.id]);if(!r)return {taskId:e.id,fields:[...Ou]};let o=cm(r,e);if(o.length>0)return {taskId:e.id,fields:o};let s=um(r.metadata,e);return t.prepare(`UPDATE tasks
|
|
413
|
+
SET run_epoch = ?, completed_at = ?, input_tokens = ?, output_tokens = ?,
|
|
414
|
+
cached_input_tokens = ?, cost_usd = ?, model = ?, metadata = ?
|
|
415
|
+
WHERE id = ?`).run(e.before_run_epoch,e.before_completed_at,e.before_input_tokens,e.before_output_tokens,e.before_cached_input_tokens,e.before_cost_usd,e.before_model,s,e.id).changes===1?void 0:{taskId:e.id,fields:[...Ou]}}).immediate()}function pm(t){if(!nn(t,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tasks'"))throw new Error("Usage backfill requires the tasks table");let n=new Set(yr(t,"PRAGMA table_info(tasks)").map(i=>i.name)),o=["id","agent_id","status","completed_at","metadata","model","platform","run_epoch","input_tokens","output_tokens","cached_input_tokens","cost_usd"].filter(i=>!n.has(i));if(o.length>0)throw new Error(`Usage backfill requires task columns: ${o.join(", ")}`);if(!nn(t,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'task_log_events'"))throw new Error("Usage backfill requires the task_log_events table")}function fm(t,e,n,r){return {mode:t,ok:true,dbPath:e,scannedTasks:n.scannedTasks,terminalTasks:n.terminalTasks,rawTargetTasks:n.rawTargetRows.length,candidateTasks:n.candidates.length,recoveredTasks:0,unavailableTasks:0,deferredTasks:0,changedTasks:0,wouldChangeTasks:0,restored:0,skippedConflict:0,conflictSamples:[],accountingTasks:n.accountingTasks,remainingTargetTasks:n.candidates.length,providerDistribution:{},reasonCounts:Xh(),estimatedFreeSpaceBytes:r.estimatedFreeSpaceBytes,requiredFreeSpaceBytes:r.requiredFreeSpaceBytes,availableFreeSpaceBytes:r.availableFreeSpaceBytes,minimumFreeSpaceReserveBytes:r.minimumFreeSpaceReserveBytes,freeSpaceGatePassed:r.freeSpaceGatePassed,failures:[],warnings:[...r.warnings]}}function gm(t,e){for(let n of e)Vh(t.providerDistribution,n.candidate.provider,n.outcome),Jh(t.reasonCounts,n.outcome==="unavailable"?n.reason:void 0),n.outcome==="recovered"&&(t.recoveredTasks+=1),n.outcome==="unavailable"&&(t.unavailableTasks+=1),n.outcome==="deferred"&&(t.deferredTasks+=1);t.providerDistribution=Yh(t.providerDistribution),t.wouldChangeTasks=t.recoveredTasks+t.unavailableTasks;}function _m(t){if(!["dry-run","apply","verify","restore"].includes(t.mode))throw new Error(`Unsupported usage backfill mode: ${t.mode}`);if(t.backupPath&&t.mode!=="apply")throw new Error("--backup is only valid with --apply");if(t.restorePath&&t.mode!=="restore")throw new Error("--restore is only valid with restore mode");if(t.mode==="restore"&&!t.restorePath)throw new Error("Restore mode requires a usage undo snapshot path")}async function hm(t){_m(t);let e=Lo(t.dbPath),n=zh(t.now),r=new Date(n).toISOString(),o=t.mode==="restore"?am(t.restorePath,e):void 0,s=Li(e,t.mode!=="apply"&&t.mode!=="restore"),i;try{pm(s);let d=xi(s),c=t.mode==="apply"&&d.candidates.length>0?t.backupPath??Uu(e):void 0,u=tm(e,d.candidates.length,c),f=fm(t.mode,e,d,u);if(o){f.backupPath=o.path,f.snapshotPath=o.path;for(let T of o.rows)try{let E=lm(s,T);E?(f.skippedConflict+=1,f.conflictSamples.length<Hh&&f.conflictSamples.push(E)):f.restored+=1;}catch(E){f.failures.push({taskId:T.id,reason:E instanceof Error?E.message:String(E)});}let m=xi(s);f.accountingTasks=m.accountingTasks,f.remainingTargetTasks=m.candidates.length,f.ok=f.failures.length===0;let k=wr(s);return k&&f.warnings.push(k),f}if(t.mode==="verify")return f;if(t.mode==="apply"&&!u.freeSpaceGatePassed&&d.candidates.length>0)return f.ok=!1,f.blockedReason=`Apply blocked: available free space (${u.availableFreeSpaceBytes} bytes) is below the required ${u.requiredFreeSpaceBytes} bytes (including a ${u.minimumFreeSpaceReserveBytes} byte reserve)`,f;if(d.candidates.length===0)return f;let l=new exports.TaskLogRepository({dbPath:e}),g=[];for(let m of d.candidates){let k=Kh(m,l,n);g.push(k);}if(gm(f,g),t.mode==="dry-run"&&(f.changedTasks=0),t.mode==="apply"){i=om(e,c,r,{candidates:g.length,recovered:f.recoveredTasks,unavailable:f.unavailableTasks,deferred:f.deferredTasks}),f.backupPath=i.path,f.snapshotPath=i.path,f.backupMethod="row-undo-snapshot";for(let k of g)if(k.outcome!=="deferred")try{em(s,i,k,r)==="changed"&&(f.changedTasks+=1);}catch(T){f.failures.push({taskId:k.candidate.id,reason:T instanceof Error?T.message:String(T)});}let m=i.path;i.db.close(),i=void 0,Bu(m);}let _=xi(s);if(f.accountingTasks=_.accountingTasks,f.remainingTargetTasks=_.candidates.length,f.ok=f.failures.length===0,t.mode==="apply"){let m=wr(s);m&&f.warnings.push(m);}return f}finally{i&&i.db.close(),s.close();}}oo();h();re();ue();_e();ie();fe();fr();h();function $o(t){return t!==null&&t!==""}function mm(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":$o(t.parent_task_id)||$o(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function Fu(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&$o(e)?e:null}}function Uo(t){let e=mm(t),n=$o(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 ju(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?Fu(t.creator_actor_kind,t.creator_actor_id):e?Uo(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?Fu(t.created_by_kind,t.created_by_id):n?Uo(n):void 0}function Rr(t){return On(t)}function Em({metadata:t,...e}){return {...e,status:st({...e,metadata:t}),terminalReason:wt({...e,metadata:t})??null}}var qo=32,zu=100,Sm=["running","failed"];function bm(t){return t==="running"?0:t==="failed"?1:2}function Gu(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 Im(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function Am(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 exports.RepositoryError("VALIDATION","Invalid descendant cursor")}function Ku(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function Vu(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function Om(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function Ju(t,e,n,r){let o=Om(e);o&&(t[o]+=r,t.total+=r,o==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var Fo=900,Xu=20;function Yu(t,e){return (t?.origin??"direct")===e}function Qu(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 on=class extends exports.RepositoryError{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function Fn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function vm(t){let n=Fn(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 Zu(t,e,n){return t.get(drizzleOrm.sql`
|
|
416
|
+
SELECT id
|
|
417
|
+
FROM tasks INDEXED BY idx_tasks_thread_id
|
|
418
|
+
WHERE thread_id = ${e}
|
|
419
|
+
AND id <> ${n}
|
|
420
|
+
LIMIT 1
|
|
421
|
+
`)!==void 0}var Mi=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(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 drizzleOrm.sql.raw(`NOT EXISTS (
|
|
422
|
+
SELECT 1 FROM ${r}
|
|
423
|
+
WHERE parent.id = ${e}.parent_task_id
|
|
424
|
+
AND parent.thread_id = ${e}.thread_id
|
|
425
|
+
)`)}workflowAnchorPredicateSql(e){return drizzleOrm.sql.raw(`COALESCE(
|
|
426
|
+
${e}.agent_id = 'workflow'
|
|
427
|
+
OR ${e}.metadata LIKE '%"kind":"workflow_card"%'
|
|
428
|
+
OR ${e}.metadata LIKE '%"kind":"workflow_ui_instance"%'
|
|
429
|
+
OR (
|
|
430
|
+
${e}.metadata LIKE '%"workflow"%'
|
|
431
|
+
AND CASE WHEN json_valid(${e}.metadata)
|
|
432
|
+
THEN json_type(${e}.metadata, '$.workflow')
|
|
433
|
+
END IN ('object', 'array')
|
|
434
|
+
),
|
|
435
|
+
0
|
|
436
|
+
)`)}descendantTraversalSql(e,n,r){return drizzleOrm.sql`
|
|
437
|
+
WITH RECURSIVE
|
|
438
|
+
own_tasks(task_id) AS (${e}),
|
|
439
|
+
seeds(task_id) AS (${n}),
|
|
440
|
+
descendants(root_task_id, task_id, depth) AS (
|
|
441
|
+
SELECT seed.task_id, seed.task_id, 0 FROM seeds seed
|
|
442
|
+
UNION
|
|
443
|
+
SELECT descendants.root_task_id, child.id, descendants.depth + 1
|
|
444
|
+
FROM descendants
|
|
445
|
+
JOIN tasks child INDEXED BY idx_tasks_parent_task_id
|
|
446
|
+
ON child.parent_task_id = descendants.task_id
|
|
447
|
+
WHERE descendants.depth < ${r}
|
|
448
|
+
),
|
|
449
|
+
descendant_ids(root_task_id, task_id, depth) AS (
|
|
450
|
+
SELECT descendants.root_task_id, descendants.task_id, MIN(descendants.depth)
|
|
451
|
+
FROM descendants
|
|
452
|
+
WHERE descendants.depth > 0
|
|
453
|
+
AND descendants.task_id <> descendants.root_task_id
|
|
454
|
+
GROUP BY descendants.root_task_id, descendants.task_id
|
|
455
|
+
)
|
|
456
|
+
`}descendantSkippedSql(e){let n=drizzleOrm.sql.raw(e);return drizzleOrm.sql`(
|
|
457
|
+
${this.workflowAnchorPredicateSql(e)}
|
|
458
|
+
OR (
|
|
459
|
+
EXISTS (SELECT 1 FROM own_tasks own WHERE own.task_id = ${n}.id)
|
|
460
|
+
AND ${this.topLevelTaskPredicateSql(e)}
|
|
461
|
+
)
|
|
462
|
+
)`}findAllThreadsQuery(e,n){let r=[];e&&r.push(drizzleOrm.sql`workspace_id = ${e}`),n&&r.push(drizzleOrm.sql`created_by_kind = ${n}`);let o=r.length>0?drizzleOrm.sql` WHERE ${drizzleOrm.sql.join(r,drizzleOrm.sql` AND `)}`:drizzleOrm.sql``;return drizzleOrm.sql`SELECT * FROM threads${o} ORDER BY updated_at DESC`}findThreadIdsQuery(e){return e?drizzleOrm.sql`SELECT id FROM threads INDEXED BY idx_threads_ws_updated
|
|
463
|
+
WHERE workspace_id = ${e}
|
|
464
|
+
ORDER BY updated_at DESC`:drizzleOrm.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(!Sd.existsSync(i))continue;let d=N(i);try{let c=d.db.all(this.findThreadIdsQuery(e));for(let u of c)o.has(u.id)||(o.add(u.id),s.push(u.id));}catch(c){throw new exports.RepositoryError("DB_ERROR",n,c)}finally{d.close();}}return s}findThreadSortKeysQuery(e){return drizzleOrm.sql`SELECT id, updated_at
|
|
465
|
+
FROM threads INDEXED BY idx_threads_ws_updated
|
|
466
|
+
WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!Sd.existsSync(s))continue;let i=N(s);try{let d=i.db.all(this.findThreadSortKeysQuery(e));for(let c of d)r.has(c.id)||(r.add(c.id),o.push(c));}catch(d){throw new exports.RepositoryError("DB_ERROR","Failed to find recent direct threads",d)}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 d of o){if(!Sd.existsSync(d))continue;let c=N(d);try{for(let u=0;u<e.length;u+=Fo){let f=e.slice(u,u+Fo),l=drizzleOrm.inArray(w.id,f),g=n?drizzleOrm.and(l,drizzleOrm.eq(w.workspace_id,n)):l,_=c.db.select().from(w).where(g).all();for(let m of _)s.has(m.id)||(s.add(m.id),i.push(m));}}catch(u){throw new exports.RepositoryError("DB_ERROR",r,u)}finally{c.close();}}return i}readThreadRows(e,n,r="Failed to find all threads"){let o=this.resolveDbPaths(),s=new Set,i=[];for(let d of o){if(!Sd.existsSync(d))continue;let c=N(d);try{let u=c.db.all(this.findAllThreadsQuery(e,n));for(let f of u)s.has(f.id)||(s.add(f.id),i.push(f));}catch(u){throw new exports.RepositoryError("DB_ERROR",r,u)}finally{c.close();}}return i}findAllThreads(e,n){return this.readThreadRows(e,n)}explainFindAllThreadsPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!Sd.existsSync(o))continue;let s=N(o);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findAllThreadsQuery(e,n)}`).map(d=>d.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(!Sd.existsSync(i))continue;let d=N(i);try{let c=drizzleOrm.or(drizzleOrm.inArray(w.id,e),drizzleOrm.inArray(w.title,e)),u=n?drizzleOrm.and(c,drizzleOrm.eq(w.workspace_id,n)):c,f=d.db.select().from(w).where(u).orderBy(drizzleOrm.desc(w.updated_at)).all();for(let l of f)o.has(l.id)||(o.add(l.id),s.push(l));}catch(c){throw new exports.RepositoryError("DB_ERROR","Failed to find threads by ids or titles",c)}finally{d.close();}}return s}findThreadById(e,n){let r=this.resolveDbPaths();for(let o of r){if(!Sd.existsSync(o))continue;let s=N(o);try{let i=drizzleOrm.eq(w.id,e),d=n?drizzleOrm.and(i,drizzleOrm.eq(w.workspace_id,n)):i,c=s.db.select().from(w).where(d).limit(1).get()??void 0;if(c)return c}catch(i){throw new exports.RepositoryError("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:P.id}).from(P).where(drizzleOrm.eq(P.id,e.workspaceId)).limit(1).get())throw new exports.RepositoryError("NOT_FOUND","Workspace not found");let s=r.select().from(w).where(drizzleOrm.eq(w.id,e.threadId)).limit(1).get();if(s){let f=Fn(s.metadata).appLaunch,l=f&&typeof f=="object"&&!Array.isArray(f)?f.appId:void 0,g=r.get(drizzleOrm.sql`
|
|
467
|
+
SELECT COUNT(*) AS count FROM tasks WHERE thread_id = ${e.threadId}
|
|
468
|
+
`)?.count??0;return s.workspace_id===e.workspaceId&&l===e.appId&&s.message_count===0&&s.first_message===null&&s.last_message===null&&g===0?{status:"existing",thread:s}:{status:"conflict"}}let i=new Date().toISOString(),d=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(w).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:d,created_at:i,updated_at:i}).run();let c=r.select().from(w).where(drizzleOrm.eq(w.id,e.threadId)).limit(1).get();if(!c)throw new exports.RepositoryError("DB_ERROR","App-launch thread could not be read after insert");return {status:"created",thread:c}},{behavior:"immediate"})}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("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(!Sd.existsSync(o))continue;let s=N(o);try{let i=drizzleOrm.eq(w.id,e),d=n?drizzleOrm.and(i,drizzleOrm.eq(w.workspace_id,n)):i;if(s.db.select({id:w.id}).from(w).where(d).limit(1).get())return !0}catch(i){throw new exports.RepositoryError("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,d=0,c=0,u=0,f=0,l=0,g=0,_=0,m=new Set;for(let k of r){if(!Sd.existsSync(k))continue;let T=N(k);try{let E=T.db.get(drizzleOrm.sql`
|
|
469
|
+
SELECT count(*) AS cnt
|
|
470
|
+
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
471
|
+
WHERE child.thread_id = ${e}
|
|
472
|
+
AND ${this.topLevelTaskPredicateSql()}
|
|
473
|
+
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
474
|
+
`);E&&(o+=E.cnt);let S=T.db.get(drizzleOrm.sql`
|
|
258
475
|
SELECT
|
|
259
|
-
count(*) AS cnt,
|
|
260
476
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
261
477
|
COALESCE(SUM(child.output_tokens), 0) AS total_output,
|
|
262
478
|
COALESCE(SUM(child.cached_input_tokens), 0) AS total_cached,
|
|
263
479
|
COALESCE(SUM(child.cost_usd), 0) AS total_cost
|
|
264
|
-
FROM tasks child
|
|
265
|
-
WHERE child.thread_id = ${
|
|
266
|
-
AND ${
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
480
|
+
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
481
|
+
WHERE child.thread_id = ${e}
|
|
482
|
+
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
483
|
+
`);S&&(s+=S.total_input,i+=S.total_output,d+=S.total_cached,c+=S.total_cost);let D=T.db.get(drizzleOrm.sql`
|
|
484
|
+
WITH RECURSIVE
|
|
485
|
+
own_tasks(task_id) AS (
|
|
486
|
+
SELECT own.id
|
|
487
|
+
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
488
|
+
WHERE own.thread_id = ${e}
|
|
489
|
+
${n?drizzleOrm.sql`AND own.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
490
|
+
),
|
|
491
|
+
descendants(task_id, depth) AS (
|
|
492
|
+
SELECT own.task_id, 0 FROM own_tasks own
|
|
493
|
+
UNION
|
|
494
|
+
SELECT child.id, descendants.depth + 1
|
|
495
|
+
FROM descendants
|
|
496
|
+
JOIN tasks child INDEXED BY idx_tasks_parent_task_id
|
|
497
|
+
ON child.parent_task_id = descendants.task_id
|
|
498
|
+
WHERE descendants.depth < ${qo}
|
|
499
|
+
),
|
|
500
|
+
delegated_ids(task_id) AS (
|
|
501
|
+
SELECT DISTINCT descendants.task_id
|
|
502
|
+
FROM descendants
|
|
503
|
+
WHERE descendants.depth > 0
|
|
504
|
+
AND NOT EXISTS (
|
|
505
|
+
SELECT 1 FROM own_tasks own
|
|
506
|
+
WHERE own.task_id = descendants.task_id
|
|
507
|
+
)
|
|
508
|
+
)
|
|
509
|
+
SELECT
|
|
510
|
+
count(*) AS cnt,
|
|
511
|
+
COALESCE(SUM(task.input_tokens), 0) AS total_input,
|
|
512
|
+
COALESCE(SUM(task.output_tokens), 0) AS total_output,
|
|
513
|
+
COALESCE(SUM(task.cached_input_tokens), 0) AS total_cached,
|
|
514
|
+
COALESCE(SUM(task.cost_usd), 0) AS total_cost
|
|
515
|
+
FROM delegated_ids
|
|
516
|
+
JOIN tasks task ON task.id = delegated_ids.task_id
|
|
517
|
+
`);D&&(u+=D.cnt,f+=D.total_input,l+=D.total_output,g+=D.total_cached,_+=D.total_cost);let y=T.db.all(drizzleOrm.sql`
|
|
518
|
+
SELECT DISTINCT child.agent_id FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
519
|
+
WHERE child.thread_id = ${e}
|
|
271
520
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
521
|
+
AND child.agent_id != 'workflow'
|
|
272
522
|
AND ${this.topLevelTaskPredicateSql()}
|
|
273
|
-
${
|
|
274
|
-
`);for(let
|
|
523
|
+
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
524
|
+
`);for(let b of y)m.add(b.agent_id);}catch(E){throw new exports.RepositoryError("DB_ERROR","Failed to aggregate task stats",E)}finally{T.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:d,costUsd:c,agentIds:Array.from(m),delegated:{taskCount:u,inputTokens:f,outputTokens:l,cachedInputTokens:g,costUsd:_}}}getDescendantSummaryByTaskId(e,n){let r=this.resolveDbPaths(),o={},s=new Date().toISOString();for(let i of r){if(!Sd.existsSync(i))continue;let d=N(i);try{let c=drizzleOrm.sql`
|
|
525
|
+
SELECT own.id
|
|
526
|
+
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
527
|
+
WHERE own.thread_id = ${e}
|
|
528
|
+
${n?drizzleOrm.sql`AND own.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
529
|
+
`,u=d.db.all(drizzleOrm.sql`
|
|
530
|
+
${this.descendantTraversalSql(c,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,qo)}
|
|
531
|
+
SELECT
|
|
532
|
+
descendant_ids.root_task_id AS root_task_id,
|
|
533
|
+
task.status AS status,
|
|
534
|
+
task.error AS error,
|
|
535
|
+
task.metadata AS metadata,
|
|
536
|
+
count(*) AS task_count
|
|
537
|
+
FROM descendant_ids
|
|
538
|
+
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
539
|
+
WHERE NOT ${this.descendantSkippedSql("task")}
|
|
540
|
+
GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
|
|
541
|
+
`);for(let f of u){let l=o[f.root_task_id]??=Vu(s);Ju(l,st(f),wt(f),f.task_count);}}catch(c){throw new exports.RepositoryError("DB_ERROR","Failed to aggregate task descendant summaries",c)}finally{d.close();}}return o}listDescendantsByTaskId(e,n,r={}){let o=new Set(r.states??Sm),s=Ku(r.limit,zu,zu),i=Ku(r.maxDepth,qo,qo),d=r.cursor?Am(r.cursor):void 0;for(let c of this.resolveDbPaths()){if(!Sd.existsSync(c))continue;let u=N(c);try{if(!u.db.get(drizzleOrm.sql`
|
|
542
|
+
SELECT anchor.id FROM tasks anchor
|
|
543
|
+
WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
|
|
544
|
+
`))continue;let l=drizzleOrm.sql`
|
|
545
|
+
SELECT own.id
|
|
546
|
+
FROM tasks own INDEXED BY idx_tasks_thread_id
|
|
547
|
+
WHERE own.thread_id = (
|
|
548
|
+
SELECT anchor.thread_id FROM tasks anchor
|
|
549
|
+
WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
|
|
550
|
+
)
|
|
551
|
+
AND own.workspace_id = ${n}
|
|
552
|
+
`,g=u.db.all(drizzleOrm.sql`
|
|
553
|
+
${this.descendantTraversalSql(l,drizzleOrm.sql`SELECT ${e}`,i)}
|
|
554
|
+
SELECT
|
|
555
|
+
task.id AS task_id,
|
|
556
|
+
task.parent_task_id AS parent_task_id,
|
|
557
|
+
task.status AS status,
|
|
558
|
+
task.error AS error,
|
|
559
|
+
task.metadata AS metadata,
|
|
560
|
+
task.started_at AS started_at,
|
|
561
|
+
descendant_ids.depth AS depth,
|
|
562
|
+
parent.agent_id AS parent_agent_id,
|
|
563
|
+
CASE
|
|
564
|
+
WHEN descendant_ids.depth >= ${i}
|
|
565
|
+
AND EXISTS (
|
|
566
|
+
SELECT 1 FROM tasks deeper INDEXED BY idx_tasks_parent_task_id
|
|
567
|
+
WHERE deeper.parent_task_id = task.id
|
|
568
|
+
)
|
|
569
|
+
THEN 1 ELSE 0
|
|
570
|
+
END AS has_deeper,
|
|
571
|
+
CASE WHEN ${this.descendantSkippedSql("task")} THEN 1 ELSE 0 END AS skipped
|
|
572
|
+
FROM descendant_ids
|
|
573
|
+
JOIN tasks task ON task.id = descendant_ids.task_id
|
|
574
|
+
LEFT JOIN tasks parent ON parent.id = task.parent_task_id
|
|
575
|
+
`),_=Vu(new Date().toISOString()),m=!1,k=[];for(let b of g){if(b.has_deeper&&(m=!0),b.skipped)continue;let O=st(b);Ju(_,O,wt(b),1),o.has(O)&&k.push({row:b,key:[bm(O),b.started_at?b.started_at:null,b.task_id]});}k.sort((b,O)=>Gu(b.key,O.key));let T=d?k.filter(b=>Gu(b.key,d)>0):k,E=T.slice(0,s),S=T.length>E.length?Im(E[E.length-1].key):null,D=new Map;if(E.length>0){let b=u.db.select(exports.taskRowColumns).from(exports.tasks).where(drizzleOrm.inArray(exports.tasks.id,E.map(O=>O.row.task_id))).all();for(let O of b)D.set(O.id,Rr(O));}let y=[];for(let{row:b}of E){let O=D.get(b.task_id);!O||!b.parent_task_id||y.push({task:O,parentTaskId:b.parent_task_id,parentAgentId:b.parent_agent_id,depth:b.depth});}return {rows:y,summary:_,nextCursor:S,traversalTruncated:m}}catch(f){throw f instanceof exports.RepositoryError?f:new exports.RepositoryError("DB_ERROR","Failed to list task descendants",f)}finally{u.close();}}}findTopLevelTasks(e,n,r,o){let s=this.resolveDbPaths(),i=o?drizzleOrm.sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${o})`:this.topLevelTaskPredicateSql(),d=new Set,c=[];for(let u of s){if(!Sd.existsSync(u))continue;let f=N(u);try{let l;r!==void 0?l=f.db.all(drizzleOrm.sql`
|
|
275
576
|
SELECT * FROM (
|
|
276
577
|
SELECT child.*,
|
|
277
578
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
278
579
|
FROM tasks child
|
|
279
|
-
WHERE child.thread_id = ${
|
|
280
|
-
AND ${
|
|
281
|
-
${
|
|
580
|
+
WHERE child.thread_id = ${e}
|
|
581
|
+
AND ${i}
|
|
582
|
+
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
282
583
|
) ranked
|
|
283
|
-
WHERE rn <= ${
|
|
584
|
+
WHERE rn <= ${r}
|
|
284
585
|
ORDER BY started_at ASC
|
|
285
|
-
`):
|
|
586
|
+
`):l=f.db.all(drizzleOrm.sql`
|
|
286
587
|
SELECT child.* FROM tasks child
|
|
287
|
-
WHERE child.thread_id = ${
|
|
288
|
-
AND ${
|
|
289
|
-
${
|
|
588
|
+
WHERE child.thread_id = ${e}
|
|
589
|
+
AND ${i}
|
|
590
|
+
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
290
591
|
ORDER BY child.started_at ASC
|
|
291
|
-
`);for(let
|
|
292
|
-
SELECT child
|
|
293
|
-
|
|
592
|
+
`);for(let g of l)d.has(g.id)||(d.add(g.id),c.push(Rr(g)));}catch(l){throw new exports.RepositoryError("DB_ERROR","Failed to find top-level tasks",l)}finally{f.close();}}if(r!==void 0&&s.length>1){let u=new Map;for(let f of c){let l=f.agent_id??"";u.has(l)||u.set(l,[]),u.get(l).push(f);}c=[];for(let f of u.values())f.sort((l,g)=>(g.started_at??"").localeCompare(l.started_at??"")),c.push(...f.slice(0,r));c.sort((f,l)=>(f.started_at??"").localeCompare(l.started_at??""));}return c}findAllTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!Sd.existsSync(i))continue;let d=N(i);try{let c=drizzleOrm.eq(exports.tasks.thread_id,e),u=n?drizzleOrm.and(c,drizzleOrm.eq(exports.tasks.workspace_id,n)):c,f=d.db.select(exports.taskRowColumns).from(exports.tasks).where(u).orderBy(drizzleOrm.asc(exports.tasks.started_at)).all();for(let l of f)o.has(l.id)||(o.add(l.id),s.push(Rr(l)));}catch(c){throw new exports.RepositoryError("DB_ERROR","Failed to find all tasks for thread",c)}finally{d.close();}}return s}findRespondedAgents(e,n){let r=this.resolveDbPaths(),o=new Map;for(let s of r){if(!Sd.existsSync(s))continue;let i=N(s,{readOnly:true});try{let d=[drizzleOrm.eq(exports.tasks.thread_id,e),drizzleOrm.sql`${exports.tasks.completed_at} IS NOT NULL`,drizzleOrm.sql`length(trim(coalesce(${exports.tasks.result}, ''))) > 0`];n&&d.push(drizzleOrm.eq(exports.tasks.workspace_id,n));let c=i.db.select({agentId:exports.tasks.agent_id,lastRepliedAt:drizzleOrm.sql`MAX(${exports.tasks.completed_at})`}).from(exports.tasks).where(drizzleOrm.and(...d)).groupBy(exports.tasks.agent_id).all();for(let u of c){let f=o.get(u.agentId);u.lastRepliedAt&&(!f||u.lastRepliedAt>f)&&o.set(u.agentId,u.lastRepliedAt);}}catch(d){throw new exports.RepositoryError("DB_ERROR","Failed to find responded agents for thread",d)}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(!Sd.existsSync(s))continue;let i=N(s);try{let d=drizzleOrm.and(drizzleOrm.eq(exports.tasks.id,n),drizzleOrm.eq(exports.tasks.thread_id,e)),c=r?drizzleOrm.and(d,drizzleOrm.eq(exports.tasks.workspace_id,r)):d,u=i.db.select(exports.taskRowColumns).from(exports.tasks).where(c).limit(1).get();if(!u)continue;let f=i.db.select(exports.taskRowColumns).from(exports.tasks).where(drizzleOrm.eq(exports.tasks.parent_task_id,u.id)).orderBy(drizzleOrm.asc(exports.tasks.started_at)).all().map(Rr);return {task:Rr(u),children:f}}catch(d){throw new exports.RepositoryError("DB_ERROR","Failed to find task by id",d)}finally{i.close();}}}batchFetchTasksQuery(e,n){return drizzleOrm.sql`
|
|
593
|
+
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
594
|
+
child.parent_task_id, child.started_at, child.completed_at,
|
|
595
|
+
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
596
|
+
child.cost_usd, child.error, child.rating, child.rated_at, child.metadata
|
|
597
|
+
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
598
|
+
WHERE child.thread_id IN (${drizzleOrm.sql.join(e.map(r=>drizzleOrm.sql`${r}`),drizzleOrm.sql`, `)})
|
|
294
599
|
AND ${this.topLevelTaskPredicateSql()}
|
|
295
|
-
${
|
|
600
|
+
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
296
601
|
ORDER BY child.started_at ASC
|
|
297
|
-
`}batchFetchTasks(
|
|
602
|
+
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!Sd.existsSync(s))continue;let i=N(s);try{let d=i.db.all(this.batchFetchTasksQuery(e,n));for(let c of d){let u=c.thread_id;r.has(u)||r.set(u,[]),r.get(u).push(Em(c));}}catch(d){throw new exports.RepositoryError("DB_ERROR","Failed to batch fetch tasks",d)}finally{i.close();}}return r}findThreadOriginsQuery(e,n){return drizzleOrm.sql`
|
|
603
|
+
WITH root AS (
|
|
604
|
+
SELECT child.thread_id, child.id, child.caller_agent_id, child.parent_task_id,
|
|
605
|
+
CASE
|
|
606
|
+
WHEN json_valid(child.metadata) = 1
|
|
607
|
+
THEN json_extract(child.metadata, '$.schedule_id')
|
|
608
|
+
ELSE NULL
|
|
609
|
+
END AS schedule_id,
|
|
610
|
+
child.platform,
|
|
611
|
+
ROW_NUMBER() OVER (
|
|
612
|
+
PARTITION BY child.thread_id
|
|
613
|
+
ORDER BY child.started_at ASC, child.id ASC
|
|
614
|
+
) AS rn
|
|
615
|
+
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
616
|
+
WHERE child.thread_id IN (${drizzleOrm.sql.join(e.map(r=>drizzleOrm.sql`${r}`),drizzleOrm.sql`, `)})
|
|
617
|
+
AND ${this.topLevelTaskPredicateSql("child","idx_tasks_thread_creator")}
|
|
618
|
+
${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
|
|
619
|
+
)
|
|
620
|
+
SELECT root.id AS task_id, root.thread_id, root.caller_agent_id, root.parent_task_id,
|
|
621
|
+
root.schedule_id, root.platform,
|
|
622
|
+
parent.thread_id AS parent_thread_id, parent.agent_id AS parent_agent_id
|
|
623
|
+
FROM root
|
|
624
|
+
LEFT JOIN tasks parent INDEXED BY idx_tasks_thread_creator
|
|
625
|
+
ON parent.id = root.parent_task_id
|
|
626
|
+
WHERE root.rn = 1
|
|
627
|
+
`}findCreatorPointersQuery(e,n){let r=[drizzleOrm.sql`thread.id IN (${drizzleOrm.sql.join(e.map(o=>drizzleOrm.sql`${o}`),drizzleOrm.sql`, `)})`];return n&&r.unshift(drizzleOrm.sql`thread.workspace_id = ${n}`),drizzleOrm.sql`
|
|
628
|
+
SELECT thread.id AS thread_id, thread.created_by_kind, thread.created_by_id,
|
|
629
|
+
thread.created_by_task_id,
|
|
630
|
+
creator.id AS creator_task_id,
|
|
631
|
+
creator.actor_kind AS creator_actor_kind,
|
|
632
|
+
creator.actor_id AS creator_actor_id,
|
|
633
|
+
CASE WHEN unverified.thread_id IS NULL THEN 0 ELSE 1 END AS creator_pointer_unverified
|
|
634
|
+
FROM threads AS thread
|
|
635
|
+
LEFT JOIN tasks AS creator INDEXED BY idx_tasks_thread_creator
|
|
636
|
+
ON creator.id = thread.created_by_task_id
|
|
637
|
+
AND creator.thread_id = thread.id
|
|
638
|
+
LEFT JOIN thread_creator_unverified AS unverified
|
|
639
|
+
ON unverified.thread_id = thread.id
|
|
640
|
+
AND unverified.created_by_task_id = thread.created_by_task_id
|
|
641
|
+
WHERE ${drizzleOrm.sql.join(r,drizzleOrm.sql` AND `)}
|
|
642
|
+
`}findTaskOriginLineageQuery(e){return drizzleOrm.sql`
|
|
643
|
+
SELECT child.id AS task_id, child.thread_id, child.caller_agent_id, child.parent_task_id,
|
|
644
|
+
CASE
|
|
645
|
+
WHEN json_valid(child.metadata) = 1
|
|
646
|
+
THEN json_extract(child.metadata, '$.schedule_id')
|
|
647
|
+
ELSE NULL
|
|
648
|
+
END AS schedule_id,
|
|
649
|
+
child.platform,
|
|
650
|
+
parent.thread_id AS parent_thread_id, parent.agent_id AS parent_agent_id
|
|
651
|
+
FROM tasks AS child
|
|
652
|
+
LEFT JOIN tasks AS parent ON parent.id = child.parent_task_id
|
|
653
|
+
WHERE child.id IN (${drizzleOrm.sql.join(e.map(n=>drizzleOrm.sql`${n}`),drizzleOrm.sql`, `)})
|
|
654
|
+
`}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!Sd.existsSync(s))continue;let i=N(s);try{for(let d=0;d<e.length;d+=Fo){let c=e.slice(d,d+Fo),f=i.db.all(this.findCreatorPointersQuery(c,n)).filter(S=>!r.has(S.thread_id)),l=f.filter(S=>S.creator_task_id!==null&&S.creator_pointer_unverified===0&&S.creator_actor_kind===null).map(S=>S.creator_task_id),g=l.length>0?i.db.all(this.findTaskOriginLineageQuery(l)):[],_=new Map(g.map(S=>[S.task_id,S])),m=new Map(f.map(S=>[S.thread_id,S])),k=c.filter(S=>{if(r.has(S))return !1;let D=m.get(S);return D?!(D.creator_task_id!==null&&D.creator_pointer_unverified===0)&&D.created_by_kind===null:!0}),T=k.length>0?i.db.all(this.findThreadOriginsQuery(k,n)):[],E=new Map(T.map(S=>[S.thread_id,S]));for(let S of f){if(r.has(S.thread_id))continue;let D=ju(S,S.created_by_task_id!==null?_.get(S.created_by_task_id):void 0,E.get(S.thread_id));D&&r.set(S.thread_id,D);}for(let S of T)r.has(S.thread_id)||m.has(S.thread_id)||r.set(S.thread_id,Uo(S));}}catch(d){throw new exports.RepositoryError("DB_ERROR","Failed to fetch thread origins",d)}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(d=>Yu(o.get(d),e));return this.readThreadRowsByIds(s,n,"Failed to find threads by origin").sort(Qu)}findRecentDirectThreads(e,n=5){if(typeof e!="string"||e.trim().length===0)throw new exports.RepositoryError("VALIDATION","workspaceId is required");if(!Number.isInteger(n)||n<=0)throw new exports.RepositoryError("VALIDATION","limit must be a positive integer");let r=this.readThreadSortKeys(e).sort(Qu),o=[],s=new Map;for(let u=0;u<r.length;u+=Xu){let f=r.slice(u,u+Xu),l=this.findThreadOrigins(f.map(g=>g.id),e);for(let[g,_]of l)s.set(g,_);for(let g of f)if(Yu(l.get(g.id),"direct")&&(o.push(g.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 f of u)i.set(f.id,f);}let d=[],c=new Map;for(let u of o){let f=i.get(u);if(!f)continue;d.push(f);let l=s.get(u);l&&c.set(u,l);}return {threads:d,originsByThread:c}}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!Sd.existsSync(o))continue;let s=N(o);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(d=>d.detail)}finally{s.close();}}return []}explainFindThreadOriginsPlan(e,n){if(e.length===0)return [];let r=this.resolveDbPaths();for(let o of r){if(!Sd.existsSync(o))continue;let s=N(o);try{let i=s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery(e,n)}`),d=s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery(e)}`),c=s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery(e,n)}`);return [...i,...d,...c].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(!Sd.existsSync(s))continue;let i=N(s);try{let d=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadIdsQuery(n)}`),c=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery([r],n)}`),u=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery([r])}`),f=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery([r],n)}`);return [...d,...c,...u,...f].map(l=>l.detail)}finally{i.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=drizzleOrm.eq(w.id,e),i=r?drizzleOrm.and(s,drizzleOrm.eq(w.workspace_id,r)):s;if(!o.db.select({id:w.id}).from(w).where(i).limit(1).get())return;o.db.update(w).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(w.id,e)).run();}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("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:P.id}).from(P).where(drizzleOrm.eq(P.id,n.workspaceId)).limit(1).get():void 0)?n.workspaceId:null,d=new Date().toISOString(),c=o.select({id:w.id,message_count:w.message_count,created_by_task_id:w.created_by_task_id}).from(w).where(drizzleOrm.eq(w.id,e)).limit(1).get();if(c){let u={updated_at:d};n.title!==void 0&&(u.title=n.title),n.titleLocked!==void 0&&(u.title_locked=n.titleLocked?1:0),c.created_by_task_id===null&&n.createdByTaskId!=null&&c.message_count===0&&!Zu(o,e,n.createdByTaskId)&&(u.created_by_task_id=n.createdByTaskId),o.update(w).set(u).where(drizzleOrm.eq(w.id,e)).run();}else o.insert(w).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:d,updated_at:d}).run();},{behavior:"immediate"});}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("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 c=(r?i.select({id:P.id}).from(P).where(drizzleOrm.eq(P.id,r)).limit(1).get():void 0)?r:null,u=i.select({id:w.id,platform:w.platform,workspace_id:w.workspace_id,message_count:w.message_count,created_by_task_id:w.created_by_task_id}).from(w).where(drizzleOrm.eq(w.id,e)).limit(1).get();if(u){let l={};c&&!u.workspace_id&&(l.workspace_id=c),u.created_by_task_id===null&&o?.createdByTaskId!=null&&u.message_count===0&&!Zu(i,e,o.createdByTaskId)&&(l.created_by_task_id=o.createdByTaskId),Object.keys(l).length>0&&i.update(w).set(l).where(drizzleOrm.eq(w.id,e)).run();return}let f=new Date().toISOString();i.insert(w).values({id:e,platform:n,workspace_id:c,created_by_kind:null,created_by_id:null,created_by_task_id:o?.createdByTaskId??null,message_count:0,created_at:f,updated_at:f}).run();},{behavior:"immediate"});}catch(i){throw i instanceof exports.RepositoryError?i:new exports.RepositoryError("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(d=>{let u=d.select({message_count:w.message_count}).from(w).where(drizzleOrm.eq(w.id,e)).limit(1).get()?.message_count===0;return d.run(drizzleOrm.sql`
|
|
298
655
|
UPDATE threads
|
|
299
|
-
SET first_message = COALESCE(first_message, ${
|
|
300
|
-
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${
|
|
301
|
-
last_message = ${
|
|
656
|
+
SET first_message = COALESCE(first_message, ${n}),
|
|
657
|
+
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
658
|
+
last_message = ${n},
|
|
302
659
|
message_count = message_count + 1,
|
|
303
|
-
updated_at = ${
|
|
304
|
-
WHERE id = ${
|
|
305
|
-
`),c},{behavior:"immediate"})}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:o}).where(drizzleOrm.eq(p.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save assistant message",o)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(drizzleOrm.eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),o=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!o)return null;let i=o.pinned?0:1,l=o.metadata?JSON.parse(o.metadata):{};if(i){let u=e?drizzleOrm.and(drizzleOrm.eq(p.pinned,1),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),_=0;for(let m of c){let f=m.metadata?JSON.parse(m.metadata):{};typeof f.pinOrder=="number"&&f.pinOrder>_&&(_=f.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let o=e?drizzleOrm.and(drizzleOrm.eq(p.id,t[r]),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t[r]),i=n.db.select({metadata:p.metadata}).from(p).where(o).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(o).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),o=n.db.select({starred:p.starred}).from(p).where(r).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(p).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let l=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t);return i.db.transaction(c=>{let _=c.select({metadata:p.metadata}).from(p).where(l).get();if(!_)return null;let m=_.metadata?JSON.parse(_.metadata):{},f=m.overdrive??{},R=r?.defaultTurns??f.defaultTurns??3,q=r?.updatedBy??"ui",z=new Date().toISOString(),C,y,B,ot;switch(n){case "enable-count":{let it=r?.turns??R,at=r?.consumeCurrent?Math.max(it-1,0):it;C=at>0?"count":"off",y=at,B=!0,ot="count";break}case "enable-latch":{C="latch",y=0,B=!0,ot="latch";break}case "disable":{C="off",y=0,B=!1;break}default:{let it=f.state??"off",at=typeof f.remaining=="number"?f.remaining:0;if(it==="count"&&at>0){let Ht=at-1;Ht<=0?(C="off",y=0):(C="count",y=Ht),B=!0,ot="count";}else it==="latch"?(C="latch",y=0,B=!0,ot="latch"):(C="off",y=0,B=!1);break}}return m.overdrive={state:C,remaining:y,defaultTurns:R,updatedAt:z,updatedBy:q},c.update(p).set({metadata:JSON.stringify(m),updated_at:z}).where(l).run(),{applied:B,appliedMode:ot,state:C,remaining:y}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Lt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(K).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(K).where(drizzleOrm.eq(K.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(K).where(drizzleOrm.eq(K.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var Pt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(F).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(F).where(drizzleOrm.eq(F.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:F.tool_name,count:drizzleOrm.sql`count(*)`}).from(F).where(drizzleOrm.eq(F.task_id,t)).groupBy(F.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var $t=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(I).where(drizzleOrm.eq(I.thread_id,t)).orderBy(drizzleOrm.asc(I.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(I).where(drizzleOrm.and(drizzleOrm.eq(I.id,e),drizzleOrm.eq(I.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(I).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(I).where(drizzleOrm.eq(I.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var It=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let o of t)r.insert(rt).values({id:crypto.randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:n,metadata:o.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(rt).orderBy(drizzleOrm.desc(rt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function ue(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Bt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=ue(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(A).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[A.provider,A.account_ref,A.limit_window,A.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:A.provider,bucket_start:A.bucket_start,used_percent:A.used_percent,remaining_percent:A.remaining_percent,resets_at:A.resets_at}).from(A).where(drizzleOrm.and(drizzleOrm.eq(A.limit_window,t.window),drizzleOrm.gte(A.bucket_start,t.fromIso),drizzleOrm.lte(A.bucket_start,t.toIso))).orderBy(drizzleOrm.asc(A.bucket_start)).all(),r=new Map;for(let o of n)r.has(o.provider)||r.set(o.provider,[]),r.get(o.provider).push({bucketStart:o.bucket_start,usedPercent:o.used_percent,remainingPercent:o.remaining_percent,resetsAt:o.resets_at??null});return Array.from(r.entries()).map(([o,i])=>({provider:o,points:i}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var Ut=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(v).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[v.workspace_id,v.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let n=e.db.select().from(v).where(drizzleOrm.and(drizzleOrm.eq(v.workspace_id,t.workspaceId),drizzleOrm.eq(v.month,t.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{e.close();}}findByMonth(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(v).where(drizzleOrm.and(drizzleOrm.eq(v.workspace_id,t),drizzleOrm.eq(v.month,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{n.close();}}listByWorkspace(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(v).where(drizzleOrm.eq(v.workspace_id,t)).orderBy(drizzleOrm.desc(v.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};exports.BaseSqliteRepository=S;exports.RepositoryError=d;exports.RequestLogRepository=It;exports.SpanRepository=Lt;exports.TaskRepository=Ct;exports.ThreadBoxRepository=$t;exports.ThreadRepository=vt;exports.ToolCallRepository=Pt;exports.UsageLimitSnapshotRepository=Bt;exports.UsageReportRepository=Ut;exports.WorkspaceRepository=At;exports.calcBucketStart=ue;exports.openDrizzleDb=w;exports.pushSchema=Ze;exports.runMigrations=nt;exports.runMigrationsOnce=D;exports.tasks=s;
|
|
660
|
+
updated_at = ${s}
|
|
661
|
+
WHERE id = ${e}
|
|
662
|
+
`),u},{behavior:"immediate"})}}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("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(w).set({last_message:n,updated_at:s}).where(drizzleOrm.eq(w.id,e)).run();}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("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(w).set(o).where(drizzleOrm.eq(w.id,e)).run();}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("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 on("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(c=>c!=="priority"&&c!=="state"))return new on("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 on("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let c of [i.priority,i.state])if(c!=null&&(typeof c!="string"||c.length===0))return new on("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let c=r?drizzleOrm.and(drizzleOrm.eq(w.id,e),drizzleOrm.eq(w.workspace_id,r)):drizzleOrm.eq(w.id,e);return d.db.transaction(u=>{let f=u.select({metadata:w.metadata}).from(w).where(c).get();if(!f)return null;let l=Fn(f.metadata),g=l.threadTitle,_=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};i.priority===null?delete _.priority:i.priority!==void 0&&(_.priority=i.priority),i.state===null?delete _.state:i.state!==void 0&&(_.state=i.state),Object.keys(_).length>0?l.threadTitle=_:delete l.threadTitle;let m=Object.keys(l).length>0?JSON.stringify(l):null,k=new Date().toISOString();u.update(w).set({metadata:m,updated_at:k}).where(c).run();let T=u.select({metadata:w.metadata}).from(w).where(c).get();if(!T)throw new exports.RepositoryError("DB_ERROR","Thread-title metadata update could not be read back");let E=vm(T.metadata);return {threadId:e,priority:E.priority,state:E.state}},{behavior:"immediate"})}catch(c){throw c instanceof exports.RepositoryError?c:new exports.RepositoryError("DB_ERROR","Failed to patch thread-title metadata",c)}finally{d.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(w.id,e),drizzleOrm.eq(w.workspace_id,n)):drizzleOrm.eq(w.id,e);return r.db.transaction(s=>{let i=s.select({pinned:w.pinned,metadata:w.metadata}).from(w).where(o).get();if(!i)return null;let d=i.pinned?0:1,c=Fn(i.metadata);if(d){let u=n?drizzleOrm.and(drizzleOrm.eq(w.pinned,1),drizzleOrm.eq(w.workspace_id,n)):drizzleOrm.eq(w.pinned,1),f=s.select({metadata:w.metadata}).from(w).where(u).all(),l=null;for(let g of f){let _=Fn(g.metadata);typeof _.pinOrder=="number"&&(l===null||_.pinOrder<l)&&(l=_.pinOrder);}c.pinOrder=l===null?0:l-1;}else delete c.pinOrder;return s.update(w).set({pinned:d,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(o).run(),{pinned:!!d}},{behavior:"immediate"})}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{for(let s=0;s<e.length;s++){let i=n?drizzleOrm.and(drizzleOrm.eq(w.id,e[s]),drizzleOrm.eq(w.workspace_id,n)):drizzleOrm.eq(w.id,e[s]),d=o.select({metadata:w.metadata}).from(w).where(i).get();if(!d)continue;let c=Fn(d.metadata);c.pinOrder=s+1,o.update(w).set({metadata:JSON.stringify(c)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?drizzleOrm.and(drizzleOrm.eq(w.id,e),drizzleOrm.eq(w.workspace_id,n)):drizzleOrm.eq(w.id,e),s=r.db.select({starred:w.starred}).from(w).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(w).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let d=n?drizzleOrm.and(drizzleOrm.eq(w.id,e),drizzleOrm.eq(w.workspace_id,n)):drizzleOrm.eq(w.id,e);return i.db.transaction(u=>{let f=u.select({metadata:w.metadata}).from(w).where(d).get();if(!f)return null;let l=f.metadata?JSON.parse(f.metadata):{},g=l.overdrive??{},_=o?.defaultTurns??g.defaultTurns??3,m=o?.updatedBy??"ui",k=new Date().toISOString(),T,E,S,D;switch(r){case "enable-count":{let y=o?.turns??_,b=o?.consumeCurrent?Math.max(y-1,0):y;T=b>0?"count":"off",E=b,S=!0,D="count";break}case "enable-latch":{T="latch",E=0,S=!0,D="latch";break}case "disable":{T="off",E=0,S=!1;break}default:{let y=g.state??"off",b=typeof g.remaining=="number"?g.remaining:0;if(y==="count"&&b>0){let O=b-1;O<=0?(T="off",E=0):(T="count",E=O),S=!0,D="count";}else y==="latch"?(T="latch",E=0,S=!0,D="latch"):(T="off",E=0,S=!1);break}}return l.overdrive={state:T,remaining:E,defaultTurns:_,updatedAt:k,updatedBy:m},u.update(w).set({metadata:JSON.stringify(l),updated_at:k}).where(d).run(),{applied:S,appliedMode:D,state:T,remaining:E}},{behavior:"immediate"})}catch(d){throw d instanceof exports.RepositoryError?d:new exports.RepositoryError("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};h();re();ue();_e();ie();fe();h();var tl=["urgent","high","medium","low"],nl=["investigating","in-progress","in-review","on-hold","done"],Er="custom:";var Nm=new Set(tl),xm=new Set(nl),Cm={urgent:"U \uAE34\uAE09 Urgent",high:"P0 \uAE09\uD568 High",medium:"P1 \uC911\uC694 Medium",low:"P2 \uBCF4\uD1B5 Low"},Hi={investigating:"\uC870\uC0AC\uC911 Looking into","in-progress":"\uC9C4\uD589\uC911 In progress","in-review":"\uAC80\uD1A0\uC911 In review","on-hold":"\uBCF4\uB958 On hold",done:"\uC644\uB8CC Done"};function el(t,e){return !e||e.includes(t)?e??t:`${t} ${e}`}function Sr(t){return typeof t=="string"&&Nm.has(t)}function br(t){if(typeof t!="string")return false;if(xm.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Er))return false;let e=t.slice(Er.length);return e.length>=1&&e.length<=20}function rl(t){if(t.startsWith(Er))return t.slice(Er.length)}function $i(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 Dm(t){let e=$i(t);return !!e&&Object.prototype.hasOwnProperty.call(e,"threadTitle")}function jo(t){let e=$i(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return Sr(r.priority)&&(o.priority=r.priority),br(r.state)&&(o.state=r.state),o}function Ui(t,e){let n=$i(t)??{},r={...jo(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)}function Pm(t,e=new Map){let n=[];return t.priority&&n.push(el(Cm[t.priority],e.get(t.priority))),t.state&&(t.state.startsWith(Er)?n.push(rl(t.state)??""):Hi[t.state]?n.push(el(Hi[t.state],e.get(t.state))):e.has(t.state)?n.push(t.state,e.get(t.state)??""):t.state.startsWith("c_")?n.push(t.state):n.push(Hi[t.state]??"")),n.filter(Boolean).join(" ")}function ol(t,e){if(!t||t.trim().length===0)return;let n=new Set,r=false,o=false;for(let s of t.split(",")){let i=s.trim();if(i){if(i==="none"){r=true,o=true;continue}e(i)&&(n.add(i),o=true);}}if(o)return {values:n,includeNone:r}}function Lm(t){return ol(t,Sr)}function Mm(t){return ol(t,br)}function Hm(t,e){return e?t?e.values.has(t):e.includeNone:true}fr();var cl="regeneration_replaced",Fm="THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS",ul="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED",jm="THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED",ll="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Ko=class extends exports.RepositoryError{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;}},zn=class extends Ko{},Vo=class extends exports.RepositoryError{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Wm=new Set(Ya),zm=new Set(Xa),Gm=new Set(Qa),Km=new Set(Za),Vm=50,il=100,al=280,dl=40,Jm=new Set(ed),Wo=["queued","running"];function qi(t){return Jm.has(t)}function Y(t){throw new exports.RepositoryError("VALIDATION",t)}function ut(t){throw new exports.RepositoryError("NOT_FOUND",t)}function $(t,e){(typeof t!="string"||t.trim().length===0)&&Y(`${e} is required`);}function Ar(t={}){let e=t.actor??t,n=e.actorType??"system";return Wm.has(n)||Y(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&Y("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Xm(t){$(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&$(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&Y("title must not be empty"),t.title.length>120&&Y("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Sr(t.priority)&&Y(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!br(t.state)&&Y(`invalid state: ${String(t.state)}`);}function Ym(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&Y("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)&&Y(`${n} must be a non-negative integer`);let e=t.limit??Vm;return (!Number.isInteger(e)||e<1||e>il)&&Y(`limit must be between 1 and ${il}`),e}function ji(t){typeof t!="string"&&Y("text is required");let e=t.trim();return e.length===0&&Y("text must not be empty"),e.length>al&&Y(`text must be at most ${al} characters`),e}function Nt(t,e){return $(t??"",e),t}function Wi(t){Km.has(t)||Y(`invalid highlight kind: ${String(t)}`);}function Qm(t){Gm.has(t)||Y(`invalid highlight source: ${String(t)}`);}function Zm(t){$(t.threadId,"threadId"),$(t.workspaceId,"workspaceId");let e=t.source??"manual";Qm(e),Wi(t.kind);let n=ji(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let f=t.taskId??(r&&o&&r===o?r:void 0),l=Nt(f,"taskId");return (r!==l||o!==l)&&Y("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:l,coversToTaskId:l,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Nt(r,"coversFromTaskId"),i=Nt(o,"coversToTaskId"),d=t.sourceTaskId??s,c=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),u=t.contentFingerprint??t.idempotencyKey??null;return Nt(d??void 0,"sourceTaskId"),Nt(c??void 0,"detectorVersion"),Nt(u??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:d,detectorVersion:c,contentFingerprint:u}}function ek(t,e){(!t||typeof t!="object")&&Y(`candidates[${e}] is required`),Wi(t.kind);let n=ji(t.text),r=Nt(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Nt(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Nt(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||gd("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return $(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function tk(t){Array.isArray(t)||Y("candidates must be an array"),t.length>dl&&Y(`candidates must contain at most ${dl} items`);let e=new Map;for(let[n,r]of t.entries()){let o=ek(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function xr(t){let e=jo(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 nk(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&Y("event payload must be a JSON object"),e}catch(e){throw new exports.RepositoryError("VALIDATION","event payload must be JSON serializable",e)}}function Or(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${K.seq}), 0)`}).from(K).where(drizzleOrm.eq(K.thread_id,e)).get()?.maxSeq??0}function vr(t,e){return !!t.select({id:K.id}).from(K).where(drizzleOrm.eq(K.thread_id,e)).limit(1).get()}function sn(t,e){zm.has(e.type)||Y(`invalid thread event type: ${String(e.type)}`);let n=je("the");t.insert(K).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:nk(e.payload),created_at:e.createdAt}).run();let r=t.select().from(K).where(drizzleOrm.eq(K.id,n)).get();if(!r)throw new exports.RepositoryError("DB_ERROR","Thread event insert did not return a row");return r}function Nr(t,e,n,r,o){let s=xr(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 Go(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 zo(t,e,n,r,o,s,i){let d=o==="thread.highlight.created"?Go(e):{before:i?Go({...e,...i,id:e.id}):void 0,after:Go(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:d})}function rk(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:Go(e),...s??{}}})}var Fi=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=drizzleOrm.eq(w.id,n),s=r===void 0?o:r===null?drizzleOrm.and(o,drizzleOrm.isNull(w.workspace_id)):drizzleOrm.and(o,drizzleOrm.eq(w.workspace_id,r));return e.select().from(w).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(F).where(drizzleOrm.eq(F.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if($(e,"threadId"),!Sd.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:w.workspace_id}).from(w).where(drizzleOrm.eq(w.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if($(e,"threadId"),!Sd.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?xr(o):null}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Xm(e);let n=Ar(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||ut(`Thread ${e.threadId} not found`);let d=xr(i),c=e.title!==void 0,u=c&&e.title!==d.title,f=c&&i.title_locked!==1,l=e.priority!==void 0&&e.priority!==d.priority,g=e.state!==void 0&&e.state!==d.state,_=u||l||g;if(!_&&!f)return d;let m=i.metadata;(l||g)&&(m=Ui(i.metadata,{priority:e.priority,state:e.state}));let k={};if(_&&(k.metadata=m,k.updated_at=r),u&&(k.title=e.title),c&&(k.title_locked=1),s.update(w).set(k).where(e.workspaceId===void 0?drizzleOrm.eq(w.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(w.id,e.threadId),drizzleOrm.isNull(w.workspace_id)):drizzleOrm.and(drizzleOrm.eq(w.id,e.threadId),drizzleOrm.eq(w.workspace_id,e.workspaceId))).run(),!_){let S={...i,title_locked:1};return xr(S)}let T=Or(s,i.id)+1;vr(s,i.id)||(Nr(s,i,n,r,T),T+=1),u&&(sn(s,{threadId:i.id,seq:T,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),T+=1),l&&(sn(s,{threadId:i.id,seq:T,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),T+=1),g&&sn(s,{threadId:i.id,seq:T,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let E={...i,title:u?e.title:i.title,metadata:m,title_locked:c?1:i.title_locked,updated_at:r};return xr(E)},{behavior:"immediate"})}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("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($(e,"threadId"),!Sd.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${K.seq}), 0)`}).from(K).where(drizzleOrm.eq(K.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if($(e,"threadId"),$(n,"workspaceId"),!Sd.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:exports.tasks.id,prompt:exports.tasks.prompt,result:exports.tasks.result,status:exports.tasks.status,startedAt:exports.tasks.started_at,completedAt:exports.tasks.completed_at}).from(exports.tasks).where(drizzleOrm.and(drizzleOrm.eq(exports.tasks.thread_id,e),drizzleOrm.eq(exports.tasks.workspace_id,n),drizzleOrm.inArray(exports.tasks.status,[...exports.TASK_TERMINAL_STORED_STATUSES]),drizzleOrm.or(drizzleOrm.isNull(exports.tasks.parent_task_id),drizzleOrm.eq(exports.tasks.parent_task_id,"")),drizzleOrm.sql`${exports.tasks.result} IS NOT NULL AND length(trim(${exports.tasks.result})) > 0`)).orderBy(drizzleOrm.asc(exports.tasks.started_at),drizzleOrm.asc(exports.tasks.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 exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.requestId,"requestId"),$(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&$(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||ut(`Thread ${e.threadId} not found`);let i=o.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.thread_id,s.id),drizzleOrm.eq(F.request_id,e.requestId))).orderBy(drizzleOrm.desc(F.requested_at),drizzleOrm.desc(F.id)).limit(1).get();if(i)return {run:i,created:!1};let d=o.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.thread_id,s.id),drizzleOrm.inArray(F.status,Wo))).orderBy(drizzleOrm.asc(F.requested_at),drizzleOrm.asc(F.id)).limit(1).get();if(d)throw new Vo(d);let c=e.runId??je("thr");o.insert(F).values({id:c,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(F).where(drizzleOrm.eq(F.id,c)).get();if(!u)throw new exports.RepositoryError("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:u,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("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($(e,"runId"),n!==void 0&&$(n,"workspaceId"),!Sd.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if($(e,"threadId"),$(n,"workspaceId"),$(r,"requestId"),!Sd.existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.thread_id,e),drizzleOrm.eq(F.request_id,r))).orderBy(drizzleOrm.desc(F.requested_at),drizzleOrm.desc(F.id)).limit(1).get()??null:null}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("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){$(e,"runId"),n!==void 0&&$(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||ut(`Highlight regeneration run ${e} not found`),qi(i.status)||Y(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(F).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(F.id,i.id),drizzleOrm.eq(F.status,"queued"))).run();let d=s.select().from(F).where(drizzleOrm.eq(F.id,i.id)).get();if(!d)throw new exports.RepositoryError("DB_ERROR","Highlight regeneration run start did not return a row");return d},{behavior:"immediate"})}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){$(e.runId,"runId"),$(e.errorCode,"errorCode"),e.workspaceId!==void 0&&$(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||ut(`Highlight regeneration run ${e.runId} not found`),qi(s.status)||Y(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(F).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(F.id,s.id),drizzleOrm.inArray(F.status,Wo))).run();let i=o.select().from(F).where(drizzleOrm.eq(F.id,s.id)).get();if(!i)throw new exports.RepositoryError("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=ul){$(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(F).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(F.status,Wo)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){$(e.runId,"runId"),$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.detectorVersion,"detectorVersion");let n=tk(e.candidates),r=Ar(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let d=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!d||d.thread_id!==e.threadId)&&ut(`Highlight regeneration run ${e.runId} not found`),qi(d.status)||Y(`invalid highlight regeneration status: ${d.status}`),d.status==="failed")throw new exports.RepositoryError("CONFLICT","Highlight regeneration run has already failed");if(d.status==="completed")return {run:d,deletedCount:0,createdCount:0,previousAutoCount:d.previous_auto_count??0,newAutoCount:d.new_auto_count??0};s=!0;let c=this.findThread(i,e.threadId,e.workspaceId);c||ut(`Thread ${e.threadId} not found`),d.detector_version!==e.detectorVersion&&Y("detectorVersion does not match the regeneration run");let u=i.select().from(U).where(drizzleOrm.eq(U.thread_id,c.id)).orderBy(drizzleOrm.asc(U.created_at),drizzleOrm.asc(U.id)).all(),f=new Set(n.map(O=>O.contentFingerprint)),l=u.filter(O=>O.source==="auto"&&O.status==="active"&&O.revision===0&&!f.has(O.content_fingerprint??"")),g=u.filter(O=>O.source==="auto"&&O.status==="active").length,_=new Set(u.filter(O=>!l.includes(O)&&O.content_fingerprint).map(O=>O.content_fingerprint)),m=n.filter(O=>!_.has(O.contentFingerprint)),k=new Date().toISOString(),T=Or(i,c.id)+1;vr(i,c.id)||(Nr(i,c,r,k,T),T+=1);for(let O of l)i.delete(U).where(drizzleOrm.eq(U.id,O.id)).run(),rk(i,O,r,k,T,{runId:e.runId,reason:cl}),T+=1;let E=0,S=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let O of m){let ne=je("thl");i.insert(U).values({id:ne,thread_id:c.id,source:"auto",kind:O.kind,status:"active",text:O.text,covers_from_task_id:O.coversFromTaskId,covers_to_task_id:O.coversToTaskId,revision:0,created_at:k,updated_at:k,agent_id:S,source_task_id:O.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:O.contentFingerprint,dismissed_at:null}).run();let se=i.select().from(U).where(drizzleOrm.eq(U.id,ne)).get();if(!se)throw new exports.RepositoryError("DB_ERROR","Regenerated highlight insert did not return a row");zo(i,se,r,k,"thread.highlight.created",T),T+=1,E+=1;}let y=i.select().from(U).where(drizzleOrm.eq(U.thread_id,c.id)).all().filter(O=>O.source==="auto"&&O.status==="active").length;sn(i,{threadId:c.id,seq:T,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:d.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:y,deletedCount:l.length,createdCount:E}}),i.update(F).set({status:"completed",started_at:d.started_at??k,completed_at:k,error_code:null,previous_auto_count:g,new_auto_count:y}).where(drizzleOrm.and(drizzleOrm.eq(F.id,d.id),drizzleOrm.inArray(F.status,Wo))).run();let b=i.select().from(F).where(drizzleOrm.eq(F.id,d.id)).get();if(!b)throw new exports.RepositoryError("DB_ERROR","Highlight regeneration completion did not return a row");return {run:b,deletedCount:l.length,createdCount:E,previousAutoCount:g,newAutoCount:y}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:ll});}catch{}throw i instanceof exports.RepositoryError?i:new exports.RepositoryError("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;$(o.threadId,"threadId"),$(o.workspaceId,"workspaceId");let s=Ym(o);if(!Sd.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let d=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${K.seq}), 0)`}).from(K).where(drizzleOrm.eq(K.thread_id,o.threadId)).get()?.maxSeq??0,c;o.beforeSeq!==void 0?c=i.db.select().from(K).where(drizzleOrm.and(drizzleOrm.eq(K.thread_id,o.threadId),drizzleOrm.lt(K.seq,o.beforeSeq))).orderBy(drizzleOrm.desc(K.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?c=i.db.select().from(K).where(drizzleOrm.and(drizzleOrm.eq(K.thread_id,o.threadId),drizzleOrm.sql`${K.seq} > ${o.afterSeq}`)).orderBy(drizzleOrm.asc(K.seq)).limit(s+1).all():c=i.db.select().from(K).where(drizzleOrm.eq(K.thread_id,o.threadId)).orderBy(drizzleOrm.desc(K.seq)).limit(s+1).all().reverse();let u=c.length>s,f=o.afterSeq!==void 0?c.slice(0,s):u?c.slice(1):c,l=!1,g=f[0];return g&&(l=!!i.db.select({id:K.id}).from(K).where(drizzleOrm.and(drizzleOrm.eq(K.thread_id,o.threadId),drizzleOrm.lt(K.seq,g.seq))).limit(1).get()),{items:f,latestSeq:d,hasMoreOlder:l}}catch(d){throw d instanceof exports.RepositoryError?d:new exports.RepositoryError("DB_ERROR","Failed to list thread timeline",d)}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=Zm(e),r=Ar(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);if(d||ut(`Thread ${e.threadId} not found`),n.source==="auto"){let g=i.select().from(U).where(drizzleOrm.and(drizzleOrm.eq(U.thread_id,e.threadId),drizzleOrm.eq(U.source_task_id,n.sourceTaskId),drizzleOrm.eq(U.detector_version,n.detectorVersion),drizzleOrm.eq(U.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(U.created_at),drizzleOrm.asc(U.id)).limit(1).get();if(g)return g}let c=e.id??je("thl"),u={id:c,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(U).values(u).run();let f=i.select().from(U).where(drizzleOrm.eq(U.id,c)).get();if(!f)throw new exports.RepositoryError("DB_ERROR","Highlight insert did not return a row");let l=Or(i,d.id)+1;return vr(i,d.id)||(Nr(i,d,r,o,l),l+=1),zo(i,f,r,o,"thread.highlight.created",l),f},{behavior:"immediate"})}catch(i){throw i instanceof exports.RepositoryError?i:new exports.RepositoryError("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Y("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&Y("highlight update requires at least one field"),e.kind!==void 0&&Wi(e.kind);let n=e.text===void 0?void 0:ji(e.text),r=Ar(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);d||ut(`Thread ${e.threadId} not found`);let c=i.select().from(U).where(drizzleOrm.and(drizzleOrm.eq(U.id,e.highlightId),drizzleOrm.eq(U.thread_id,d.id))).limit(1).get();if(c||ut(`Highlight ${e.highlightId} not found`),c.revision!==e.expectedRevision)throw new zn(d.id,c.id,e.expectedRevision,c.revision);if(c.status!=="active")throw new zn(d.id,c.id,e.expectedRevision,c.revision);let u=e.kind??c.kind,f=n??c.text,l=e.coversFromTaskId??c.covers_from_task_id,g=e.coversToTaskId??c.covers_to_task_id;(!f||l.length===0||g.length===0)&&Y("highlight projection is incomplete");let _=u!==c.kind||f!==c.text||l!==c.covers_from_task_id||g!==c.covers_to_task_id,m=r.actorType==="user"&&c.source==="auto"&&_?"manual":c.source;if(!(_||m!==c.source))return c;let T=c.revision+1;i.update(U).set({source:m,kind:u,text:f,covers_from_task_id:l,covers_to_task_id:g,revision:T,updated_at:o}).where(drizzleOrm.and(drizzleOrm.eq(U.id,c.id),drizzleOrm.eq(U.revision,c.revision))).run();let E=i.select().from(U).where(drizzleOrm.eq(U.id,c.id)).get();if(!E)throw new exports.RepositoryError("DB_ERROR","Highlight update did not return a row");let S=Or(i,d.id)+1;return vr(i,d.id)||(Nr(i,d,r,o,S),S+=1),zo(i,E,r,o,"thread.highlight.updated",S,c),E},{behavior:"immediate"})}catch(i){throw i instanceof exports.RepositoryError?i:new exports.RepositoryError("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&Y("expectedRevision must be a non-negative integer");let n=Ar(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||ut(`Thread ${e.threadId} not found`);let d=s.select().from(U).where(drizzleOrm.and(drizzleOrm.eq(U.id,e.highlightId),drizzleOrm.eq(U.thread_id,i.id))).limit(1).get();if(d||ut(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new zn(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let c=d.revision+1;s.update(U).set({status:"dismissed",text:null,revision:c,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(U.id,d.id),drizzleOrm.eq(U.revision,d.revision))).run();let u=s.select().from(U).where(drizzleOrm.eq(U.id,d.id)).get();if(!u)throw new exports.RepositoryError("DB_ERROR","Highlight dismissal did not return a row");let f=Or(s,i.id)+1;return vr(s,i.id)||(Nr(s,i,n,r,f),f+=1),zo(s,u,n,r,"thread.highlight.deleted",f,d),u},{behavior:"immediate"})}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if($(e,"threadId"),$(n,"workspaceId"),r.taskId!==void 0&&$(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&$(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&$(r.coversToTaskId,"coversToTaskId"),!Sd.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(U).where(drizzleOrm.and(drizzleOrm.eq(U.thread_id,e),drizzleOrm.eq(U.status,"active"))).orderBy(drizzleOrm.asc(U.created_at),drizzleOrm.asc(U.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(drizzleOrm.sql`
|
|
663
|
+
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
664
|
+
ORDER BY started_at ASC, id ASC
|
|
665
|
+
`),c=new Map(d.map((g,_)=>[g.id,_])),u=r.taskId===void 0?void 0:c.get(r.taskId),f=r.coversFromTaskId===void 0?void 0:c.get(r.coversFromTaskId),l=r.coversToTaskId===void 0?void 0:c.get(r.coversToTaskId);return i.filter(g=>{let _=c.get(g.covers_from_task_id),m=c.get(g.covers_to_task_id);if(_===void 0||m===void 0)return !1;let k=Math.min(_,m),T=Math.max(_,m);return !(u!==void 0&&(u<k||u>T)||f!==void 0&&T<f||l!==void 0&&k>l)})}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("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)}};h();re();ue();_e();ie();fe();var zi=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}insertSpan(e){let n=this.openHandle(true);try{n.db.insert(It).values(e).run();}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to insert span",r)}finally{n.close();}}findByTaskId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(It).where(drizzleOrm.eq(It.task_id,e)).all()}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to find spans by task id",r)}finally{n.close();}}findById(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(It).where(drizzleOrm.eq(It.id,e)).limit(1).get()??void 0}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to find span by id",r)}finally{n.close();}}};h();re();ue();_e();ie();fe();var Gi=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}insertToolCall(e){let n=this.openHandle(true);try{n.db.insert(gt).values(e).run();}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to insert tool call",r)}finally{n.close();}}findByTaskId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(gt).where(drizzleOrm.eq(gt.task_id,e)).all()}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to find tool calls by task id",r)}finally{n.close();}}aggregateByName(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select({toolName:gt.tool_name,count:drizzleOrm.sql`count(*)`}).from(gt).where(drizzleOrm.eq(gt.task_id,e)).groupBy(gt.tool_name).all().map(r=>({toolName:r.toolName,count:r.count}))}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to aggregate tool calls by name",r)}finally{n.close();}}};h();re();ue();_e();ie();fe();var Ki=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}ensureThreadExists(e,n){if(!e.db.select({id:w.id}).from(w).where(drizzleOrm.eq(w.id,n)).limit(1).get())throw new exports.RepositoryError("NOT_FOUND",`Thread not found: ${n}`)}findByThreadId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return this.ensureThreadExists(n,e),n.db.select().from(Je).where(drizzleOrm.eq(Je.thread_id,e)).orderBy(drizzleOrm.asc(Je.seq)).all()}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to find boxes by thread id",r)}finally{n.close();}}findById(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(Je).where(drizzleOrm.and(drizzleOrm.eq(Je.id,n),drizzleOrm.eq(Je.thread_id,e))).limit(1).get()??void 0}catch(o){throw o instanceof exports.RepositoryError?o:new exports.RepositoryError("DB_ERROR","Failed to find box by id",o)}finally{r.close();}}insert(e){let n=this.openHandle(true);try{this.ensureThreadExists(n,e.threadId);try{n.db.insert(Je).values({id:e.id,thread_id:e.threadId,seq:e.seq,first_task_id:e.first_task_id,mid_task_id:e.mid_task_id,last_task_id:e.last_task_id,task_count:e.task_count,summary:e.summary??null,source_tokens:e.source_tokens,summary_tokens:e.summary_tokens??null,created_at:e.created_at}).run();}catch(o){throw o instanceof Error&&/UNIQUE constraint failed/i.test(o.message)?new exports.RepositoryError("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let r=n.db.select().from(Je).where(drizzleOrm.eq(Je.id,e.id)).limit(1).get();if(!r)throw new exports.RepositoryError("DB_ERROR","Insert did not return a row");return r}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to insert thread box",r)}finally{n.close();}}};h();re();h();re();ue();ie();var kl="logs.db",Vi=1,wk=[`CREATE TABLE IF NOT EXISTS request_logs (
|
|
666
|
+
id TEXT PRIMARY KEY,
|
|
667
|
+
path TEXT NOT NULL,
|
|
668
|
+
method TEXT NOT NULL,
|
|
669
|
+
status_code INTEGER NOT NULL,
|
|
670
|
+
duration_ms INTEGER NOT NULL,
|
|
671
|
+
ip TEXT,
|
|
672
|
+
request_headers TEXT,
|
|
673
|
+
response_headers TEXT,
|
|
674
|
+
request_body_hash TEXT,
|
|
675
|
+
response_body_hash TEXT,
|
|
676
|
+
query TEXT,
|
|
677
|
+
user_id TEXT,
|
|
678
|
+
project_id TEXT,
|
|
679
|
+
partition_key TEXT NOT NULL,
|
|
680
|
+
timestamp TEXT NOT NULL,
|
|
681
|
+
metadata TEXT
|
|
682
|
+
)`,`CREATE TABLE IF NOT EXISTS request_log_bodies (
|
|
683
|
+
hash TEXT PRIMARY KEY,
|
|
684
|
+
body TEXT NOT NULL,
|
|
685
|
+
bytes INTEGER NOT NULL,
|
|
686
|
+
first_seen TEXT NOT NULL
|
|
687
|
+
)`,"CREATE INDEX IF NOT EXISTS idx_request_logs_timestamp_id ON request_logs (timestamp, id)","CREATE INDEX IF NOT EXISTS idx_request_logs_request_body_hash ON request_logs (request_body_hash)","CREATE INDEX IF NOT EXISTS idx_request_logs_response_body_hash ON request_logs (response_body_hash)"],Ji=class extends exports.BaseSqliteRepository{};function an(t){let e=t??new Ji().resolveDbPath();if(e===":memory:"||e==="")throw new exports.RepositoryError("VALIDATION","logs.db lives next to a file-backed crewx.db; CREWX_DB=:memory: has no directory for it. Set CREWX_DB to a file path.");return He(Ae.join(Ae.dirname(e),kl))}function Dr(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function yk(t){let e=t.db.$client;if(!e)throw new exports.RepositoryError("DB_ERROR","drizzle did not expose its better-sqlite3 client");return e}function Rk(t){t.pragma("user_version",{simple:true})>=Vi||t.transaction(()=>{for(let n of wk)t.exec(n);t.pragma(`user_version = ${Vi}`);}).immediate();}function Pr(t){let e=an(t),n=Ae.dirname(e);Sd.existsSync(n)||Sd.mkdirSync(n,{recursive:true});let r=N(e);try{let o=yk(r);return Rk(o),{path:e,sqlite:o,close:()=>r.close()}}catch(o){throw r.close(),o}}ie();var Xi=class extends exports.BaseSqliteRepository{dbPath;writer;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}resolveLogsDbPath(){return an(this.resolveDbPath())}ensureWriter(){let e=this.resolveLogsDbPath(),n=this.writer;if(n){try{let o=Sd.statSync(e);if(o.ino===n.ino&&o.dev===n.dev&&n.logs.path===e)return n}catch{}this.close();}let r=Pr(this.resolveDbPath());try{let{sqlite:o}=r,s=o.prepare("INSERT OR IGNORE INTO request_log_bodies (hash, body, bytes, first_seen) VALUES (?, ?, ?, ?)"),i=o.prepare(`INSERT INTO request_logs (
|
|
688
|
+
id, path, method, status_code, duration_ms, ip,
|
|
689
|
+
request_headers, response_headers, request_body_hash, response_body_hash,
|
|
690
|
+
query, user_id, project_id, partition_key, timestamp, metadata
|
|
691
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),d=o.transaction(f=>{let l=new Set;for(let g of f){for(let{hash:_,body:m}of g.bodies)l.has(_)||(l.add(_),s.run(_,m,Buffer.byteLength(m,"utf8"),g.firstSeen));i.run(...g.params);}}),c=Sd.statSync(r.path),u={logs:r,ino:c.ino,dev:c.dev,writeBatch:f=>d.immediate(f)};return this.writer=u,u}catch(o){throw r.close(),o}}bulkInsert(e){if(e.length===0)return;let n=this.ensureWriter();try{n.writeBatch(e.map(r=>this.prepareRow(r)));}catch(r){throw this.close(),r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to bulk insert request logs",r)}}prepareRow(e){let n=e.timestamp??new Date().toISOString(),r=[],o=d=>{if(d==null)return null;let c=Dr(d);return r.push({hash:c,body:d}),c},s=o(e.requestBody),i=o(e.responseBody);return {firstSeen:n,bodies:r,params:[crypto.randomUUID(),e.path,e.method,e.statusCode,e.durationMs,e.ip??null,e.requestHeaders??null,e.responseHeaders??null,s,i,e.query??null,e.userId??null,e.projectId??null,e.partitionKey??"default",n,e.metadata??null]}}close(){let e=this.writer;this.writer=void 0,e?.logs.close();}};h();re();ue();ie();var Rl=250,El=8*1024*1024,Sl=2*exports.CREWX_JOURNAL_SIZE_LIMIT_BYTES,bl=5e3,Yo=class extends exports.BaseSqliteRepository{},bk=`
|
|
692
|
+
SELECT rowid AS rowid, id, path, method, status_code, duration_ms, ip,
|
|
693
|
+
request_headers, response_headers, request_body, response_body,
|
|
694
|
+
query, user_id, project_id, partition_key, timestamp, metadata
|
|
695
|
+
FROM request_logs
|
|
696
|
+
WHERE rowid > ?
|
|
697
|
+
ORDER BY rowid
|
|
698
|
+
LIMIT ?`;function Qi(t){let e=t.db.$client;if(!e)throw new exports.RepositoryError("DB_ERROR","drizzle did not expose its better-sqlite3 client");return e}function Il(t){try{return Sd.statSync(`${t}-wal`).size}catch{return 0}}function Xo(t,e){return t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Jo(t,e,n){if(t===void 0)return e;if(!Number.isSafeInteger(t)||t<1)throw new exports.RepositoryError("VALIDATION",`${n} must be a positive integer`);return t}function wl(t,e){let n=t[e];if(n==null)return null;if(typeof n!="string")throw new exports.RepositoryError("DB_ERROR",`request_logs row ${t.id} has a non-text ${e} (${typeof n}); not moved`);return n}function Ik(t,e){let n=[],r=new Map,o=0;for(let s of t){let i=wl(s,"request_body"),d=wl(s,"response_body"),c=0;for(let g of [s.request_headers,s.response_headers,s.query,s.metadata,s.path])c+=g?g.length:0;let u=[],f=[],l=[];for(let g of [i,d]){if(g===null){u.push(null);continue}let _=Buffer.byteLength(g,"utf8");c+=_;let m=Dr(g);u.push(m),f.push({hash:m,body:g,bytes:_,firstSeen:s.timestamp}),l.push({hash:m,bytes:_});}if(n.length>0&&o+c>e)break;o+=c;for(let g of f)r.has(g.hash)||r.set(g.hash,g);n.push({rowid:s.rowid,id:s.id,requestBodyHash:u[0],responseBodyHash:u[1],sourceBytes:c,bodies:l,params:[s.id,s.path,s.method,s.status_code,s.duration_ms,s.ip,s.request_headers,s.response_headers,u[0],u[1],s.query,s.user_id,s.project_id,s.partition_key,s.timestamp,s.metadata]});}return {rows:n,bodies:[...r.values()]}}function Ak(t,e){let n=t.prepare("SELECT request_body_hash AS req, response_body_hash AS res FROM request_logs WHERE id = ?"),r=t.prepare("SELECT 1 FROM request_log_bodies WHERE hash = ?");for(let o of e){let s=n.get(o.id);if(!s||s.req!==o.requestBodyHash||s.res!==o.responseBodyHash)throw new exports.RepositoryError("DB_ERROR",`logs.db does not hold request log ${o.id} as read; it stays in crewx.db`);for(let i of [o.requestBodyHash,o.responseBodyHash])if(i!==null&&r.get(i)===void 0)throw new exports.RepositoryError("DB_ERROR",`logs.db is missing body ${i} of request log ${o.id}; it stays in crewx.db`)}}function Ok(t){let e=Pr(t);try{let n=e.sqlite.prepare("INSERT OR IGNORE INTO request_log_bodies (hash, body, bytes, first_seen) VALUES (?, ?, ?, ?)"),r=e.sqlite.prepare(`INSERT OR IGNORE INTO request_logs (
|
|
699
|
+
id, path, method, status_code, duration_ms, ip,
|
|
700
|
+
request_headers, response_headers, request_body_hash, response_body_hash,
|
|
701
|
+
query, user_id, project_id, partition_key, timestamp, metadata
|
|
702
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),o=e.sqlite.transaction((s,i)=>{let d=0;for(let c of i)d+=n.run(c.hash,c.body,c.bytes,c.firstSeen).changes;for(let c of s)r.run(...c.params);return d});return {logs:e,writeBatch:(s,i)=>o.immediate(s,i)}}catch(n){throw e.close(),n}}function vk(t={}){let e=t.crewxDbPath??new Yo().resolveDbPath(),n=an(e),r=Jo(t.batchRows,Rl,"batchRows"),o=Jo(t.batchBytes,El,"batchBytes"),s=t.maxBatches===void 0?void 0:Jo(t.maxBatches,1,"maxBatches"),i=t.maxMs===void 0?void 0:Jo(t.maxMs,1,"maxMs"),d=t.dryRun===true,c=t.checkpointWalBytes??Sl,u=t.checkpointMinIntervalMs??bl;if(!Sd.existsSync(e))throw new exports.RepositoryError("NOT_FOUND",`crewx.db not found: ${e}`);let f=Date.now(),l={crewxDbPath:e,logsDbPath:n,dryRun:d,movedRows:0,remainingRows:0,bodiesAdded:0,batches:0,maxDeleteTxMs:0,deleteTxMs:[],maxWalBytes:0,checkpoints:0,elapsedMs:0,sliceLimitReached:false},g=N(e,d?{readOnly:true}:{}),_;try{let m=Qi(g);if(!Xo(m,"request_logs"))return l;let k=m.prepare(bk),T=d?void 0:m.prepare("DELETE FROM request_logs WHERE rowid = ? AND id = ?"),E=T?m.transaction(se=>{let Et=0;for(let ce of se)Et+=T.run(ce.rowid,ce.id).changes;return Et}):void 0,S=Date.now(),D=()=>{S=Date.now();try{Zo(e,"PASSIVE"),l.checkpoints+=1;}catch{}};d||D();let y={rows:0,bodies:0,bodyBytes:0,distinct:new Map},b=0,O=0,ne=0;for(;;){if(s!==void 0&&l.batches>=s){l.sliceLimitReached=!0;break}if(i!==void 0&&l.batches>0&&Date.now()-f>=i){l.sliceLimitReached=!0;break}let se=O>0?Math.max(1,Math.min(r,Math.floor(o/O))):r,Et=k.all(b,se);if(Et.length===0)break;let ce=Ik(Et,o),Mr=ce.rows.reduce((Jn,Xn)=>Jn+Xn.sourceBytes,0);O=O===0?Mr/ce.rows.length:O*.5+Mr/ce.rows.length*.5,b=ce.rows[ce.rows.length-1].rowid,ne+=ce.rows.length,t.testHooks?.afterRead?.(ce.rows);let Vn=0;if(d){y.rows+=ce.rows.length;for(let Jn of ce.rows)for(let Xn of Jn.bodies)y.bodies+=1,y.bodyBytes+=Xn.bytes,y.distinct.set(Xn.hash,Xn.bytes);}else {_??=Ok(e),l.bodiesAdded+=_.writeBatch(ce.rows,ce.bodies),t.testHooks?.afterLogsCommit?.(ce.rows),Ak(_.logs.sqlite,ce.rows);let Jn=performance.now();l.movedRows+=E.immediate(ce.rows),Vn=performance.now()-Jn,l.deleteTxMs.push(Vn),Vn>l.maxDeleteTxMs&&(l.maxDeleteTxMs=Vn);}l.batches+=1;let Hr=Il(e);Hr>l.maxWalBytes&&(l.maxWalBytes=Hr),!d&&Hr>c&&Date.now()-S>=u&&D(),t.onProgress?.({batches:l.batches,scannedRows:ne,movedRows:l.movedRows,bodiesAdded:l.bodiesAdded,lastRowid:b,elapsedMs:Date.now()-f,deleteTxMs:Vn,walBytes:Hr});}if(d){let se=0;for(let Et of y.distinct.values())se+=Et;l.scan={rows:y.rows,bodies:y.bodies,bodyBytes:y.bodyBytes,distinctBodies:y.distinct.size,distinctBodyBytes:se};}return l.remainingRows=m.prepare("SELECT count(*) AS n FROM request_logs").get().n,l}finally{_?.logs.close(),g.close(),l.elapsedMs=Date.now()-f;}}function Nk(t){let e=t??new Yo().resolveDbPath(),n=an(e);if(!Sd.existsSync(e))throw new exports.RepositoryError("NOT_FOUND",`crewx.db not found: ${e}`);let r={crewxDbPath:e,logsDbPath:n,crewxRows:0,crewxFreelistPages:0,logsRows:null,logsBodies:null,logsFileBytes:0,logsWalBytes:Il(n)},o=N(e,{readOnly:true});try{let s=Qi(o);Xo(s,"request_logs")&&(r.crewxRows=s.prepare("SELECT count(*) AS n FROM request_logs").get().n),r.crewxFreelistPages=s.pragma("freelist_count",{simple:!0});}finally{o.close();}if(Sd.existsSync(n)&&(r.logsFileBytes=Sd.statSync(n).size,r.logsFileBytes>0)){let s=N(n,{readOnly:true});try{let i=Qi(s);Xo(i,"request_logs")&&(r.logsRows=i.prepare("SELECT count(*) AS n FROM request_logs").get().n),Xo(i,"request_log_bodies")&&(r.logsBodies=i.prepare("SELECT count(*) AS n FROM request_log_bodies").get().n);}finally{s.close();}}return r}h();re();ue();_e();ie();fe();function Ol(t){return new Date(Math.floor(t/3e5)*3e5).toISOString()}var Zi=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}upsert(e){let n=this.openHandle(true);try{let r=Ol(e.bucketStartMs),o=e.accountRef??"default";n.db.insert(Te).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:r,captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,source:e.source,metadata:e.metadata??null}).onConflictDoUpdate({target:[Te.provider,Te.account_ref,Te.limit_window,Te.bucket_start],set:{captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,metadata:e.metadata??null}}).run();}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to upsert usage limit snapshot",r)}finally{n.close();}}getTrends(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=n.db.select({provider:Te.provider,bucket_start:Te.bucket_start,used_percent:Te.used_percent,remaining_percent:Te.remaining_percent,resets_at:Te.resets_at}).from(Te).where(drizzleOrm.and(drizzleOrm.eq(Te.limit_window,e.window),drizzleOrm.gte(Te.bucket_start,e.fromIso),drizzleOrm.lte(Te.bucket_start,e.toIso))).orderBy(drizzleOrm.asc(Te.bucket_start)).all(),o=new Map;for(let s of r)o.has(s.provider)||o.set(s.provider,[]),o.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(o.entries()).map(([s,i])=>({provider:s,points:i}))}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to get usage limit trends",r)}finally{n.close();}}};h();re();ue();_e();ie();fe();var ea=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}publish(e){let n=this.openHandle(true);try{n.db.insert($e).values({id:e.id,workspace_id:e.workspaceId,month:e.month,generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}).onConflictDoUpdate({target:[$e.workspace_id,$e.month],set:{generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}}).run();let r=n.db.select().from($e).where(drizzleOrm.and(drizzleOrm.eq($e.workspace_id,e.workspaceId),drizzleOrm.eq($e.month,e.month))).limit(1).get();if(!r)throw new exports.RepositoryError("DB_ERROR","Failed to read back published usage report");return r}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to publish usage report",r)}finally{n.close();}}findByMonth(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from($e).where(drizzleOrm.and(drizzleOrm.eq($e.workspace_id,e),drizzleOrm.eq($e.month,n))).limit(1).get()??void 0}catch(o){throw new exports.RepositoryError("DB_ERROR","Failed to find usage report",o)}finally{r.close();}}listByWorkspace(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from($e).where(drizzleOrm.eq($e.workspace_id,e)).orderBy(drizzleOrm.desc($e.month)).all()}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to list usage reports",r)}finally{n.close();}}};h();re();ue();_e();ie();fe();var Ll=500,Ml=50,ta=class extends exports.BaseSqliteRepository{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??Ll;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}create(e){let n=this.openHandle(true);try{let r=je("ntf"),o=new Date().toISOString();return n.db.insert(q).values({id:r,workspace_id:e.workspaceId,agent_id:e.agentId??null,task_id:e.taskId??null,thread_id:e.threadId??null,source:e.source??"agent",level:e.level??"info",title:e.title,body:e.body??null,target_user_id:e.targetUserId??null,created_at:o,metadata:e.metadata??null}).run(),this.enforceCap(n,e.workspaceId),{id:r}}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to create notification",r)}finally{n.close();}}enforceCap(e,n){let s=(e.db.select({count:drizzleOrm.sql`count(*)`}).from(q).where(drizzleOrm.eq(q.workspace_id,n)).get()?.count??0)-this.cap;if(s<=0)return;let d=e.db.select({id:q.id}).from(q).innerJoin(pe,drizzleOrm.eq(pe.notification_id,q.id)).where(drizzleOrm.eq(q.workspace_id,n)).groupBy(q.id).orderBy(drizzleOrm.asc(q.created_at)).limit(s).all().map(c=>c.id);d.length!==0&&(e.db.delete(pe).where(drizzleOrm.inArray(pe.notification_id,d)).run(),e.db.delete(q).where(drizzleOrm.inArray(q.id,d)).run());}list(e){if(!this.dbExists())return [];let n=e.limit??Ml,r=this.openHandle(false);try{return r.db.select({id:q.id,workspace_id:q.workspace_id,agent_id:q.agent_id,task_id:q.task_id,thread_id:q.thread_id,source:q.source,level:q.level,title:q.title,body:q.body,target_user_id:q.target_user_id,created_at:q.created_at,metadata:q.metadata,read_at:pe.read_at}).from(q).leftJoin(pe,drizzleOrm.and(drizzleOrm.eq(pe.notification_id,q.id),drizzleOrm.eq(pe.user_id,e.userId))).where(drizzleOrm.eq(q.workspace_id,e.workspaceId)).orderBy(drizzleOrm.desc(q.created_at)).limit(n).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new exports.RepositoryError("DB_ERROR","Failed to list notifications",o)}finally{r.close();}}unreadCount(e){if(!this.dbExists())return 0;let n=this.openHandle(false);try{return n.db.select({count:drizzleOrm.sql`count(*)`}).from(q).leftJoin(pe,drizzleOrm.and(drizzleOrm.eq(pe.notification_id,q.id),drizzleOrm.eq(pe.user_id,e.userId))).where(drizzleOrm.and(drizzleOrm.eq(q.workspace_id,e.workspaceId),drizzleOrm.isNull(pe.notification_id))).get()?.count??0}catch(r){throw new exports.RepositoryError("DB_ERROR","Failed to count unread notifications",r)}finally{n.close();}}markRead(e){let n=this.openHandle(true);try{if(!n.db.select({id:q.id}).from(q).where(drizzleOrm.and(drizzleOrm.eq(q.id,e.notificationId),drizzleOrm.eq(q.workspace_id,e.workspaceId))).get())throw new exports.RepositoryError("NOT_FOUND","Notification not found in workspace");return n.db.insert(pe).values({notification_id:e.notificationId,user_id:e.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to mark notification read",r)}finally{n.close();}}markAllRead(e){let n=this.openHandle(true);try{let r=n.db.select({id:q.id}).from(q).leftJoin(pe,drizzleOrm.and(drizzleOrm.eq(pe.notification_id,q.id),drizzleOrm.eq(pe.user_id,e.userId))).where(drizzleOrm.and(drizzleOrm.eq(q.workspace_id,e.workspaceId),drizzleOrm.isNull(pe.notification_id))).all();if(r.length===0)return 0;let o=new Date().toISOString();return n.db.transaction(s=>{for(let i of r)s.insert(pe).values({notification_id:i.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),r.length}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to mark all notifications read",r)}finally{n.close();}}};h();re();ue();_e();ie();fe();var Ul=50,ra=class extends exports.BaseSqliteRepository{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Ae.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=Ae.dirname(n);Sd.existsSync(o)||Sd.mkdirSync(o,{recursive:true});}else if(!Sd.existsSync(n))throw new exports.RepositoryError("NOT_FOUND","Database not found");let r=N(n);if(e)try{V(r.db,n);}catch(o){throw r.close(),o}return r}create(e){let n=this.openHandle(true);try{let r=new Date().toISOString(),o=[],s=e.map(i=>{let d=je("sug");return o.push(d),{id:d,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:r,updated_at:r}});return s.length>0&&n.db.insert(W).values(s).run(),{ids:o}}catch(r){throw r instanceof exports.RepositoryError?r:new exports.RepositoryError("DB_ERROR","Failed to create agent suggestions",r)}finally{n.close();}}findLatestSet(e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({task_id:W.task_id}).from(W).where(drizzleOrm.and(drizzleOrm.eq(W.workspace_id,e),drizzleOrm.eq(W.agent_id,n))).orderBy(drizzleOrm.desc(W.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?drizzleOrm.isNull(W.task_id):drizzleOrm.eq(W.task_id,o.task_id);return r.db.select().from(W).where(drizzleOrm.and(drizzleOrm.eq(W.workspace_id,e),drizzleOrm.eq(W.agent_id,n),s)).orderBy(drizzleOrm.asc(W.created_at)).all()}catch(o){throw new exports.RepositoryError("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{r.close();}}findSetByTaskId(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(W).where(drizzleOrm.and(drizzleOrm.eq(W.workspace_id,e),drizzleOrm.eq(W.agent_id,n),drizzleOrm.eq(W.task_id,r))).orderBy(drizzleOrm.asc(W.created_at)).all()}catch(s){throw new exports.RepositoryError("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,n,r){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(W).where(drizzleOrm.and(drizzleOrm.eq(W.workspace_id,e),drizzleOrm.eq(W.agent_id,n),drizzleOrm.eq(W.id,r))).get()??null}catch(s){throw new exports.RepositoryError("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,n,r){let o=this.openHandle(true);try{let s={status:n,updated_at:new Date().toISOString()};return r!==void 0&&(s.applied_commit_sha=r),o.db.update(W).set(s).where(drizzleOrm.eq(W.id,e)).run().changes>0}catch(s){throw s instanceof exports.RepositoryError?s:new exports.RepositoryError("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,n,r=Ul){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(W).where(drizzleOrm.and(drizzleOrm.eq(W.workspace_id,e),drizzleOrm.eq(W.agent_id,n))).orderBy(drizzleOrm.desc(W.created_at)).limit(r).all()}catch(s){throw new exports.RepositoryError("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,n,r=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(W).where(drizzleOrm.and(drizzleOrm.eq(W.workspace_id,e),drizzleOrm.eq(W.agent_id,n),drizzleOrm.eq(W.status,"dismissed"))).orderBy(drizzleOrm.desc(W.updated_at)).limit(r).all()}catch(s){throw new exports.RepositoryError("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};exports.AgentSuggestionRepository=ra;exports.BUILTIN_THREAD_STATES=nl;exports.CommonCodeRepository=_s;exports.CommonCodeRepositoryError=ee;exports.DEFAULT_AGENT_SUGGESTION_LIST_LIMIT=Ul;exports.DEFAULT_NOTIFICATION_CAP=Ll;exports.DEFAULT_NOTIFICATION_LIST_LIMIT=Ml;exports.DEFAULT_PROJECT_STAGES=wd;exports.DEFAULT_PROJECT_STAGE_KEYS=Es;exports.LOGS_DB_FILE_NAME=kl;exports.LOGS_DB_SCHEMA_VERSION=Vi;exports.NotificationRepository=ta;exports.ProjectRepository=Rs;exports.REQUEST_LOG_MOVE_CHECKPOINT_MIN_INTERVAL_MS=bl;exports.REQUEST_LOG_MOVE_CHECKPOINT_WAL_BYTES=Sl;exports.REQUEST_LOG_MOVE_DEFAULT_BATCH_BYTES=El;exports.REQUEST_LOG_MOVE_DEFAULT_BATCH_ROWS=Rl;exports.RequestLogRepository=Xi;exports.SpanRepository=zi;exports.TASK_LOG_MIGRATION_EVENT_ROW_BYTES=wu;exports.TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES=Po;exports.TASK_LOG_MIGRATION_TERMINAL_STATUSES=Tu;exports.THREAD_HIGHLIGHT_DELETION_REASON_REGENERATION_REPLACED=cl;exports.THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED=ll;exports.THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED=jm;exports.THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED=ul;exports.THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS=Fm;exports.THREAD_PRIORITIES=tl;exports.ThreadBoxRepository=Ki;exports.ThreadHighlightConflictError=zn;exports.ThreadHighlightRegenerationConflictError=Vo;exports.ThreadHistoryConflictError=Ko;exports.ThreadHistoryRepository=Fi;exports.ThreadRepository=Mi;exports.ThreadTitleMetadataPatchError=on;exports.ToolCallRepository=Gi;exports.USAGE_BACKFILL_MAX_LATE_USAGE_AGE_MS=xu;exports.USAGE_BACKFILL_TERMINAL_STATUSES=Ho;exports.UsageLimitSnapshotRepository=Zi;exports.UsageReportRepository=ea;exports.WorkspaceRepository=Ts;exports.calcBucketStart=Ol;exports.classifyUsageAccountingReason=$u;exports.countRatedTasks=_u;exports.customStateLabel=rl;exports.generateCommonCodeId=gs;exports.hasRecordedUsage=Mn;exports.hasSufficientTaskLogMigrationFreeSpace=Su;exports.hasThreadTitleKey=Dm;exports.hashRequestLogBody=Dr;exports.inspectRequestLogsMove=Nk;exports.isTaskRetryableByDefault=P_;exports.isThreadPriority=Sr;exports.isThreadState=br;exports.listRatedTasks=fu;exports.matchesThreadTitleFilter=Hm;exports.mergeTerminalReason=vo;exports.mergeThreadTitleMeta=Ui;exports.moveRequestLogsToLogsDb=vk;exports.normalizeTaskRow=On;exports.normalizeTaskStatus=st;exports.openDrizzleDb=N;exports.openLogsDb=Pr;exports.parseThreadPriorityFilter=Lm;exports.parseThreadStateFilter=Mm;exports.pushSchema=Xf;exports.readTaskTerminalReason=wt;exports.readThreadTitleMeta=jo;exports.reclaimTemporaryJournal=Zo;exports.resolveCrewxLogsDbPath=an;exports.resolveTaskHeartbeatHardStaleMs=gr;exports.resolveTaskHeartbeatIntervalMs=yo;exports.resolveTaskHeartbeatStaleMs=en;exports.resolveTaskLogMigrationDbPath=Lo;exports.resolveTaskStopMethod=ci;exports.runHeartbeatTick=Zs;exports.runMigrations=cn;exports.runMigrationsOnce=V;exports.runTaskLogMigration=xh;exports.runUsageBackfill=hm;exports.setTaskRating=lu;exports.startTaskHeartbeat=H_;exports.stopTask=li;exports.stopTaskHeartbeat=Kc;exports.storedTaskStatusesFor=To;exports.taskLogBackupName=Ch;exports.threadTitleSearchHaystack=Pm;exports.tryCheckpointTaskLogWal=wr;
|