@crewx/sdk 0.9.0-rc.118 → 0.9.0-rc.119

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.
@@ -3,7 +3,7 @@ import type { McpAppServerStateInput, McpAppStateDescriptor, McpAppStateProjecti
3
3
  export declare const MCP_APP_PROJECTION_MAX_BYTES: number;
4
4
  export declare function buildMcpAppStateDescriptor(input: McpAppServerStateInput): McpAppStateDescriptor;
5
5
  export declare function buildTerminalMcpAppStateDescriptor(input: McpAppServerStateInput): McpAppStateDescriptor;
6
- export declare function serializeMcpAppStateJson(descriptor: McpAppStateDescriptor): string;
6
+ export declare function serializeMcpAppStateJson(descriptor: McpAppStateDescriptor, dataPaths?: readonly string[]): string;
7
7
  export declare function serializeMcpAppStateXml(descriptor: McpAppStateDescriptor): string;
8
8
  export declare function buildMcpAppStateProjections(input: McpAppServerStateInput): McpAppStateProjections;
9
9
  export declare function buildTerminalMcpAppStateProjections(input: McpAppServerStateInput): McpAppStateProjections;
@@ -285,6 +285,7 @@ export interface McpAppStateProjections {
285
285
  readonly descriptor: McpAppStateDescriptor;
286
286
  readonly json: string;
287
287
  readonly xml: string;
288
+ readonly omittedPaths?: readonly string[];
288
289
  };
289
290
  }
290
291
  export interface McpAppRegistry {
@@ -0,0 +1 @@
1
+ ALTER TABLE `ui_instances` ADD `opened_by_json` text;
@@ -225,6 +225,13 @@
225
225
  "when": 1789704195695,
226
226
  "tag": "0031_petite_arclight",
227
227
  "breakpoints": true
228
+ },
229
+ {
230
+ "idx": 32,
231
+ "version": "6",
232
+ "when": 1790121600000,
233
+ "tag": "0032_ui_instance_opened_by",
234
+ "breakpoints": true
228
235
  }
229
236
  ]
230
- }
237
+ }
@@ -5,7 +5,7 @@
5
5
  AND (stop_requested_at IS NOT NULL OR stop_requested_epoch IS NOT NULL)
6
6
  `);return {hash:u,affectedRows:l?.count??0}}function wd(t){let{migrate:e}=wt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=wt("drizzle-orm"),r=[pe__namespace.default.join(__dirname,"../migrations"),pe__namespace.default.join(__dirname,"migrations"),pe__namespace.default.join(__dirname,"../../../../drizzle/migrations"),pe__namespace.default.join(process.cwd(),"drizzle/migrations")],s=r.find(l=>fs$1.existsSync(pe__namespace.default.join(l,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
7
7
  ${r.join(`
8
- `)}`);let o=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ld(t,i),o?.cnt&&(md(t,s),_d(t,s,n),fd(t,s,n));let u=Td(t,s,n,!!o?.cnt);e(t,{migrationsFolder:s});let c=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}u&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(p=>p.hash===u.hash)&&console.error(`[crewx] Task stop-marker cleanup (${u.affectedRows} success/failed row(s) affected).`);}function De(t,e){oo.has(e)||(wd(t),oo.add(e));}var oo,cd,pd,kd,Rt=b(()=>{_();oo=new Set,cd={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"};pd={"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"}};kd="0027_task_stop_scope_cleanup";});var St,vr=b(()=>{_();St=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var a,Vt=b(()=>{_();a=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"),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)},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),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_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)}));});var Me,po=b(()=>{_();Vt();Me=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>a.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 xd,Cd,T,Mn=b(()=>{_();vr();xd="json_extract(metadata, '$.threadTitle.state')",Cd="json_extract(metadata, '$.threadTitle.priority')",T=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>St.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(xd)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(Cd))}));});var Dd,ho=b(()=>{_();Vt();Dd=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Dd.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 _o=b(()=>{_();Vt();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.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 ko=b(()=>{_();Mn();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.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 wo=b(()=>{_();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 Ro=b(()=>{_();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 So=b(()=>{_();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 Ao=b(()=>{_();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var bo=b(()=>{_();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 vo=b(()=>{_();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("[]"),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'`),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 Co=b(()=>{_();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),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`(
8
+ `)}`);let o=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ld(t,i),o?.cnt&&(md(t,s),_d(t,s,n),fd(t,s,n));let u=Td(t,s,n,!!o?.cnt);e(t,{migrationsFolder:s});let c=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}u&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(p=>p.hash===u.hash)&&console.error(`[crewx] Task stop-marker cleanup (${u.affectedRows} success/failed row(s) affected).`);}function De(t,e){oo.has(e)||(wd(t),oo.add(e));}var oo,cd,pd,kd,Rt=b(()=>{_();oo=new Set,cd={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"};pd={"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"}};kd="0027_task_stop_scope_cleanup";});var St,vr=b(()=>{_();St=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var a,Vt=b(()=>{_();a=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"),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)},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),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_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)}));});var Me,po=b(()=>{_();Vt();Me=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>a.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 xd,Cd,T,Mn=b(()=>{_();vr();xd="json_extract(metadata, '$.threadTitle.state')",Cd="json_extract(metadata, '$.threadTitle.priority')",T=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>St.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(xd)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(Cd))}));});var Dd,ho=b(()=>{_();Vt();Dd=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Dd.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 _o=b(()=>{_();Vt();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.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 ko=b(()=>{_();Mn();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.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 wo=b(()=>{_();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 Ro=b(()=>{_();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 So=b(()=>{_();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 Ao=b(()=>{_();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var bo=b(()=>{_();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 vo=b(()=>{_();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"),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 Co=b(()=>{_();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),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`(
9
9
  (${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
10
10
  OR
11
11
  (${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
@@ -69,7 +69,7 @@ ${r.join(`
69
69
  COALESCE(SUM(
70
70
  CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
71
71
  ), 0)
72
- `}function qt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Z(t){if(!t)return {};try{let e=JSON.parse(t);return qt(e)?{...e}:{}}catch{return {}}}function fr(t){return t==null||t===""}function xs(t,e){return fr(t)&&!fr(e)?e:t}function gl(t,e){let n=Z(t);if(!e)return n;for(let[r,s]of Object.entries(e))fr(n[r])&&!fr(s)&&(n[r]=s);return n}function lr(t,e){let n=t.origin&&Aa.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 hl(t){let e=Z(t).stopRequest;if(qt(e)&&!(typeof e.origin!="string"||!Aa.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function Ra(){return drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.ne(drizzleOrm.sql`COALESCE(${a.stop_requested_epoch}, 0)`,drizzleOrm.sql`COALESCE(${a.run_epoch}, 0)`))}function Ps(t,e){let n=Z(t??null);return n.terminalReason=e,JSON.stringify(n)}function Cs(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==Ea&&(n[ll]=e),{error:Ea,metadata:n}}function re(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ds(t){return re(t.input_tokens)!==0||re(t.output_tokens)!==0||re(t.cached_input_tokens)!==0||re(t.cost_usd)!==0}function K(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Sa(t){return {inputTokens:re(t.inputTokens??0),outputTokens:re(t.outputTokens??0),cachedInputTokens:re(t.cachedInputTokens??0),costUsd:re(t.costUsd??0)}}function _l(t){if(qt(t))return {inputTokens:re(t.inputTokens),outputTokens:re(t.outputTokens),cachedInputTokens:re(t.cachedInputTokens),costUsd:re(t.costUsd)}}function ml(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=_l(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function pr(t,e,n){let r=Date.parse(t),s=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(s)?s-r:n??null}var Os,$t,ul,Ut,Ft,cl,vs,_n,Ce,Ea,Ia,ll,pl,fl,Aa,Ls,Oa,ba,kn,Ss=b(()=>{_();ot();Et();Rt();rt();It();jn();zn();si();us();ir();pn();Rs();pn();Os=40,$t="2026-05-09",ul="0.8.9-rc.13",Ut=10,Ft=parseInt(ul.split("rc.")[1]);cl=new Set(["workflow","mcp"]),vs="usageByEpoch",_n="lateUsage",Ce="usageAccounting",Ea="Stopped by user",Ia="Stopped by app shutdown",ll="terminalErrorOriginal",pl=new Set(["stopped","runner_lost"]),fl=["pending","running"];Aa=new Set(["http","cli","instruction","workflow","internal"]);Ls=600*1e3,Oa=600*1e3,ba=300*1e3,kn=class extends we{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=pe.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Kn({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?st(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=pe.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new g("NOT_FOUND","Database not found");let r=U(n);if(e)try{De(r.db,n);}catch(s){throw r.close(),s}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=K(e.runEpoch),s=r===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),s,drizzleOrm.eq(a.status,"running"))).run().changes>0}catch(r){throw r instanceof g?r:new g("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(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=K(o.run_epoch);if(o.status!=="running"){r={accepted:!1,status:o.status,runEpoch:i};return}let u=o.stop_requested_at!==null&&K(o.stop_requested_epoch)===i,d=u?o.stop_requested_at:e.requestedAt,c=Z(o.metadata),l=u?hl(o.metadata)??lr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):lr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),Ra())).run().changes===0){let m=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:K(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:K(m.run_epoch),...m.stop_requested_at&&K(m.stop_requested_epoch)===K(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:o.status,runEpoch:i};let f=new Set([e.id]),h=(m,w)=>{if(w>=8)return;let k=s.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,m),drizzleOrm.eq(a.status,"running"))).all();for(let C of k)f.has(C.id)||(f.add(C.id),s.update(a).set({stop_requested_at:d,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...Z(C.metadata),stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,C.id),drizzleOrm.eq(a.status,"running"),Ra())).run(),h(C.id,w+1));};h(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof g?r:new g("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(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=K(o.run_epoch),u=K(e.sourceRunEpoch),d=K(e.settleRunEpoch);if(o.status!=="running"||i!==d||e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId){r={accepted:!1,status:o.status,runEpoch:i};return}let c=d===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,d),l=drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.isNull(a.stop_requested_epoch),drizzleOrm.ne(a.stop_requested_epoch,u)),p=lr({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),f=k=>s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:JSON.stringify({...Z(o.metadata),stopRequest:p})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,k,l)).run();if((e.workspaceId===void 0?f():e.workspaceId===null?f(drizzleOrm.isNull(a.workspace_id)):f(drizzleOrm.eq(a.workspace_id,e.workspaceId))).changes>0){r={accepted:!0,status:o.status,runEpoch:d};return}let m=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:K(m?.run_epoch)};return}let w=K(m.run_epoch);r={accepted:!1,status:m.status,runEpoch:w,...m.stop_requested_at&&K(m.stop_requested_epoch)===u?{alreadyRequestedAt:m.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof g?r:new g("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(),s=!1;return n.db.transaction(o=>{let i=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||K(i.run_epoch)!==K(e.runEpoch))return;let u=i.stop_requested_at!==null&&K(i.stop_requested_epoch)===K(e.runEpoch),d=Z(i.metadata),c=u?Cs(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...c.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??pr(i.started_at,r,void 0),f=i.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,i.run_epoch);s=o.update(a).set({status:"stopped",error:c.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),f)).run().changes>0;},{behavior:"immediate"}),s}catch(r){throw r instanceof g?r:new g("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(),s=K(e.expectedRunEpoch),o="not_running";return n.db.transaction(i=>{let u=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!u||u.status!=="running"){o="not_running";return}if(K(u.run_epoch)!==s){o="epoch_mismatch";return}if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId){o="workspace_mismatch";return}let c=u.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?drizzleOrm.isNull(a.workspace_id):drizzleOrm.eq(a.workspace_id,e.workspaceId),p={...Z(u.metadata),terminalReason:"runner_lost"},f=u.duration_ms??pr(u.started_at,r,void 0);o=i.update(a).set({status:"runner_lost",error:Ia,completed_at:r,duration_ms:f,metadata:JSON.stringify(p)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),o}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return wa(this,e,n)}async stopTaskGenerationForInstruction(e){return ka({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={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,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},s=o=>{n.db.insert(a).values(o).onConflictDoUpdate({target:a.id,set:{status:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:drizzleOrm.sql`COALESCE(excluded.pid, ${a.pid})`,actor_kind:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.actor_kind}, excluded.actor_kind) ELSE ${a.actor_kind} END`,actor_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.actor_id}, excluded.actor_id) ELSE ${a.actor_id} END`,command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workspace_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.workspace_id}, excluded.workspace_id) ELSE ${a.workspace_id} END`,cwd:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.project_id}, excluded.project_id) ELSE ${a.project_id} END`,crewx_version:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,coding_agent_command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.and(drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid)))}).run();};try{s(r);}catch(o){let i=o instanceof Error?o.message:typeof o=="object"&&o!==null&&"message"in o?String(o.message):String(o);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|cwd|actor_kind|actor_id/i.test(i)||!/no such column|no column named/i.test(i))throw o;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(Ir=>Ir.name)),d=u.has("cwd"),c=u.has("user_id"),l=u.has("actor_kind"),p=u.has("actor_id"),f=u.has("log_storage"),h=d?", cwd":"",m=d?", ?":"",w=d?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",k=f?", log_storage":"",C=f?", ?":"",L=c?", user_id":"",N=c?", ?":"",E=l?", actor_kind":"",v=l?", ?":"",O=p?", actor_id":"",Y=p?", ?":"",de=f?`,
72
+ `}function qt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Z(t){if(!t)return {};try{let e=JSON.parse(t);return qt(e)?{...e}:{}}catch{return {}}}function fr(t){return t==null||t===""}function xs(t,e){return fr(t)&&!fr(e)?e:t}function gl(t,e){let n=Z(t);if(!e)return n;for(let[r,s]of Object.entries(e))fr(n[r])&&!fr(s)&&(n[r]=s);return n}function lr(t,e){let n=t.origin&&Aa.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 hl(t){let e=Z(t).stopRequest;if(qt(e)&&!(typeof e.origin!="string"||!Aa.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function Ra(){return drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.ne(drizzleOrm.sql`COALESCE(${a.stop_requested_epoch}, 0)`,drizzleOrm.sql`COALESCE(${a.run_epoch}, 0)`))}function Ps(t,e){let n=Z(t??null);return n.terminalReason=e,JSON.stringify(n)}function Cs(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==Ea&&(n[ll]=e),{error:Ea,metadata:n}}function se(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ds(t){return se(t.input_tokens)!==0||se(t.output_tokens)!==0||se(t.cached_input_tokens)!==0||se(t.cost_usd)!==0}function K(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Sa(t){return {inputTokens:se(t.inputTokens??0),outputTokens:se(t.outputTokens??0),cachedInputTokens:se(t.cachedInputTokens??0),costUsd:se(t.costUsd??0)}}function _l(t){if(qt(t))return {inputTokens:se(t.inputTokens),outputTokens:se(t.outputTokens),cachedInputTokens:se(t.cachedInputTokens),costUsd:se(t.costUsd)}}function ml(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=_l(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function pr(t,e,n){let r=Date.parse(t),s=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(s)?s-r:n??null}var Os,$t,ul,Ut,Ft,cl,vs,_n,Ce,Ea,Ia,ll,pl,fl,Aa,Ls,Oa,ba,kn,Ss=b(()=>{_();ot();Et();Rt();rt();It();jn();zn();si();us();ir();pn();Rs();pn();Os=40,$t="2026-05-09",ul="0.8.9-rc.13",Ut=10,Ft=parseInt(ul.split("rc.")[1]);cl=new Set(["workflow","mcp"]),vs="usageByEpoch",_n="lateUsage",Ce="usageAccounting",Ea="Stopped by user",Ia="Stopped by app shutdown",ll="terminalErrorOriginal",pl=new Set(["stopped","runner_lost"]),fl=["pending","running"];Aa=new Set(["http","cli","instruction","workflow","internal"]);Ls=600*1e3,Oa=600*1e3,ba=300*1e3,kn=class extends we{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=pe.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Kn({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?st(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=pe.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new g("NOT_FOUND","Database not found");let r=U(n);if(e)try{De(r.db,n);}catch(s){throw r.close(),s}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=K(e.runEpoch),s=r===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),s,drizzleOrm.eq(a.status,"running"))).run().changes>0}catch(r){throw r instanceof g?r:new g("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(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=K(o.run_epoch);if(o.status!=="running"){r={accepted:!1,status:o.status,runEpoch:i};return}let u=o.stop_requested_at!==null&&K(o.stop_requested_epoch)===i,d=u?o.stop_requested_at:e.requestedAt,c=Z(o.metadata),l=u?hl(o.metadata)??lr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):lr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),Ra())).run().changes===0){let m=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:K(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:K(m.run_epoch),...m.stop_requested_at&&K(m.stop_requested_epoch)===K(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:o.status,runEpoch:i};let f=new Set([e.id]),h=(m,w)=>{if(w>=8)return;let k=s.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,m),drizzleOrm.eq(a.status,"running"))).all();for(let C of k)f.has(C.id)||(f.add(C.id),s.update(a).set({stop_requested_at:d,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...Z(C.metadata),stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,C.id),drizzleOrm.eq(a.status,"running"),Ra())).run(),h(C.id,w+1));};h(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof g?r:new g("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(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=K(o.run_epoch),u=K(e.sourceRunEpoch),d=K(e.settleRunEpoch);if(o.status!=="running"||i!==d||e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId){r={accepted:!1,status:o.status,runEpoch:i};return}let c=d===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,d),l=drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.isNull(a.stop_requested_epoch),drizzleOrm.ne(a.stop_requested_epoch,u)),p=lr({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),f=k=>s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:JSON.stringify({...Z(o.metadata),stopRequest:p})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,k,l)).run();if((e.workspaceId===void 0?f():e.workspaceId===null?f(drizzleOrm.isNull(a.workspace_id)):f(drizzleOrm.eq(a.workspace_id,e.workspaceId))).changes>0){r={accepted:!0,status:o.status,runEpoch:d};return}let m=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:K(m?.run_epoch)};return}let w=K(m.run_epoch);r={accepted:!1,status:m.status,runEpoch:w,...m.stop_requested_at&&K(m.stop_requested_epoch)===u?{alreadyRequestedAt:m.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof g?r:new g("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(),s=!1;return n.db.transaction(o=>{let i=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||K(i.run_epoch)!==K(e.runEpoch))return;let u=i.stop_requested_at!==null&&K(i.stop_requested_epoch)===K(e.runEpoch),d=Z(i.metadata),c=u?Cs(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...c.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??pr(i.started_at,r,void 0),f=i.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,i.run_epoch);s=o.update(a).set({status:"stopped",error:c.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),f)).run().changes>0;},{behavior:"immediate"}),s}catch(r){throw r instanceof g?r:new g("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(),s=K(e.expectedRunEpoch),o="not_running";return n.db.transaction(i=>{let u=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!u||u.status!=="running"){o="not_running";return}if(K(u.run_epoch)!==s){o="epoch_mismatch";return}if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId){o="workspace_mismatch";return}let c=u.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?drizzleOrm.isNull(a.workspace_id):drizzleOrm.eq(a.workspace_id,e.workspaceId),p={...Z(u.metadata),terminalReason:"runner_lost"},f=u.duration_ms??pr(u.started_at,r,void 0);o=i.update(a).set({status:"runner_lost",error:Ia,completed_at:r,duration_ms:f,metadata:JSON.stringify(p)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),o}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return wa(this,e,n)}async stopTaskGenerationForInstruction(e){return ka({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={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,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},s=o=>{n.db.insert(a).values(o).onConflictDoUpdate({target:a.id,set:{status:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:drizzleOrm.sql`COALESCE(excluded.pid, ${a.pid})`,actor_kind:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.actor_kind}, excluded.actor_kind) ELSE ${a.actor_kind} END`,actor_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.actor_id}, excluded.actor_id) ELSE ${a.actor_id} END`,command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workspace_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.workspace_id}, excluded.workspace_id) ELSE ${a.workspace_id} END`,cwd:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.project_id}, excluded.project_id) ELSE ${a.project_id} END`,crewx_version:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,coding_agent_command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.and(drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid)))}).run();};try{s(r);}catch(o){let i=o instanceof Error?o.message:typeof o=="object"&&o!==null&&"message"in o?String(o.message):String(o);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|cwd|actor_kind|actor_id/i.test(i)||!/no such column|no column named/i.test(i))throw o;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(Ir=>Ir.name)),d=u.has("cwd"),c=u.has("user_id"),l=u.has("actor_kind"),p=u.has("actor_id"),f=u.has("log_storage"),h=d?", cwd":"",m=d?", ?":"",w=d?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",k=f?", log_storage":"",C=f?", ?":"",L=c?", user_id":"",N=c?", ?":"",E=l?", actor_kind":"",v=l?", ?":"",O=p?", actor_id":"",Y=p?", ?":"",ue=f?`,
73
73
  log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
74
74
  id, agent_id, prompt, mode, status, started_at, pid,
75
75
  parent_task_id, caller_agent_id, trace_id, command, metadata,
@@ -86,10 +86,10 @@ ${r.join(`
86
86
  crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
87
87
  model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
88
88
  rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
89
- coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${de}
89
+ coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${ue}
90
90
  WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[r.id,r.agent_id,r.prompt,r.mode,r.status,r.started_at,r.pid,r.parent_task_id,r.caller_agent_id,r.trace_id,r.command,r.metadata,r.workspace_id,...d?[r.cwd]:[],r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command,...c?[r.user_id]:[],...l?[r.actor_kind]:[],...p?[r.actor_id]:[],...f?[r.log_storage]:[]]);}}catch(r){throw r instanceof g?r:new g("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:a.status,run_epoch:a.run_epoch,metadata:a.metadata,model:a.model,rendered_prompt:a.rendered_prompt,coding_agent_command:a.coding_agent_command}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||K(r.run_epoch)!==K(e.runEpoch))return !1;let s=gl(r.metadata,e.runtime?.metadata);s.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0&&(s.providerPid=e.providerPid);let o=r.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,r.run_epoch),i=n.db.update(a).set({metadata:JSON.stringify(s),model:xs(r.model,e.runtime?.model),rendered_prompt:xs(r.rendered_prompt,e.runtime?.renderedPrompt),coding_agent_command:xs(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o)).run();return i.changes>0&&K(e.runEpoch)>0&&n.db.update(a).set({stop_requested_at:null,stop_requested_epoch:null}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o,drizzleOrm.sql`${a.stop_requested_at} IS NOT NULL
91
- AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(a).set({status:"running"}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid))).run().changes===1}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let s=this.openHandle(true);try{return s.db.update(a).set({status:"failed",error:n,completed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes>0}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to fail pending task",o)}finally{s.close();}}stopPendingTask(e,n,r=new Date().toISOString(),s={}){let o=this.openHandle(true);try{let i=!1;return o.db.transaction(u=>{let d=u.select({metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).limit(1).get();if(!d)return;let c=Cs(Z(d.metadata),n),l={...c.metadata,stopMethod:"cooperative",stopRequest:lr(s,r)};i=u.update(a).set({status:"stopped",error:c.error,completed_at:r,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes===1;},{behavior:"immediate"}),i}catch(i){throw i instanceof g?i:new g("DB_ERROR","Failed to stop pending task",i)}finally{o.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(a).where(drizzleOrm.eq(a.project_id,e)).orderBy(drizzleOrm.desc(a.started_at)).all().map(xe)}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true),r,s;try{n.db.transaction(o=>{let i=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,result:a.result,exit_code:a.exit_code,error:a.error,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i)return;let u=K(i.run_epoch),d=K(e.runEpoch),c=i.status==="running"&&u===d,l=i.stop_requested_at!==null&&K(i.stop_requested_epoch)===u,p=c&&l,f=i.status==="stopped"&&u===d&&l,h=Z(i.metadata),m=qt(h[_n])?h[_n]:{},w=String(d),k=pl.has(i.status),C=k&&u===d&&!Ds(i)&&!Object.prototype.hasOwnProperty.call(m,w),L=k&&u===d&&!Object.prototype.hasOwnProperty.call(m,w),N=u>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||u!==d,E={},v;if(i.status!=="running"&&(r=i.status,s=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),N&&(i.status==="running"||L)){v=Z(i.metadata);let O=qt(v[vs])?{...v[vs]}:{};O[String(d)]=Sa(e),v[vs]=O;let Y=ml(O),de=Y.inputTokens!==0||Y.outputTokens!==0||Y.cachedInputTokens!==0||Y.costUsd!==0;de&&h[Ce]==="unavailable"?v[Ce]="recorded":i.status!=="running"&&!de&&h[Ce]===void 0&&(v[Ce]="unavailable"),E.metadata=JSON.stringify(v),E.input_tokens=Y.inputTokens,E.output_tokens=Y.outputTokens,E.cached_input_tokens=Y.cachedInputTokens,E.cost_usd=Y.costUsd;}else if(c||C)if(c)E.input_tokens=re(e.inputTokens??0),E.output_tokens=re(e.outputTokens??0),E.cached_input_tokens=re(e.cachedInputTokens??0),E.cost_usd=re(e.costUsd??0);else {let O=Sa(e),Y=O.inputTokens!==0||O.outputTokens!==0||O.cachedInputTokens!==0||O.costUsd!==0;Y&&(E.input_tokens=O.inputTokens,E.output_tokens=O.outputTokens,E.cached_input_tokens=O.cachedInputTokens,E.cost_usd=O.costUsd),v={...h};let de=qt(h[_n])?{...h[_n]}:{};de[w]={at:e.completedAt},v[_n]=de,v[Ce]===void 0?v[Ce]=Y?"recorded":"unavailable":Y&&v[Ce]==="unavailable"&&(v[Ce]="recorded"),E.metadata=JSON.stringify(v);}if((c||C)&&e.model!==void 0&&e.model!==null&&(!C||i.model===null)&&(E.model=e.model),p){v??=Z(i.metadata);let O=Cs(v,e.error);v={...O.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:ur(i.stop_requested_at,e.completedAt)},E.status="stopped",E.result=e.result??i.result,E.error=O.error,E.completed_at=e.completedAt,E.duration_ms=i.duration_ms??e.durationMs??pr(i.started_at,e.completedAt,void 0),E.exit_code=e.exitCode??i.exit_code,E.metadata=JSON.stringify(v);}else if(c)e.partialResultRecovered===!0&&(v??=Z(i.metadata),v.partialResultRecovered=!0,E.metadata=JSON.stringify(v)),E.status=e.status,E.result=e.result??null,E.error=e.error??null,E.completed_at=e.completedAt,E.duration_ms=u>0?pr(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,E.exit_code=e.exitCode??null;else if(f){let O=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(E.result=e.result,O=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(E.exit_code=e.exitCode),e.partialResultRecovered===!0&&(v??=Z(i.metadata),v.partialResultRecovered=!0,E.metadata=JSON.stringify(v)),O&&(r=void 0,s=void 0);}Object.keys(E).length>0&&o.update(a).set(E).where(drizzleOrm.eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to finish task",o)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:s??`task:end status=${e.status}`});}catch(o){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${o instanceof Error?o.message:String(o)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
92
- `);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.workspace_id,e.workspaceId)),s={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let o=n.db.select({metadata:a.metadata}).from(a).where(r).limit(1).get(),i=Z(o?.metadata??null);i.terminalReason=e.terminalReason,s.metadata=JSON.stringify(i);}n.db.update(a).set(s).where(r).run();}catch(r){throw r instanceof g?r:new g("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().from(a).where(drizzleOrm.eq(a.status,"running")).orderBy(drizzleOrm.desc(a.started_at)).all().map(xe)}catch(n){throw new g("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().from(a).where(drizzleOrm.inArray(a.status,["pending","running"])).orderBy(drizzleOrm.desc(a.started_at)).all().map(xe)}catch(n){throw new g("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().from(a).orderBy(drizzleOrm.desc(a.started_at)).limit(100).all().map(xe)}catch(n){throw new g("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select().from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();return r?xe(r):void 0}catch(r){throw new g("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:a.id,status:a.status,pid:a.pid,platform:a.platform,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at,started_at:a.started_at,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.status,"pending"))).all(),s=this.clock(),o=Math.max(1,Math.trunc(e.tickIntervalMs??ba)),i=this.lastReaperTickAt,u=i===void 0?Number.POSITIVE_INFINITY:s-i,d=i!==void 0&&u>=0&&u<=o*2;this.lastReaperTickAt=s;let c=Ht(),l=dr(),p=new Date(s-Oa).toISOString(),f=new Date(s).toISOString(),h=new Set,m=0,w=(k,C)=>{let L=Z(Ps(k.metadata,"runner_lost")),N=typeof L.provider=="string"?L.provider:void 0,E;try{E=or({taskLogRepository:this.taskLogRepository,taskId:k.id,provider:N,model:k.model})?.usage;}catch{}let v={status:"runner_lost",error:C,completed_at:f};E?(v.input_tokens=E.inputTokens,v.output_tokens=E.outputTokens,v.cached_input_tokens=E.cachedInputTokens,v.cost_usd=E.costUsd,k.model===null&&E.model!==null&&(v.model=E.model),L[Ce]="recorded"):!Ds(k)&&L[Ce]!=="recorded"&&(L[Ce]="unavailable"),v.metadata=JSON.stringify(L);let O=k.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,k.run_epoch),Y=k.heartbeat_at===null?drizzleOrm.isNull(a.heartbeat_at):drizzleOrm.eq(a.heartbeat_at,k.heartbeat_at),de=n.db.update(a).set(v).where(drizzleOrm.and(drizzleOrm.eq(a.id,k.id),drizzleOrm.eq(a.status,"running"),O,Y)).run();return de.changes>0&&m++,de.changes>0};for(let k of r){if(k.status==="pending"){if(k.pid!==null||k.started_at>=p)continue;let E=Ps(k.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:f,metadata:E}).where(drizzleOrm.and(drizzleOrm.eq(a.id,k.id),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,p))).run().changes>0&&m++;continue}if(cl.has(k.platform??"cli"))continue;if(k.pid===null){let E=`${k.id}:${k.run_epoch??0}`;h.add(E);let v=this.pidNullObservedSince.get(E);if(v===void 0){this.pidNullObservedSince.set(E,s);continue}s-v>=Ls&&w(k,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(E);continue}if(k.heartbeat_at===null){ut(k.pid)==="not_found"&&w(k,"Reaped: process not found (orphaned task)");continue}let C=Date.parse(k.heartbeat_at),L=Number.isFinite(C)?s-C:Number.POSITIVE_INFINITY;if(L<=c)continue;ut(k.pid)==="not_found"?w(k,"Reaped: process not found (orphaned task)"):L>l&&d&&w(k,"Reaped: heartbeat stale beyond hard limit (orphaned task)");}for(let k of Array.from(this.pidNullObservedSince.keys()))h.has(k)||this.pidNullObservedSince.delete(k);return m}finally{n.close();}}reapRunningWorkflowTasks(e=Ls){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),s=drizzleOrm.and(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,r),drizzleOrm.or(drizzleOrm.isNull(a.metadata),drizzleOrm.and(drizzleOrm.notLike(a.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(a.metadata,'%"kind":"workflow_ui_instance"%')))),o=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(s).all(),i=new Date().toISOString(),u=0;for(let d of o){let c=Z(d.metadata);c.terminalReason="runner_lost";let l=n.db.update(a).set({status:"runner_lost",error:"Reaped: stale workflow run (finally not executed)",completed_at:i,metadata:JSON.stringify(c)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,d.id),drizzleOrm.eq(a.status,"running"))).run();u+=l.changes??0;}return u}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=U(s);try{let i=n?drizzleOrm.eq(a.workspace_id,n):void 0,u=i?drizzleOrm.and(drizzleOrm.eq(a.id,e),i):drizzleOrm.eq(a.id,e),d=o.db.select().from(a).where(u).limit(1).get()??void 0;if(!d){let c=i?drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),i):drizzleOrm.eq(a.thread_id,e);d=o.db.select().from(a).where(c).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??void 0;}if(d)return xe(d)}catch(i){throw new g("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!fs$1.existsSync(i))continue;let u=U(i);try{let d=n?drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,e),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.eq(a.parent_task_id,e),c=u.db.select().from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(xe(l)));}catch(d){throw new g("DB_ERROR","Failed to find child tasks",d)}finally{u.close();}}return o}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?drizzleOrm.sql`
91
+ AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(a).set({status:"running"}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid))).run().changes===1}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let s=this.openHandle(true);try{return s.db.update(a).set({status:"failed",error:n,completed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes>0}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to fail pending task",o)}finally{s.close();}}stopPendingTask(e,n,r=new Date().toISOString(),s={}){let o=this.openHandle(true);try{let i=!1;return o.db.transaction(u=>{let d=u.select({metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).limit(1).get();if(!d)return;let c=Cs(Z(d.metadata),n),l={...c.metadata,stopMethod:"cooperative",stopRequest:lr(s,r)};i=u.update(a).set({status:"stopped",error:c.error,completed_at:r,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes===1;},{behavior:"immediate"}),i}catch(i){throw i instanceof g?i:new g("DB_ERROR","Failed to stop pending task",i)}finally{o.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(a).where(drizzleOrm.eq(a.project_id,e)).orderBy(drizzleOrm.desc(a.started_at)).all().map(xe)}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true),r,s;try{n.db.transaction(o=>{let i=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,result:a.result,exit_code:a.exit_code,error:a.error,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i)return;let u=K(i.run_epoch),d=K(e.runEpoch),c=i.status==="running"&&u===d,l=i.stop_requested_at!==null&&K(i.stop_requested_epoch)===u,p=c&&l,f=i.status==="stopped"&&u===d&&l,h=Z(i.metadata),m=qt(h[_n])?h[_n]:{},w=String(d),k=pl.has(i.status),C=k&&u===d&&!Ds(i)&&!Object.prototype.hasOwnProperty.call(m,w),L=k&&u===d&&!Object.prototype.hasOwnProperty.call(m,w),N=u>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||u!==d,E={},v;if(i.status!=="running"&&(r=i.status,s=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),N&&(i.status==="running"||L)){v=Z(i.metadata);let O=qt(v[vs])?{...v[vs]}:{};O[String(d)]=Sa(e),v[vs]=O;let Y=ml(O),ue=Y.inputTokens!==0||Y.outputTokens!==0||Y.cachedInputTokens!==0||Y.costUsd!==0;ue&&h[Ce]==="unavailable"?v[Ce]="recorded":i.status!=="running"&&!ue&&h[Ce]===void 0&&(v[Ce]="unavailable"),E.metadata=JSON.stringify(v),E.input_tokens=Y.inputTokens,E.output_tokens=Y.outputTokens,E.cached_input_tokens=Y.cachedInputTokens,E.cost_usd=Y.costUsd;}else if(c||C)if(c)E.input_tokens=se(e.inputTokens??0),E.output_tokens=se(e.outputTokens??0),E.cached_input_tokens=se(e.cachedInputTokens??0),E.cost_usd=se(e.costUsd??0);else {let O=Sa(e),Y=O.inputTokens!==0||O.outputTokens!==0||O.cachedInputTokens!==0||O.costUsd!==0;Y&&(E.input_tokens=O.inputTokens,E.output_tokens=O.outputTokens,E.cached_input_tokens=O.cachedInputTokens,E.cost_usd=O.costUsd),v={...h};let ue=qt(h[_n])?{...h[_n]}:{};ue[w]={at:e.completedAt},v[_n]=ue,v[Ce]===void 0?v[Ce]=Y?"recorded":"unavailable":Y&&v[Ce]==="unavailable"&&(v[Ce]="recorded"),E.metadata=JSON.stringify(v);}if((c||C)&&e.model!==void 0&&e.model!==null&&(!C||i.model===null)&&(E.model=e.model),p){v??=Z(i.metadata);let O=Cs(v,e.error);v={...O.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:ur(i.stop_requested_at,e.completedAt)},E.status="stopped",E.result=e.result??i.result,E.error=O.error,E.completed_at=e.completedAt,E.duration_ms=i.duration_ms??e.durationMs??pr(i.started_at,e.completedAt,void 0),E.exit_code=e.exitCode??i.exit_code,E.metadata=JSON.stringify(v);}else if(c)e.partialResultRecovered===!0&&(v??=Z(i.metadata),v.partialResultRecovered=!0,E.metadata=JSON.stringify(v)),E.status=e.status,E.result=e.result??null,E.error=e.error??null,E.completed_at=e.completedAt,E.duration_ms=u>0?pr(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,E.exit_code=e.exitCode??null;else if(f){let O=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(E.result=e.result,O=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(E.exit_code=e.exitCode),e.partialResultRecovered===!0&&(v??=Z(i.metadata),v.partialResultRecovered=!0,E.metadata=JSON.stringify(v)),O&&(r=void 0,s=void 0);}Object.keys(E).length>0&&o.update(a).set(E).where(drizzleOrm.eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to finish task",o)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:s??`task:end status=${e.status}`});}catch(o){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${o instanceof Error?o.message:String(o)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
92
+ `);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.workspace_id,e.workspaceId)),s={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let o=n.db.select({metadata:a.metadata}).from(a).where(r).limit(1).get(),i=Z(o?.metadata??null);i.terminalReason=e.terminalReason,s.metadata=JSON.stringify(i);}n.db.update(a).set(s).where(r).run();}catch(r){throw r instanceof g?r:new g("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().from(a).where(drizzleOrm.eq(a.status,"running")).orderBy(drizzleOrm.desc(a.started_at)).all().map(xe)}catch(n){throw new g("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().from(a).where(drizzleOrm.inArray(a.status,["pending","running"])).orderBy(drizzleOrm.desc(a.started_at)).all().map(xe)}catch(n){throw new g("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().from(a).orderBy(drizzleOrm.desc(a.started_at)).limit(100).all().map(xe)}catch(n){throw new g("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select().from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();return r?xe(r):void 0}catch(r){throw new g("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:a.id,status:a.status,pid:a.pid,platform:a.platform,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at,started_at:a.started_at,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.status,"pending"))).all(),s=this.clock(),o=Math.max(1,Math.trunc(e.tickIntervalMs??ba)),i=this.lastReaperTickAt,u=i===void 0?Number.POSITIVE_INFINITY:s-i,d=i!==void 0&&u>=0&&u<=o*2;this.lastReaperTickAt=s;let c=Ht(),l=dr(),p=new Date(s-Oa).toISOString(),f=new Date(s).toISOString(),h=new Set,m=0,w=(k,C)=>{let L=Z(Ps(k.metadata,"runner_lost")),N=typeof L.provider=="string"?L.provider:void 0,E;try{E=or({taskLogRepository:this.taskLogRepository,taskId:k.id,provider:N,model:k.model})?.usage;}catch{}let v={status:"runner_lost",error:C,completed_at:f};E?(v.input_tokens=E.inputTokens,v.output_tokens=E.outputTokens,v.cached_input_tokens=E.cachedInputTokens,v.cost_usd=E.costUsd,k.model===null&&E.model!==null&&(v.model=E.model),L[Ce]="recorded"):!Ds(k)&&L[Ce]!=="recorded"&&(L[Ce]="unavailable"),v.metadata=JSON.stringify(L);let O=k.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,k.run_epoch),Y=k.heartbeat_at===null?drizzleOrm.isNull(a.heartbeat_at):drizzleOrm.eq(a.heartbeat_at,k.heartbeat_at),ue=n.db.update(a).set(v).where(drizzleOrm.and(drizzleOrm.eq(a.id,k.id),drizzleOrm.eq(a.status,"running"),O,Y)).run();return ue.changes>0&&m++,ue.changes>0};for(let k of r){if(k.status==="pending"){if(k.pid!==null||k.started_at>=p)continue;let E=Ps(k.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:f,metadata:E}).where(drizzleOrm.and(drizzleOrm.eq(a.id,k.id),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,p))).run().changes>0&&m++;continue}if(cl.has(k.platform??"cli"))continue;if(k.pid===null){let E=`${k.id}:${k.run_epoch??0}`;h.add(E);let v=this.pidNullObservedSince.get(E);if(v===void 0){this.pidNullObservedSince.set(E,s);continue}s-v>=Ls&&w(k,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(E);continue}if(k.heartbeat_at===null){ut(k.pid)==="not_found"&&w(k,"Reaped: process not found (orphaned task)");continue}let C=Date.parse(k.heartbeat_at),L=Number.isFinite(C)?s-C:Number.POSITIVE_INFINITY;if(L<=c)continue;ut(k.pid)==="not_found"?w(k,"Reaped: process not found (orphaned task)"):L>l&&d&&w(k,"Reaped: heartbeat stale beyond hard limit (orphaned task)");}for(let k of Array.from(this.pidNullObservedSince.keys()))h.has(k)||this.pidNullObservedSince.delete(k);return m}finally{n.close();}}reapRunningWorkflowTasks(e=Ls){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),s=drizzleOrm.and(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,r),drizzleOrm.or(drizzleOrm.isNull(a.metadata),drizzleOrm.and(drizzleOrm.notLike(a.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(a.metadata,'%"kind":"workflow_ui_instance"%')))),o=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(s).all(),i=new Date().toISOString(),u=0;for(let d of o){let c=Z(d.metadata);c.terminalReason="runner_lost";let l=n.db.update(a).set({status:"runner_lost",error:"Reaped: stale workflow run (finally not executed)",completed_at:i,metadata:JSON.stringify(c)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,d.id),drizzleOrm.eq(a.status,"running"))).run();u+=l.changes??0;}return u}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=U(s);try{let i=n?drizzleOrm.eq(a.workspace_id,n):void 0,u=i?drizzleOrm.and(drizzleOrm.eq(a.id,e),i):drizzleOrm.eq(a.id,e),d=o.db.select().from(a).where(u).limit(1).get()??void 0;if(!d){let c=i?drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),i):drizzleOrm.eq(a.thread_id,e);d=o.db.select().from(a).where(c).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??void 0;}if(d)return xe(d)}catch(i){throw new g("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!fs$1.existsSync(i))continue;let u=U(i);try{let d=n?drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,e),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.eq(a.parent_task_id,e),c=u.db.select().from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(xe(l)));}catch(d){throw new g("DB_ERROR","Failed to find child tasks",d)}finally{u.close();}}return o}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?drizzleOrm.sql`
93
93
  SELECT
94
94
  COALESCE(workspace_id, 'unknown') AS workspace_id,
95
95
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -384,7 +384,7 @@ Message: ${n.message}
384
384
  message_count = message_count + 1,
385
385
  updated_at = ${o}
386
386
  WHERE id = ${e}
387
- `),c},{behavior:"immediate"})}}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to save user message",o)}finally{s.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.update(T).set({last_message:n,updated_at:o}).where(drizzleOrm.eq(T.id,e)).run();}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to save assistant message",o)}finally{s.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};n.title!==void 0&&(s.title=n.title,s.title_locked=1),n.titleLocked!==void 0&&(s.title_locked=n.titleLocked?1:0),r.db.update(T).set(s).where(drizzleOrm.eq(T.id,e)).run();}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to update thread",s)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let s=n;if(!s||typeof s!="object"||Array.isArray(s))return new Bt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(d=>d!=="priority"&&d!=="state"))return new Bt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=s;if(i.priority===void 0&&i.state===void 0)return new Bt("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [i.priority,i.state])if(d!=null&&(typeof d!="string"||d.length===0))return new Bt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let u=this.openHandle(true);try{let d=r?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,r)):drizzleOrm.eq(T.id,e);return u.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(d).get();if(!l)return null;let p=wn(l.metadata),f=p.threadTitle,h=f&&typeof f=="object"&&!Array.isArray(f)?{...f}:{};i.priority===null?delete h.priority:i.priority!==void 0&&(h.priority=i.priority),i.state===null?delete h.state:i.state!==void 0&&(h.state=i.state),Object.keys(h).length>0?p.threadTitle=h:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,w=new Date().toISOString();c.update(T).set({metadata:m,updated_at:w}).where(d).run();let k=c.select({metadata:T.metadata}).from(T).where(d).get();if(!k)throw new g("DB_ERROR","Thread-title metadata update could not be read back");let C=Pl(k.metadata);return {threadId:e,priority:C.priority,state:C.state}},{behavior:"immediate"})}catch(d){throw d instanceof g?d:new g("DB_ERROR","Failed to patch thread-title metadata",d)}finally{u.close();}}togglePin(e,n){let r=this.openHandle(true);try{let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e);return r.db.transaction(o=>{let i=o.select({pinned:T.pinned,metadata:T.metadata}).from(T).where(s).get();if(!i)return null;let u=i.pinned?0:1,d=wn(i.metadata);if(u){let c=n?drizzleOrm.and(drizzleOrm.eq(T.pinned,1),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.pinned,1),l=o.select({metadata:T.metadata}).from(T).where(c).all(),p=null;for(let f of l){let h=wn(f.metadata);typeof h.pinOrder=="number"&&(p===null||h.pinOrder<p)&&(p=h.pinOrder);}d.pinOrder=p===null?0:p-1;}else delete d.pinOrder;return o.update(T).set({pinned:u,metadata:Object.keys(d).length>0?JSON.stringify(d):null}).where(s).run(),{pinned:!!u}},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to toggle pin",s)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>{for(let o=0;o<e.length;o++){let i=n?drizzleOrm.and(drizzleOrm.eq(T.id,e[o]),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e[o]),u=s.select({metadata:T.metadata}).from(T).where(i).get();if(!u)continue;let d=wn(u.metadata);d.pinOrder=o+1,s.update(T).set({metadata:JSON.stringify(d)}).where(i).run();}},{behavior:"immediate"});}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to reorder pins",s)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e),o=r.db.select({starred:T.starred}).from(T).where(s).get();if(!o)return null;let i=o.starred?0:1;return r.db.update(T).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to toggle star",s)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,s){let i=this.openHandle(true);try{let u=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e);return i.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},f=p.overdrive??{},h=s?.defaultTurns??f.defaultTurns??3,m=s?.updatedBy??"ui",w=new Date().toISOString(),k,C,L,N;switch(r){case "enable-count":{let E=s?.turns??h,v=s?.consumeCurrent?Math.max(E-1,0):E;k=v>0?"count":"off",C=v,L=!0,N="count";break}case "enable-latch":{k="latch",C=0,L=!0,N="latch";break}case "disable":{k="off",C=0,L=!1;break}default:{let E=f.state??"off",v=typeof f.remaining=="number"?f.remaining:0;if(E==="count"&&v>0){let O=v-1;O<=0?(k="off",C=0):(k="count",C=O),L=!0,N="count";}else E==="latch"?(k="latch",C=0,L=!0,N="latch"):(k="off",C=0,L=!1);break}}return p.overdrive={state:k,remaining:C,defaultTurns:h,updatedAt:w,updatedBy:m},c.update(T).set({metadata:JSON.stringify(p),updated_at:w}).where(u).run(),{applied:L,appliedMode:N,state:k,remaining:C}},{behavior:"immediate"})}catch(u){throw u instanceof g?u:new g("DB_ERROR","Failed to resolve overdrive",u)}finally{i.close();}}};_();ot();Et();Rt();rt();_();var Hs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Dl(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let s=e[r];s<248&&(n+=Hs[s%62]);}for(;n.length<t;)n+=Hs[crypto.randomBytes(1)[0]%62];return n}function yn(t){return `${t}_${Dl(8)}`}function Ha(t,e){let{createHash:n}=wt("crypto"),r=n("sha256").update(e).digest(),s=Buffer.alloc(8);for(let i=0;i<32;i++)s[i%8]^=r[i];let o="";for(let i of s)o+=Hs[i%62];return `${t}_${o}`}It();_();var Ll=["urgent","high","medium","low"],Ml=["investigating","in-progress","in-review","on-hold","done"],$a="custom:";var Hl=new Set(Ll),$l=new Set(Ml);function $s(t){return typeof t=="string"&&Hl.has(t)}function Us(t){if(typeof t!="string")return false;if($l.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith($a))return false;let e=t.slice($a.length);return e.length>=1&&e.length<=20}function Ua(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 Fs(t){let e=Ua(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,s={};return $s(r.priority)&&(s.priority=r.priority),Us(r.state)&&(s.state=r.state),s}function Fa(t,e){let n=Ua(t)??{},r={...Fs(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)}ir();var Wl="regeneration_replaced";var jl="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Gl="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Ws=class extends g{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,s){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${s}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=s;}},bn=class extends Ws{},js=class extends g{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},zl=new Set(Mo),Kl=new Set(Lo),Vl=new Set(Ho),Jl=new Set($o),Yl=50,Ba=100,Wa=280,ja=40,Xl=new Set(Uo),kr=["queued","running"];function Bs(t){return Xl.has(t)}function W(t){throw new g("VALIDATION",t)}function Pe(t){throw new g("NOT_FOUND",t)}function P(t,e){(typeof t!="string"||t.trim().length===0)&&W(`${e} is required`);}function Rn(t={}){let e=t.actor??t,n=e.actorType??"system";return zl.has(n)||W(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&W("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Ql(t){P(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&P(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&W("title must not be empty"),t.title.length>120&&W("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!$s(t.priority)&&W(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Us(t.state)&&W(`invalid state: ${String(t.state)}`);}function Zl(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&W("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)&&W(`${n} must be a non-negative integer`);let e=t.limit??Yl;return (!Number.isInteger(e)||e<1||e>Ba)&&W(`limit must be between 1 and ${Ba}`),e}function Gs(t){typeof t!="string"&&W("text is required");let e=t.trim();return e.length===0&&W("text must not be empty"),e.length>Wa&&W(`text must be at most ${Wa} characters`),e}function Ke(t,e){return P(t??"",e),t}function zs(t){Jl.has(t)||W(`invalid highlight kind: ${String(t)}`);}function ep(t){Vl.has(t)||W(`invalid highlight source: ${String(t)}`);}function tp(t){P(t.threadId,"threadId"),P(t.workspaceId,"workspaceId");let e=t.source??"manual";ep(e),zs(t.kind);let n=Gs(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,s=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&s&&r===s?r:void 0),p=Ke(l,"taskId");return (r!==p||s!==p)&&W("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let o=Ke(r,"coversFromTaskId"),i=Ke(s,"coversToTaskId"),u=t.sourceTaskId??o,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Ke(u??void 0,"sourceTaskId"),Ke(d??void 0,"detectorVersion"),Ke(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:o,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:u,detectorVersion:d,contentFingerprint:c}}function np(t,e){(!t||typeof t!="object")&&W(`candidates[${e}] is required`),zs(t.kind);let n=Gs(t.text),r=Ke(t.anchorTaskId,`candidates[${e}].anchorTaskId`),s=Ke(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),o=Ke(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Ha("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o}));return P(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o,contentFingerprint:i}}function rp(t){Array.isArray(t)||W("candidates must be an array"),t.length>ja&&W(`candidates must contain at most ${ja} items`);let e=new Map;for(let[n,r]of t.entries()){let s=np(r,n);e.set(s.contentFingerprint,s);}return [...e.values()]}function On(t){let e=Fs(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 sp(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&W("event payload must be a JSON object"),e}catch(e){throw new g("VALIDATION","event payload must be JSON serializable",e)}}function Sn(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,e)).get()?.maxSeq??0}function In(t,e){return !!t.select({id:B.id}).from(B).where(drizzleOrm.eq(B.thread_id,e)).limit(1).get()}function kt(t,e){Kl.has(e.type)||W(`invalid thread event type: ${String(e.type)}`);let n=yn("the");t.insert(B).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:sp(e.payload),created_at:e.createdAt}).run();let r=t.select().from(B).where(drizzleOrm.eq(B.id,n)).get();if(!r)throw new g("DB_ERROR","Thread event insert did not return a row");return r}function An(t,e,n,r,s){let o=On(e);kt(t,{threadId:e.id,seq:s,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:o.title,priority:o.priority,state:o.state}});}function wr(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 Tr(t,e,n,r,s,o,i){let u=s==="thread.highlight.created"?wr(e):{before:i?wr({...e,...i,id:e.id}):void 0,after:wr(e)};return kt(t,{threadId:e.thread_id,seq:o,type:s,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:u})}function op(t,e,n,r,s,o){return kt(t,{threadId:e.thread_id,seq:s,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:wr(e),...o??{}}})}var yr=class extends we{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=pe.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs$1.existsSync(n))throw new g("NOT_FOUND","Database not found");if(e){let s=pe.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}let r=U(n);if(e)try{De(r.db,n);}catch(s){throw r.close(),s}return r}findThread(e,n,r){let s=drizzleOrm.eq(T.id,n),o=r===void 0?s:r===null?drizzleOrm.and(s,drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(s,drizzleOrm.eq(T.workspace_id,r));return e.select().from(T).where(o).limit(1).get()}findRegenerationRun(e,n,r){let s=e.select().from($).where(drizzleOrm.eq($.id,n)).limit(1).get();if(s&&!(r!==void 0&&!this.findThread(e,s.thread_id,r)))return s}resolveWorkspaceId(e){if(P(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:T.workspace_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(P(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,n);return s?On(s):null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){Ql(e);let n=Rn(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||Pe(`Thread ${e.threadId} not found`);let u=On(i),d=e.title!==void 0,c=d&&e.title!==u.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==u.priority,f=e.state!==void 0&&e.state!==u.state,h=c||p||f;if(!h&&!l)return u;let m=i.metadata;(p||f)&&(m=Fa(i.metadata,{priority:e.priority,state:e.state}));let w={};if(h&&(w.metadata=m,w.updated_at=r),c&&(w.title=e.title),d&&(w.title_locked=1),o.update(T).set(w).where(e.workspaceId===void 0?drizzleOrm.eq(T.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.eq(T.workspace_id,e.workspaceId))).run(),!h){let L={...i,title_locked:1};return On(L)}let k=Sn(o,i.id)+1;In(o,i.id)||(An(o,i,n,r,k),k+=1),c&&(kt(o,{threadId:i.id,seq:k,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),k+=1),p&&(kt(o,{threadId:i.id,seq:k,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),k+=1),f&&kt(o,{threadId:i.id,seq:k,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let C={...i,title:c?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return On(C)},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to update thread snapshot",o)}finally{s.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(P(e,"threadId"),!fs$1.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(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,e)).get()?.maxSeq??0:null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read latest thread event sequence",s)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(P(e,"threadId"),P(n,"workspaceId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...oa,"completed","done","error"]),drizzleOrm.or(drizzleOrm.isNull(a.parent_task_id),drizzleOrm.eq(a.parent_task_id,"")),drizzleOrm.sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.asc(a.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read completed thread highlight turns",s)}finally{r.close();}}createHighlightRegenerationRun(e){P(e.threadId,"threadId"),P(e.workspaceId,"workspaceId"),P(e.requestId,"requestId"),P(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&P(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findThread(s,e.threadId,e.workspaceId);o||Pe(`Thread ${e.threadId} not found`);let i=s.select().from($).where(drizzleOrm.and(drizzleOrm.eq($.thread_id,o.id),drizzleOrm.eq($.request_id,e.requestId))).orderBy(drizzleOrm.desc($.requested_at),drizzleOrm.desc($.id)).limit(1).get();if(i)return {run:i,created:!1};let u=s.select().from($).where(drizzleOrm.and(drizzleOrm.eq($.thread_id,o.id),drizzleOrm.inArray($.status,kr))).orderBy(drizzleOrm.asc($.requested_at),drizzleOrm.asc($.id)).limit(1).get();if(u)throw new js(u);let d=e.runId??yn("thr");s.insert($).values({id:d,thread_id:o.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 c=s.select().from($).where(drizzleOrm.eq($.id,d)).get();if(!c)throw new g("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to create highlight regeneration run",s)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(P(e,"runId"),n!==void 0&&P(n,"workspaceId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read highlight regeneration run",s)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(P(e,"threadId"),P(n,"workspaceId"),P(r,"requestId"),!fs$1.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{return this.findThread(s.db,e,n)?s.db.select().from($).where(drizzleOrm.and(drizzleOrm.eq($.thread_id,e),drizzleOrm.eq($.request_id,r))).orderBy(drizzleOrm.desc($.requested_at),drizzleOrm.desc($.id)).limit(1).get()??null:null}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to read highlight regeneration request",o)}finally{s.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){P(e,"runId"),n!==void 0&&P(n,"workspaceId");let r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findRegenerationRun(o,e,n);if(i||Pe(`Highlight regeneration run ${e} not found`),Bs(i.status)||W(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;o.update($).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq($.id,i.id),drizzleOrm.eq($.status,"queued"))).run();let u=o.select().from($).where(drizzleOrm.eq($.id,i.id)).get();if(!u)throw new g("DB_ERROR","Highlight regeneration run start did not return a row");return u},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to start highlight regeneration run",o)}finally{s.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){P(e.runId,"runId"),P(e.errorCode,"errorCode"),e.workspaceId!==void 0&&P(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findRegenerationRun(s,e.runId,e.workspaceId);if(o||Pe(`Highlight regeneration run ${e.runId} not found`),Bs(o.status)||W(`invalid highlight regeneration status: ${o.status}`),o.status==="completed"||o.status==="failed")return o;s.update($).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq($.id,o.id),drizzleOrm.inArray($.status,kr))).run();let i=s.select().from($).where(drizzleOrm.eq($.id,o.id)).get();if(!i)throw new g("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to fail highlight regeneration run",s)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=jl){P(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update($).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray($.status,kr)).run().changes,{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to recover interrupted highlight runs",s)}finally{r.close();}}completeHighlightRegenerationRun(e){P(e.runId,"runId"),P(e.threadId,"threadId"),P(e.workspaceId,"workspaceId"),P(e.detectorVersion,"detectorVersion");let n=rp(e.candidates),r=Rn(e),s=this.openHandle(true),o=false;try{return s.db.transaction(i=>{let u=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!u||u.thread_id!==e.threadId)&&Pe(`Highlight regeneration run ${e.runId} not found`),Bs(u.status)||W(`invalid highlight regeneration status: ${u.status}`),u.status==="failed")throw new g("CONFLICT","Highlight regeneration run has already failed");if(u.status==="completed")return {run:u,deletedCount:0,createdCount:0,previousAutoCount:u.previous_auto_count??0,newAutoCount:u.new_auto_count??0};o=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||Pe(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&W("detectorVersion does not match the regeneration run");let c=i.select().from(D).where(drizzleOrm.eq(D.thread_id,d.id)).orderBy(drizzleOrm.asc(D.created_at),drizzleOrm.asc(D.id)).all(),l=new Set(n.map(O=>O.contentFingerprint)),p=c.filter(O=>O.source==="auto"&&O.status==="active"&&O.revision===0&&!l.has(O.content_fingerprint??"")),f=c.filter(O=>O.source==="auto"&&O.status==="active").length,h=new Set(c.filter(O=>!p.includes(O)&&O.content_fingerprint).map(O=>O.content_fingerprint)),m=n.filter(O=>!h.has(O.contentFingerprint)),w=new Date().toISOString(),k=Sn(i,d.id)+1;In(i,d.id)||(An(i,d,r,w,k),k+=1);for(let O of p)i.delete(D).where(drizzleOrm.eq(D.id,O.id)).run(),op(i,O,r,w,k,{runId:e.runId,reason:Wl}),k+=1;let C=0,L=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let O of m){let Y=yn("thl");i.insert(D).values({id:Y,thread_id:d.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:w,updated_at:w,agent_id:L,source_task_id:O.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:O.contentFingerprint,dismissed_at:null}).run();let de=i.select().from(D).where(drizzleOrm.eq(D.id,Y)).get();if(!de)throw new g("DB_ERROR","Regenerated highlight insert did not return a row");Tr(i,de,r,w,"thread.highlight.created",k),k+=1,C+=1;}let E=i.select().from(D).where(drizzleOrm.eq(D.thread_id,d.id)).all().filter(O=>O.source==="auto"&&O.status==="active").length;kt(i,{threadId:d.id,seq:k,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:w,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:f,newAutoCount:E,deletedCount:p.length,createdCount:C}}),i.update($).set({status:"completed",started_at:u.started_at??w,completed_at:w,error_code:null,previous_auto_count:f,new_auto_count:E}).where(drizzleOrm.and(drizzleOrm.eq($.id,u.id),drizzleOrm.inArray($.status,kr))).run();let v=i.select().from($).where(drizzleOrm.eq($.id,u.id)).get();if(!v)throw new g("DB_ERROR","Highlight regeneration completion did not return a row");return {run:v,deletedCount:p.length,createdCount:C,previousAutoCount:f,newAutoCount:E}},{behavior:"immediate"})}catch(i){if(o)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Gl});}catch{}throw i instanceof g?i:new g("DB_ERROR","Failed to complete highlight regeneration",i)}finally{s.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let s=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;P(s.threadId,"threadId"),P(s.workspaceId,"workspaceId");let o=Zl(s);if(!fs$1.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,s.threadId,s.workspaceId))return null;let u=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,s.threadId)).get()?.maxSeq??0,d;s.beforeSeq!==void 0?d=i.db.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.lt(B.seq,s.beforeSeq))).orderBy(drizzleOrm.desc(B.seq)).limit(o+1).all().reverse():s.afterSeq!==void 0?d=i.db.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.sql`${B.seq} > ${s.afterSeq}`)).orderBy(drizzleOrm.asc(B.seq)).limit(o+1).all():d=i.db.select().from(B).where(drizzleOrm.eq(B.thread_id,s.threadId)).orderBy(drizzleOrm.desc(B.seq)).limit(o+1).all().reverse();let c=d.length>o,l=s.afterSeq!==void 0?d.slice(0,o):c?d.slice(1):d,p=!1,f=l[0];return f&&(p=!!i.db.select({id:B.id}).from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.lt(B.seq,f.seq))).limit(1).get()),{items:l,latestSeq:u,hasMoreOlder:p}}catch(u){throw u instanceof g?u:new g("DB_ERROR","Failed to list thread timeline",u)}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=tp(e),r=Rn(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);if(u||Pe(`Thread ${e.threadId} not found`),n.source==="auto"){let f=i.select().from(D).where(drizzleOrm.and(drizzleOrm.eq(D.thread_id,e.threadId),drizzleOrm.eq(D.source_task_id,n.sourceTaskId),drizzleOrm.eq(D.detector_version,n.detectorVersion),drizzleOrm.eq(D.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(D.created_at),drizzleOrm.asc(D.id)).limit(1).get();if(f)return f}let d=e.id??yn("thl"),c={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:s,updated_at:s,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(D).values(c).run();let l=i.select().from(D).where(drizzleOrm.eq(D.id,d)).get();if(!l)throw new g("DB_ERROR","Highlight insert did not return a row");let p=Sn(i,u.id)+1;return In(i,u.id)||(An(i,u,r,s,p),p+=1),Tr(i,l,r,s,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof g?i:new g("DB_ERROR","Failed to create thread highlight",i)}finally{o.close();}}updateHighlight(e){P(e.threadId,"threadId"),P(e.workspaceId,"workspaceId"),P(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&W("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&W("highlight update requires at least one field"),e.kind!==void 0&&zs(e.kind);let n=e.text===void 0?void 0:Gs(e.text),r=Rn(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);u||Pe(`Thread ${e.threadId} not found`);let d=i.select().from(D).where(drizzleOrm.and(drizzleOrm.eq(D.id,e.highlightId),drizzleOrm.eq(D.thread_id,u.id))).limit(1).get();if(d||Pe(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new bn(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new bn(u.id,d.id,e.expectedRevision,d.revision);let c=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,f=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||f.length===0)&&W("highlight projection is incomplete");let h=c!==d.kind||l!==d.text||p!==d.covers_from_task_id||f!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&h?"manual":d.source;if(!(h||m!==d.source))return d;let k=d.revision+1;i.update(D).set({source:m,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:f,revision:k,updated_at:s}).where(drizzleOrm.and(drizzleOrm.eq(D.id,d.id),drizzleOrm.eq(D.revision,d.revision))).run();let C=i.select().from(D).where(drizzleOrm.eq(D.id,d.id)).get();if(!C)throw new g("DB_ERROR","Highlight update did not return a row");let L=Sn(i,u.id)+1;return In(i,u.id)||(An(i,u,r,s,L),L+=1),Tr(i,C,r,s,"thread.highlight.updated",L,d),C},{behavior:"immediate"})}catch(i){throw i instanceof g?i:new g("DB_ERROR","Failed to update thread highlight",i)}finally{o.close();}}dismissHighlight(e){P(e.threadId,"threadId"),P(e.workspaceId,"workspaceId"),P(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&W("expectedRevision must be a non-negative integer");let n=Rn(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||Pe(`Thread ${e.threadId} not found`);let u=o.select().from(D).where(drizzleOrm.and(drizzleOrm.eq(D.id,e.highlightId),drizzleOrm.eq(D.thread_id,i.id))).limit(1).get();if(u||Pe(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new bn(i.id,u.id,e.expectedRevision,u.revision);if(u.status==="dismissed")return u;let d=u.revision+1;o.update(D).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(D.id,u.id),drizzleOrm.eq(D.revision,u.revision))).run();let c=o.select().from(D).where(drizzleOrm.eq(D.id,u.id)).get();if(!c)throw new g("DB_ERROR","Highlight dismissal did not return a row");let l=Sn(o,i.id)+1;return In(o,i.id)||(An(o,i,n,r,l),l+=1),Tr(o,c,n,r,"thread.highlight.deleted",l,u),c},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to dismiss thread highlight",o)}finally{s.close();}}listActiveHighlights(e,n,r={}){if(P(e,"threadId"),P(n,"workspaceId"),r.taskId!==void 0&&P(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&P(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&P(r.coversToTaskId,"coversToTaskId"),!fs$1.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{if(!this.findThread(s.db,e,n))return null;let i=s.db.select().from(D).where(drizzleOrm.and(drizzleOrm.eq(D.thread_id,e),drizzleOrm.eq(D.status,"active"))).orderBy(drizzleOrm.asc(D.created_at),drizzleOrm.asc(D.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let u=s.db.all(drizzleOrm.sql`
387
+ `),c},{behavior:"immediate"})}}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to save user message",o)}finally{s.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.update(T).set({last_message:n,updated_at:o}).where(drizzleOrm.eq(T.id,e)).run();}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to save assistant message",o)}finally{s.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};n.title!==void 0&&(s.title=n.title,s.title_locked=1),n.titleLocked!==void 0&&(s.title_locked=n.titleLocked?1:0),r.db.update(T).set(s).where(drizzleOrm.eq(T.id,e)).run();}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to update thread",s)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let s=n;if(!s||typeof s!="object"||Array.isArray(s))return new Bt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(d=>d!=="priority"&&d!=="state"))return new Bt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=s;if(i.priority===void 0&&i.state===void 0)return new Bt("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [i.priority,i.state])if(d!=null&&(typeof d!="string"||d.length===0))return new Bt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let u=this.openHandle(true);try{let d=r?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,r)):drizzleOrm.eq(T.id,e);return u.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(d).get();if(!l)return null;let p=wn(l.metadata),f=p.threadTitle,h=f&&typeof f=="object"&&!Array.isArray(f)?{...f}:{};i.priority===null?delete h.priority:i.priority!==void 0&&(h.priority=i.priority),i.state===null?delete h.state:i.state!==void 0&&(h.state=i.state),Object.keys(h).length>0?p.threadTitle=h:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,w=new Date().toISOString();c.update(T).set({metadata:m,updated_at:w}).where(d).run();let k=c.select({metadata:T.metadata}).from(T).where(d).get();if(!k)throw new g("DB_ERROR","Thread-title metadata update could not be read back");let C=Pl(k.metadata);return {threadId:e,priority:C.priority,state:C.state}},{behavior:"immediate"})}catch(d){throw d instanceof g?d:new g("DB_ERROR","Failed to patch thread-title metadata",d)}finally{u.close();}}togglePin(e,n){let r=this.openHandle(true);try{let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e);return r.db.transaction(o=>{let i=o.select({pinned:T.pinned,metadata:T.metadata}).from(T).where(s).get();if(!i)return null;let u=i.pinned?0:1,d=wn(i.metadata);if(u){let c=n?drizzleOrm.and(drizzleOrm.eq(T.pinned,1),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.pinned,1),l=o.select({metadata:T.metadata}).from(T).where(c).all(),p=null;for(let f of l){let h=wn(f.metadata);typeof h.pinOrder=="number"&&(p===null||h.pinOrder<p)&&(p=h.pinOrder);}d.pinOrder=p===null?0:p-1;}else delete d.pinOrder;return o.update(T).set({pinned:u,metadata:Object.keys(d).length>0?JSON.stringify(d):null}).where(s).run(),{pinned:!!u}},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to toggle pin",s)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>{for(let o=0;o<e.length;o++){let i=n?drizzleOrm.and(drizzleOrm.eq(T.id,e[o]),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e[o]),u=s.select({metadata:T.metadata}).from(T).where(i).get();if(!u)continue;let d=wn(u.metadata);d.pinOrder=o+1,s.update(T).set({metadata:JSON.stringify(d)}).where(i).run();}},{behavior:"immediate"});}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to reorder pins",s)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e),o=r.db.select({starred:T.starred}).from(T).where(s).get();if(!o)return null;let i=o.starred?0:1;return r.db.update(T).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to toggle star",s)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,s){let i=this.openHandle(true);try{let u=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e);return i.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},f=p.overdrive??{},h=s?.defaultTurns??f.defaultTurns??3,m=s?.updatedBy??"ui",w=new Date().toISOString(),k,C,L,N;switch(r){case "enable-count":{let E=s?.turns??h,v=s?.consumeCurrent?Math.max(E-1,0):E;k=v>0?"count":"off",C=v,L=!0,N="count";break}case "enable-latch":{k="latch",C=0,L=!0,N="latch";break}case "disable":{k="off",C=0,L=!1;break}default:{let E=f.state??"off",v=typeof f.remaining=="number"?f.remaining:0;if(E==="count"&&v>0){let O=v-1;O<=0?(k="off",C=0):(k="count",C=O),L=!0,N="count";}else E==="latch"?(k="latch",C=0,L=!0,N="latch"):(k="off",C=0,L=!1);break}}return p.overdrive={state:k,remaining:C,defaultTurns:h,updatedAt:w,updatedBy:m},c.update(T).set({metadata:JSON.stringify(p),updated_at:w}).where(u).run(),{applied:L,appliedMode:N,state:k,remaining:C}},{behavior:"immediate"})}catch(u){throw u instanceof g?u:new g("DB_ERROR","Failed to resolve overdrive",u)}finally{i.close();}}};_();ot();Et();Rt();rt();_();var Hs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Dl(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let s=e[r];s<248&&(n+=Hs[s%62]);}for(;n.length<t;)n+=Hs[crypto.randomBytes(1)[0]%62];return n}function yn(t){return `${t}_${Dl(8)}`}function Ha(t,e){let{createHash:n}=wt("crypto"),r=n("sha256").update(e).digest(),s=Buffer.alloc(8);for(let i=0;i<32;i++)s[i%8]^=r[i];let o="";for(let i of s)o+=Hs[i%62];return `${t}_${o}`}It();_();var Ll=["urgent","high","medium","low"],Ml=["investigating","in-progress","in-review","on-hold","done"],$a="custom:";var Hl=new Set(Ll),$l=new Set(Ml);function $s(t){return typeof t=="string"&&Hl.has(t)}function Us(t){if(typeof t!="string")return false;if($l.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith($a))return false;let e=t.slice($a.length);return e.length>=1&&e.length<=20}function Ua(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 Fs(t){let e=Ua(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,s={};return $s(r.priority)&&(s.priority=r.priority),Us(r.state)&&(s.state=r.state),s}function Fa(t,e){let n=Ua(t)??{},r={...Fs(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)}ir();var Wl="regeneration_replaced";var jl="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Gl="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Ws=class extends g{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,s){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${s}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=s;}},bn=class extends Ws{},js=class extends g{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},zl=new Set(Mo),Kl=new Set(Lo),Vl=new Set(Ho),Jl=new Set($o),Yl=50,Ba=100,Wa=280,ja=40,Xl=new Set(Uo),kr=["queued","running"];function Bs(t){return Xl.has(t)}function W(t){throw new g("VALIDATION",t)}function Pe(t){throw new g("NOT_FOUND",t)}function P(t,e){(typeof t!="string"||t.trim().length===0)&&W(`${e} is required`);}function Rn(t={}){let e=t.actor??t,n=e.actorType??"system";return zl.has(n)||W(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&W("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Ql(t){P(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&P(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&W("title must not be empty"),t.title.length>120&&W("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!$s(t.priority)&&W(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Us(t.state)&&W(`invalid state: ${String(t.state)}`);}function Zl(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&W("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)&&W(`${n} must be a non-negative integer`);let e=t.limit??Yl;return (!Number.isInteger(e)||e<1||e>Ba)&&W(`limit must be between 1 and ${Ba}`),e}function Gs(t){typeof t!="string"&&W("text is required");let e=t.trim();return e.length===0&&W("text must not be empty"),e.length>Wa&&W(`text must be at most ${Wa} characters`),e}function Ke(t,e){return P(t??"",e),t}function zs(t){Jl.has(t)||W(`invalid highlight kind: ${String(t)}`);}function ep(t){Vl.has(t)||W(`invalid highlight source: ${String(t)}`);}function tp(t){P(t.threadId,"threadId"),P(t.workspaceId,"workspaceId");let e=t.source??"manual";ep(e),zs(t.kind);let n=Gs(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,s=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&s&&r===s?r:void 0),p=Ke(l,"taskId");return (r!==p||s!==p)&&W("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let o=Ke(r,"coversFromTaskId"),i=Ke(s,"coversToTaskId"),u=t.sourceTaskId??o,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Ke(u??void 0,"sourceTaskId"),Ke(d??void 0,"detectorVersion"),Ke(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:o,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:u,detectorVersion:d,contentFingerprint:c}}function np(t,e){(!t||typeof t!="object")&&W(`candidates[${e}] is required`),zs(t.kind);let n=Gs(t.text),r=Ke(t.anchorTaskId,`candidates[${e}].anchorTaskId`),s=Ke(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),o=Ke(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Ha("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o}));return P(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o,contentFingerprint:i}}function rp(t){Array.isArray(t)||W("candidates must be an array"),t.length>ja&&W(`candidates must contain at most ${ja} items`);let e=new Map;for(let[n,r]of t.entries()){let s=np(r,n);e.set(s.contentFingerprint,s);}return [...e.values()]}function On(t){let e=Fs(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 sp(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&W("event payload must be a JSON object"),e}catch(e){throw new g("VALIDATION","event payload must be JSON serializable",e)}}function Sn(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,e)).get()?.maxSeq??0}function In(t,e){return !!t.select({id:B.id}).from(B).where(drizzleOrm.eq(B.thread_id,e)).limit(1).get()}function kt(t,e){Kl.has(e.type)||W(`invalid thread event type: ${String(e.type)}`);let n=yn("the");t.insert(B).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:sp(e.payload),created_at:e.createdAt}).run();let r=t.select().from(B).where(drizzleOrm.eq(B.id,n)).get();if(!r)throw new g("DB_ERROR","Thread event insert did not return a row");return r}function An(t,e,n,r,s){let o=On(e);kt(t,{threadId:e.id,seq:s,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:o.title,priority:o.priority,state:o.state}});}function wr(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 Tr(t,e,n,r,s,o,i){let u=s==="thread.highlight.created"?wr(e):{before:i?wr({...e,...i,id:e.id}):void 0,after:wr(e)};return kt(t,{threadId:e.thread_id,seq:o,type:s,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:u})}function op(t,e,n,r,s,o){return kt(t,{threadId:e.thread_id,seq:s,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:wr(e),...o??{}}})}var yr=class extends we{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=pe.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs$1.existsSync(n))throw new g("NOT_FOUND","Database not found");if(e){let s=pe.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}let r=U(n);if(e)try{De(r.db,n);}catch(s){throw r.close(),s}return r}findThread(e,n,r){let s=drizzleOrm.eq(T.id,n),o=r===void 0?s:r===null?drizzleOrm.and(s,drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(s,drizzleOrm.eq(T.workspace_id,r));return e.select().from(T).where(o).limit(1).get()}findRegenerationRun(e,n,r){let s=e.select().from($).where(drizzleOrm.eq($.id,n)).limit(1).get();if(s&&!(r!==void 0&&!this.findThread(e,s.thread_id,r)))return s}resolveWorkspaceId(e){if(P(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:T.workspace_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof g?r:new g("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(P(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,n);return s?On(s):null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){Ql(e);let n=Rn(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||Pe(`Thread ${e.threadId} not found`);let u=On(i),d=e.title!==void 0,c=d&&e.title!==u.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==u.priority,f=e.state!==void 0&&e.state!==u.state,h=c||p||f;if(!h&&!l)return u;let m=i.metadata;(p||f)&&(m=Fa(i.metadata,{priority:e.priority,state:e.state}));let w={};if(h&&(w.metadata=m,w.updated_at=r),c&&(w.title=e.title),d&&(w.title_locked=1),o.update(T).set(w).where(e.workspaceId===void 0?drizzleOrm.eq(T.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.eq(T.workspace_id,e.workspaceId))).run(),!h){let L={...i,title_locked:1};return On(L)}let k=Sn(o,i.id)+1;In(o,i.id)||(An(o,i,n,r,k),k+=1),c&&(kt(o,{threadId:i.id,seq:k,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),k+=1),p&&(kt(o,{threadId:i.id,seq:k,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),k+=1),f&&kt(o,{threadId:i.id,seq:k,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let C={...i,title:c?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return On(C)},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to update thread snapshot",o)}finally{s.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(P(e,"threadId"),!fs$1.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(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,e)).get()?.maxSeq??0:null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read latest thread event sequence",s)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(P(e,"threadId"),P(n,"workspaceId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...oa,"completed","done","error"]),drizzleOrm.or(drizzleOrm.isNull(a.parent_task_id),drizzleOrm.eq(a.parent_task_id,"")),drizzleOrm.sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.asc(a.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read completed thread highlight turns",s)}finally{r.close();}}createHighlightRegenerationRun(e){P(e.threadId,"threadId"),P(e.workspaceId,"workspaceId"),P(e.requestId,"requestId"),P(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&P(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findThread(s,e.threadId,e.workspaceId);o||Pe(`Thread ${e.threadId} not found`);let i=s.select().from($).where(drizzleOrm.and(drizzleOrm.eq($.thread_id,o.id),drizzleOrm.eq($.request_id,e.requestId))).orderBy(drizzleOrm.desc($.requested_at),drizzleOrm.desc($.id)).limit(1).get();if(i)return {run:i,created:!1};let u=s.select().from($).where(drizzleOrm.and(drizzleOrm.eq($.thread_id,o.id),drizzleOrm.inArray($.status,kr))).orderBy(drizzleOrm.asc($.requested_at),drizzleOrm.asc($.id)).limit(1).get();if(u)throw new js(u);let d=e.runId??yn("thr");s.insert($).values({id:d,thread_id:o.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 c=s.select().from($).where(drizzleOrm.eq($.id,d)).get();if(!c)throw new g("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to create highlight regeneration run",s)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(P(e,"runId"),n!==void 0&&P(n,"workspaceId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to read highlight regeneration run",s)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(P(e,"threadId"),P(n,"workspaceId"),P(r,"requestId"),!fs$1.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{return this.findThread(s.db,e,n)?s.db.select().from($).where(drizzleOrm.and(drizzleOrm.eq($.thread_id,e),drizzleOrm.eq($.request_id,r))).orderBy(drizzleOrm.desc($.requested_at),drizzleOrm.desc($.id)).limit(1).get()??null:null}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to read highlight regeneration request",o)}finally{s.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){P(e,"runId"),n!==void 0&&P(n,"workspaceId");let r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findRegenerationRun(o,e,n);if(i||Pe(`Highlight regeneration run ${e} not found`),Bs(i.status)||W(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;o.update($).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq($.id,i.id),drizzleOrm.eq($.status,"queued"))).run();let u=o.select().from($).where(drizzleOrm.eq($.id,i.id)).get();if(!u)throw new g("DB_ERROR","Highlight regeneration run start did not return a row");return u},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to start highlight regeneration run",o)}finally{s.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){P(e.runId,"runId"),P(e.errorCode,"errorCode"),e.workspaceId!==void 0&&P(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findRegenerationRun(s,e.runId,e.workspaceId);if(o||Pe(`Highlight regeneration run ${e.runId} not found`),Bs(o.status)||W(`invalid highlight regeneration status: ${o.status}`),o.status==="completed"||o.status==="failed")return o;s.update($).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq($.id,o.id),drizzleOrm.inArray($.status,kr))).run();let i=s.select().from($).where(drizzleOrm.eq($.id,o.id)).get();if(!i)throw new g("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to fail highlight regeneration run",s)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=jl){P(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update($).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray($.status,kr)).run().changes,{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to recover interrupted highlight runs",s)}finally{r.close();}}completeHighlightRegenerationRun(e){P(e.runId,"runId"),P(e.threadId,"threadId"),P(e.workspaceId,"workspaceId"),P(e.detectorVersion,"detectorVersion");let n=rp(e.candidates),r=Rn(e),s=this.openHandle(true),o=false;try{return s.db.transaction(i=>{let u=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!u||u.thread_id!==e.threadId)&&Pe(`Highlight regeneration run ${e.runId} not found`),Bs(u.status)||W(`invalid highlight regeneration status: ${u.status}`),u.status==="failed")throw new g("CONFLICT","Highlight regeneration run has already failed");if(u.status==="completed")return {run:u,deletedCount:0,createdCount:0,previousAutoCount:u.previous_auto_count??0,newAutoCount:u.new_auto_count??0};o=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||Pe(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&W("detectorVersion does not match the regeneration run");let c=i.select().from(D).where(drizzleOrm.eq(D.thread_id,d.id)).orderBy(drizzleOrm.asc(D.created_at),drizzleOrm.asc(D.id)).all(),l=new Set(n.map(O=>O.contentFingerprint)),p=c.filter(O=>O.source==="auto"&&O.status==="active"&&O.revision===0&&!l.has(O.content_fingerprint??"")),f=c.filter(O=>O.source==="auto"&&O.status==="active").length,h=new Set(c.filter(O=>!p.includes(O)&&O.content_fingerprint).map(O=>O.content_fingerprint)),m=n.filter(O=>!h.has(O.contentFingerprint)),w=new Date().toISOString(),k=Sn(i,d.id)+1;In(i,d.id)||(An(i,d,r,w,k),k+=1);for(let O of p)i.delete(D).where(drizzleOrm.eq(D.id,O.id)).run(),op(i,O,r,w,k,{runId:e.runId,reason:Wl}),k+=1;let C=0,L=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let O of m){let Y=yn("thl");i.insert(D).values({id:Y,thread_id:d.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:w,updated_at:w,agent_id:L,source_task_id:O.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:O.contentFingerprint,dismissed_at:null}).run();let ue=i.select().from(D).where(drizzleOrm.eq(D.id,Y)).get();if(!ue)throw new g("DB_ERROR","Regenerated highlight insert did not return a row");Tr(i,ue,r,w,"thread.highlight.created",k),k+=1,C+=1;}let E=i.select().from(D).where(drizzleOrm.eq(D.thread_id,d.id)).all().filter(O=>O.source==="auto"&&O.status==="active").length;kt(i,{threadId:d.id,seq:k,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:w,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:f,newAutoCount:E,deletedCount:p.length,createdCount:C}}),i.update($).set({status:"completed",started_at:u.started_at??w,completed_at:w,error_code:null,previous_auto_count:f,new_auto_count:E}).where(drizzleOrm.and(drizzleOrm.eq($.id,u.id),drizzleOrm.inArray($.status,kr))).run();let v=i.select().from($).where(drizzleOrm.eq($.id,u.id)).get();if(!v)throw new g("DB_ERROR","Highlight regeneration completion did not return a row");return {run:v,deletedCount:p.length,createdCount:C,previousAutoCount:f,newAutoCount:E}},{behavior:"immediate"})}catch(i){if(o)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Gl});}catch{}throw i instanceof g?i:new g("DB_ERROR","Failed to complete highlight regeneration",i)}finally{s.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let s=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;P(s.threadId,"threadId"),P(s.workspaceId,"workspaceId");let o=Zl(s);if(!fs$1.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,s.threadId,s.workspaceId))return null;let u=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${B.seq}), 0)`}).from(B).where(drizzleOrm.eq(B.thread_id,s.threadId)).get()?.maxSeq??0,d;s.beforeSeq!==void 0?d=i.db.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.lt(B.seq,s.beforeSeq))).orderBy(drizzleOrm.desc(B.seq)).limit(o+1).all().reverse():s.afterSeq!==void 0?d=i.db.select().from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.sql`${B.seq} > ${s.afterSeq}`)).orderBy(drizzleOrm.asc(B.seq)).limit(o+1).all():d=i.db.select().from(B).where(drizzleOrm.eq(B.thread_id,s.threadId)).orderBy(drizzleOrm.desc(B.seq)).limit(o+1).all().reverse();let c=d.length>o,l=s.afterSeq!==void 0?d.slice(0,o):c?d.slice(1):d,p=!1,f=l[0];return f&&(p=!!i.db.select({id:B.id}).from(B).where(drizzleOrm.and(drizzleOrm.eq(B.thread_id,s.threadId),drizzleOrm.lt(B.seq,f.seq))).limit(1).get()),{items:l,latestSeq:u,hasMoreOlder:p}}catch(u){throw u instanceof g?u:new g("DB_ERROR","Failed to list thread timeline",u)}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=tp(e),r=Rn(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);if(u||Pe(`Thread ${e.threadId} not found`),n.source==="auto"){let f=i.select().from(D).where(drizzleOrm.and(drizzleOrm.eq(D.thread_id,e.threadId),drizzleOrm.eq(D.source_task_id,n.sourceTaskId),drizzleOrm.eq(D.detector_version,n.detectorVersion),drizzleOrm.eq(D.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(D.created_at),drizzleOrm.asc(D.id)).limit(1).get();if(f)return f}let d=e.id??yn("thl"),c={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:s,updated_at:s,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(D).values(c).run();let l=i.select().from(D).where(drizzleOrm.eq(D.id,d)).get();if(!l)throw new g("DB_ERROR","Highlight insert did not return a row");let p=Sn(i,u.id)+1;return In(i,u.id)||(An(i,u,r,s,p),p+=1),Tr(i,l,r,s,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof g?i:new g("DB_ERROR","Failed to create thread highlight",i)}finally{o.close();}}updateHighlight(e){P(e.threadId,"threadId"),P(e.workspaceId,"workspaceId"),P(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&W("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&W("highlight update requires at least one field"),e.kind!==void 0&&zs(e.kind);let n=e.text===void 0?void 0:Gs(e.text),r=Rn(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);u||Pe(`Thread ${e.threadId} not found`);let d=i.select().from(D).where(drizzleOrm.and(drizzleOrm.eq(D.id,e.highlightId),drizzleOrm.eq(D.thread_id,u.id))).limit(1).get();if(d||Pe(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new bn(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new bn(u.id,d.id,e.expectedRevision,d.revision);let c=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,f=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||f.length===0)&&W("highlight projection is incomplete");let h=c!==d.kind||l!==d.text||p!==d.covers_from_task_id||f!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&h?"manual":d.source;if(!(h||m!==d.source))return d;let k=d.revision+1;i.update(D).set({source:m,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:f,revision:k,updated_at:s}).where(drizzleOrm.and(drizzleOrm.eq(D.id,d.id),drizzleOrm.eq(D.revision,d.revision))).run();let C=i.select().from(D).where(drizzleOrm.eq(D.id,d.id)).get();if(!C)throw new g("DB_ERROR","Highlight update did not return a row");let L=Sn(i,u.id)+1;return In(i,u.id)||(An(i,u,r,s,L),L+=1),Tr(i,C,r,s,"thread.highlight.updated",L,d),C},{behavior:"immediate"})}catch(i){throw i instanceof g?i:new g("DB_ERROR","Failed to update thread highlight",i)}finally{o.close();}}dismissHighlight(e){P(e.threadId,"threadId"),P(e.workspaceId,"workspaceId"),P(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&W("expectedRevision must be a non-negative integer");let n=Rn(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||Pe(`Thread ${e.threadId} not found`);let u=o.select().from(D).where(drizzleOrm.and(drizzleOrm.eq(D.id,e.highlightId),drizzleOrm.eq(D.thread_id,i.id))).limit(1).get();if(u||Pe(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new bn(i.id,u.id,e.expectedRevision,u.revision);if(u.status==="dismissed")return u;let d=u.revision+1;o.update(D).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(D.id,u.id),drizzleOrm.eq(D.revision,u.revision))).run();let c=o.select().from(D).where(drizzleOrm.eq(D.id,u.id)).get();if(!c)throw new g("DB_ERROR","Highlight dismissal did not return a row");let l=Sn(o,i.id)+1;return In(o,i.id)||(An(o,i,n,r,l),l+=1),Tr(o,c,n,r,"thread.highlight.deleted",l,u),c},{behavior:"immediate"})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to dismiss thread highlight",o)}finally{s.close();}}listActiveHighlights(e,n,r={}){if(P(e,"threadId"),P(n,"workspaceId"),r.taskId!==void 0&&P(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&P(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&P(r.coversToTaskId,"coversToTaskId"),!fs$1.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{if(!this.findThread(s.db,e,n))return null;let i=s.db.select().from(D).where(drizzleOrm.and(drizzleOrm.eq(D.thread_id,e),drizzleOrm.eq(D.status,"active"))).orderBy(drizzleOrm.asc(D.created_at),drizzleOrm.asc(D.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let u=s.db.all(drizzleOrm.sql`
388
388
  SELECT id, started_at FROM tasks WHERE thread_id = ${e}
389
389
  ORDER BY started_at ASC, id ASC
390
390
  `),d=new Map(u.map((f,h)=>[f.id,h])),c=r.taskId===void 0?void 0:d.get(r.taskId),l=r.coversFromTaskId===void 0?void 0:d.get(r.coversFromTaskId),p=r.coversToTaskId===void 0?void 0:d.get(r.coversToTaskId);return i.filter(f=>{let h=d.get(f.covers_from_task_id),m=d.get(f.covers_to_task_id);if(h===void 0||m===void 0)return !1;let w=Math.min(h,m),k=Math.max(h,m);return !(c!==void 0&&(c<w||c>k)||l!==void 0&&k<l||p!==void 0&&w>p)})}catch(o){throw o instanceof g?o:new g("DB_ERROR","Failed to list active thread highlights",o)}finally{s.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};_();ot();Et();Rt();rt();It();$r();var J=class extends g{reason;constructor(e,n="VALIDATION",r=e,s){super(n,r,s),this.name="CommonCodeRepositoryError",this.reason=e;}},za="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function gp(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=za[n%za.length];return e.slice(0,12)}function Ka(){return `c_${gp()}`}function hp(t){return typeof t=="string"&&Mr.includes(t)}function _p(t){return typeof t=="string"&&Hr.includes(t)}function zt(t){if(!hp(t))throw new J("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Va(t){if(!_p(t))throw new J("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function Ja(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new J("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function Kt(t){if(typeof t!="string"||t.trim().length===0)throw new J("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Er(t){if(typeof t!="string"||t.trim().length===0)throw new J("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function nt(t,e){return drizzleOrm.and(drizzleOrm.eq(S.code_group,t),drizzleOrm.or(drizzleOrm.isNull(S.workspace_id),drizzleOrm.eq(S.workspace_id,e)))}var Rr=class extends we{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=pe.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs$1.existsSync(n))throw new g("NOT_FOUND","Database not found");e&&fs$1.mkdirSync(pe.dirname(n),{recursive:true});let r=U(n);if(e)try{De(r.db,n);}catch(s){throw r.close(),s}return r}listSelectable(e,n){if(zt(e),Kt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(drizzleOrm.and(nt(e,n),drizzleOrm.eq(S.is_archived,0))).orderBy(drizzleOrm.asc(S.sort_order),drizzleOrm.asc(S.code)).all()}catch(s){throw new g("DB_ERROR","Failed to list selectable common codes",s)}finally{r.close();}}listForHistory(e,n){if(zt(e),Kt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(nt(e,n)).orderBy(drizzleOrm.asc(S.sort_order),drizzleOrm.asc(S.code)).all()}catch(s){throw new g("DB_ERROR","Failed to list common-code history",s)}finally{r.close();}}reorder(e){let n=e.group;if(zt(n),Kt(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let s of e.codes)Er(s);if(new Set(e.codes).size!==e.codes.length)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(S).where(nt(n,e.workspaceId)).all(),i=o.filter(h=>h.is_archived===0),u=new Set(o.map(h=>h.code)),d=new Set(i.map(h=>h.code)),c=e.codes.find(h=>!u.has(h));if(c)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(h=>!d.has(h)))throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let l=new Map(i.map(h=>[h.code,h])),p=e.codes.map(h=>{let m=l.get(h);if(!m)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${h}`);return m}),f;for(let[h,m]of p.entries())m.sort_order!==h&&(f??=new Date().toISOString(),s.update(S).set({sort_order:h,updated_at:f}).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,n),drizzleOrm.eq(S.code,m.code))).run());return s.select().from(S).where(nt(n,e.workspaceId)).orderBy(drizzleOrm.asc(S.sort_order),drizzleOrm.asc(S.code)).all()},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to reorder common codes",s)}finally{r.close();}}resolve(e,n){if(zt(e),Er(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(S).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,e),drizzleOrm.eq(S.code,n))).limit(1).get()??null}catch(s){throw new g("DB_ERROR","Failed to resolve common code",s)}finally{r.close();}}createThreadState(e){Kt(e.workspaceId);let n=Ja(e.name);Va(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{if(s.select({code:S.code}).from(S).where(drizzleOrm.and(nt("THREAD_STATE",e.workspaceId),drizzleOrm.eq(S.is_archived,0),drizzleOrm.eq(S.code_name,n))).limit(1).get())throw new J("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=s.select({maxSortOrder:drizzleOrm.sql`max(${S.sort_order})`}).from(S).where(nt("THREAD_STATE",e.workspaceId)).get(),u=new Date().toISOString(),d=Ka();for(;s.select({code:S.code}).from(S).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,"THREAD_STATE"),drizzleOrm.eq(S.code,d))).limit(1).get();)d=Ka();s.insert(S).values({code_group:"THREAD_STATE",code:d,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:u,updated_at:u}).run();let c=s.select().from(S).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,"THREAD_STATE"),drizzleOrm.eq(S.code,d))).limit(1).get();if(!c)throw new g("DB_ERROR","Created common code could not be read back");return c},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to create thread state common code",s)}finally{r.close();}}updateDisplay(e){if(zt(e.group),Er(e.code),Kt(e.workspaceId),e.name===void 0&&e.color===void 0)throw new J("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:Ja(e.name);e.color!==void 0&&Va(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(S).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,e.group),drizzleOrm.eq(S.code,e.code))).limit(1).get();if(!o)throw new J("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(o,e.workspaceId),n===null&&o.is_builtin!==1)throw new J("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&o.is_archived===0){let d=drizzleOrm.and(nt(e.group,e.workspaceId),drizzleOrm.eq(S.is_archived,0));if(s.select({code:S.code}).from(S).where(drizzleOrm.and(d,drizzleOrm.eq(S.code_name,n),drizzleOrm.sql`${S.code} <> ${e.code}`)).limit(1).get())throw new J("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),s.update(S).set(i).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,e.group),drizzleOrm.eq(S.code,e.code))).run();let u=s.select().from(S).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,e.group),drizzleOrm.eq(S.code,e.code))).limit(1).get();if(!u)throw new g("DB_ERROR","Updated common code could not be read back");return u},{behavior:"immediate"})}catch(s){throw s instanceof g?s:new g("DB_ERROR","Failed to update common-code display values",s)}finally{r.close();}}archive(e,n,r,s=true){if(zt(e),Er(n),Kt(r),typeof s!="boolean")throw new J("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let o=this.openHandle(true);try{return o.db.transaction(i=>{let u=i.select().from(S).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,e),drizzleOrm.eq(S.code,n))).limit(1).get();if(!u)throw new J("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(u.is_builtin===1)throw new J("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(u,r),!s&&u.code_name!==null&&i.select({code:S.code}).from(S).where(drizzleOrm.and(nt(e,r),drizzleOrm.eq(S.is_archived,0),drizzleOrm.eq(S.code_name,u.code_name),drizzleOrm.ne(S.code,n))).limit(1).get())throw new J("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${u.code_name}`);i.update(S).set({is_archived:s?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,e),drizzleOrm.eq(S.code,n))).run();let d=i.select().from(S).where(drizzleOrm.and(drizzleOrm.eq(S.code_group,e),drizzleOrm.eq(S.code,n))).limit(1).get();if(!d)throw new g("DB_ERROR","Archived common code could not be read back");return d},{behavior:"immediate"})}catch(i){throw i instanceof g?i:new g("DB_ERROR","Failed to archive common code",i)}finally{o.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new J("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};vt();_();var Tt={threadContext:"crewx_thread_context",apps:"apps",crewxUiState:"crewx_ui_state"};function Tp(t){return t.replace(new RegExp(`<${Tt.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${Tt.threadContext}>`,"g"),"").replace(new RegExp(`<${Tt.apps}\\b[^>]*>[\\s\\S]*?<\\/${Tt.apps}>`,"g"),"").replace(new RegExp(`<${Tt.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${Tt.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`