@crewx/sdk 0.9.0-rc.75 → 0.9.0-rc.76

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.
@@ -1,4 +1,4 @@
1
- import*as st from'path';import st__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import jn,{homedir}from'os';import {createHash,randomBytes}from'crypto';import {sql,eq,desc,and,isNull,lt,or,notLike,asc,like,inArray,gte,isNotNull,ne as ne$1}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey}from'drizzle-orm/sqlite-core';var Bt=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Nn=()=>fileURLToPath(import.meta.url),Cn=()=>st__default.dirname(Nn()),m=Cn();var ht=class{detach(t){}};function Ne(n){let t=e=>String(e).padStart(2,"0");return `${n.getFullYear()}${t(n.getMonth()+1)}${t(n.getDate())}T${t(n.getHours())}${t(n.getMinutes())}${t(n.getSeconds())}`}function ae(n){let t=n.toISOString();return `${t.slice(0,10)} ${t.slice(11,19)} UTC`}var de=class extends ht{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let r=Ne(e.timestamp),i=join(this.logsDir,`${r}_${e.traceId}.log`);this.logFiles.set(e.traceId,i);let o=`=== TASK LOG: ${e.traceId} ===
1
+ import*as st from'path';import st__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import jn,{homedir}from'os';import {createHash,randomBytes}from'crypto';import {sql,eq,desc,and,isNull,lt,or,notLike,asc,like,inArray,gte,isNotNull,ne as ne$1}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey}from'drizzle-orm/sqlite-core';var Ut=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Cn=()=>fileURLToPath(import.meta.url),Dn=()=>st__default.dirname(Cn()),m=Dn();var ht=class{detach(t){}};function Ne(n){let t=e=>String(e).padStart(2,"0");return `${n.getFullYear()}${t(n.getMonth()+1)}${t(n.getDate())}T${t(n.getHours())}${t(n.getMinutes())}${t(n.getSeconds())}`}function ae(n){let t=n.toISOString();return `${t.slice(0,10)} ${t.slice(11,19)} UTC`}var de=class extends ht{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let r=Ne(e.timestamp),i=join(this.logsDir,`${r}_${e.traceId}.log`);this.logFiles.set(e.traceId,i);let o=`=== TASK LOG: ${e.traceId} ===
2
2
  CrewX Version: ${this.version}
3
3
  Mode: ${e.mode}
4
4
  Agent: ${e.agentRef}
@@ -8,13 +8,13 @@ Message: ${e.message}
8
8
  `;writeFileSync(i,o,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",e=>{try{let r=this.logFiles.get(e.traceId);if(!r)return;let i=new Date().toISOString();appendFileSync(r,`[${i}] STDOUT: ${e.output}
9
9
  `,"utf8");}catch{}}),t.on("task:end",e=>{try{let r=this.logFiles.get(e.traceId);if(!r)return;let i=ae(new Date),o=e.error?`failed: ${e.error.message}`:"completed successfully",a=`[${i}] INFO: Task ${o} in ${e.durationMs}ms
10
10
  [${i}] INFO: Process closed with exit code: ${e.error?1:0}
11
- `;appendFileSync(r,a,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Pn(n){let t=st.resolve(n);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,r)=>`${r.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function $e(n){let t=Pn(n);return createHash("sha256").update(t).digest("hex")}var J=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(jn.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var Un=32*1024*1024;function b(n){let t=Bt("better-sqlite3"),{drizzle:e}=Bt("drizzle-orm/better-sqlite3"),r=new t(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Un}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),r.exec("PRAGMA optimize"),{db:e(r),runRaw:(i,o=[])=>r.prepare(i).run(...o),close:()=>r.close()}}var Le=new Set,Bn={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"};function ce(n,t){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Fn(n,t){if(t>0||!ce(n,"tasks"))return;let e=n.all("PRAGMA table_info(tasks)"),r=new Set(e.map(i=>i.name));for(let[i,o]of Object.entries(Bn))r.has(i)||n.run(`ALTER TABLE tasks ADD COLUMN ${i} ${o}`);}var zn={"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"}};function Wn(n,t,e){if(!ce(n,"__drizzle_migrations")||!ce(n,"tasks"))return;let r=n.all(e`SELECT hash FROM __drizzle_migrations`),i=new Set(r.map(a=>a.hash)),o=JSON.parse(readFileSync(st__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of o.entries){let d=zn[a.tag];if(!d)continue;let c=st__default.join(t,`${a.tag}.sql`);if(!existsSync(c))continue;let l=readFileSync(c,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(i.has(u))continue;let h=n.all("PRAGMA table_info(tasks)"),g=new Set(h.map(f=>f.name));for(let[f,A]of Object.entries(d))g.has(f)||(n.run(`ALTER TABLE tasks ADD COLUMN ${f} ${A}`),g.add(f));}}function Kn(n,t,e){let r=n.all(e`SELECT hash FROM __drizzle_migrations`),i=new Set(r.map(a=>a.hash)),o=JSON.parse(readFileSync(st__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of o.entries){let d=st__default.join(t,`${a.tag}.sql`);if(!existsSync(d))continue;let c=readFileSync(d,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(i.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,h=[],g;for(;(g=u.exec(c))!==null;)h.push({table:g[1],column:g[2]});if(h.length===0||!c.split(/-->\s*statement-breakpoint/).map(N=>N.trim()).filter(Boolean).every(N=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(N)))continue;h.every(({table:N,column:I})=>n.all(`PRAGMA table_info("${N}")`).some(j=>j.name===I))&&n.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${a.when})`);}}function Gn(n){let{migrate:t}=Bt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Bt("drizzle-orm"),r=[st__default.join(m,"../migrations"),st__default.join(m,"migrations"),st__default.join(m,"../../../../drizzle/migrations"),st__default.join(process.cwd(),"drizzle/migrations")],i=r.find(l=>existsSync(st__default.join(l,"meta/_journal.json")));if(!i)throw new Error(`migrations folder not found. Searched:
11
+ `;appendFileSync(r,a,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Hn(n){let t=st.resolve(n);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,r)=>`${r.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Le(n){let t=Hn(n);return createHash("sha256").update(t).digest("hex")}var _=class extends Error{code;cause;constructor(t,e,r){super(e),this.name="RepositoryError",this.code=t,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};var J=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(jn.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var Un=32*1024*1024;function A(n){let t=Ut("better-sqlite3"),{drizzle:e}=Ut("drizzle-orm/better-sqlite3"),r=new t(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Un}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),{db:e(r),runRaw:(i,o=[])=>r.prepare(i).run(...o),close:()=>r.close()}}var $e=new Set,Fn={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"};function ce(n,t){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function zn(n,t){if(t>0||!ce(n,"tasks"))return;let e=n.all("PRAGMA table_info(tasks)"),r=new Set(e.map(i=>i.name));for(let[i,o]of Object.entries(Fn))r.has(i)||n.run(`ALTER TABLE tasks ADD COLUMN ${i} ${o}`);}var Wn={"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"}};function Kn(n,t,e){if(!ce(n,"__drizzle_migrations")||!ce(n,"tasks"))return;let r=n.all(e`SELECT hash FROM __drizzle_migrations`),i=new Set(r.map(a=>a.hash)),o=JSON.parse(readFileSync(st__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of o.entries){let d=Wn[a.tag];if(!d)continue;let c=st__default.join(t,`${a.tag}.sql`);if(!existsSync(c))continue;let l=readFileSync(c,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(i.has(u))continue;let h=n.all("PRAGMA table_info(tasks)"),g=new Set(h.map(f=>f.name));for(let[f,b]of Object.entries(d))g.has(f)||(n.run(`ALTER TABLE tasks ADD COLUMN ${f} ${b}`),g.add(f));}}function Gn(n,t,e){let r=n.all(e`SELECT hash FROM __drizzle_migrations`),i=new Set(r.map(a=>a.hash)),o=JSON.parse(readFileSync(st__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of o.entries){let d=st__default.join(t,`${a.tag}.sql`);if(!existsSync(d))continue;let c=readFileSync(d,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(i.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,h=[],g;for(;(g=u.exec(c))!==null;)h.push({table:g[1],column:g[2]});if(h.length===0||!c.split(/-->\s*statement-breakpoint/).map(N=>N.trim()).filter(Boolean).every(N=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(N)))continue;h.every(({table:N,column:I})=>n.all(`PRAGMA table_info("${N}")`).some(q=>q.name===I))&&n.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${a.when})`);}}function Xn(n){let{migrate:t}=Ut("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Ut("drizzle-orm"),r=[st__default.join(m,"../migrations"),st__default.join(m,"migrations"),st__default.join(m,"../../../../drizzle/migrations"),st__default.join(process.cwd(),"drizzle/migrations")],i=r.find(l=>existsSync(st__default.join(l,"meta/_journal.json")));if(!i)throw new Error(`migrations folder not found. Searched:
12
12
  ${r.join(`
13
- `)}`);let o=n.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;o?.cnt&&(a=n.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Fn(n,a),o?.cnt&&(Kn(n,i,e),Wn(n,i,e)),t(n,{migrationsFolder:i});let c=(n.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function gt(n,t){Le.has(t)||(Gn(n),Le.add(t));}var _=class extends Error{code;cause;constructor(t,e,r){super(e),this.name="RepositoryError",this.code=t,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};var Rt=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var s=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},n=>({log_storage_check:check("tasks_log_storage_ck",sql`${n.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));var Q=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>s.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},n=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(n.task_id,n.seq)}));var rr="json_extract(metadata, '$.threadTitle.state')",sr="json_extract(metadata, '$.threadTitle.priority')",p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Rt.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(n.workspace_id,n.updated_at),idx_threads_title:index("idx_threads_title").on(n.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(n.workspace_id,sql.raw(rr)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(n.workspace_id,sql.raw(sr))}));var ar=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>ar.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},n=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(n.workspace_id,n.month)}));sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},n=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(n.workspace_id,sql`${n.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},n=>({pk:primaryKey({columns:[n.notification_id,n.user_id]})}));sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},n=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(n.workspace_id,n.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(n.workspace_id,n.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},n=>({idCheck:check("ui_instances_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128 AND ${n.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${n.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${n.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${n.definition_hash}) = 64 AND ${n.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${n.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${n.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${n.domain_ref_json}) AND json_type(${n.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${n.state_json}) AND json_type(${n.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${n.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${n.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${n.granted_capabilities_json}) AND json_type(${n.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${n.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${n.updated_at} >= ${n.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(n.workspace_id,n.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},n=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${n.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${n.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${n.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${n.actor_json}) AND json_type(${n.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${n.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${n.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${n.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${n.after_revision} IS NULL OR ${n.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${n.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${n.outcome} IS NULL OR ${n.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${n.input_json}) AND json_type(${n.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${n.result_json} IS NULL OR (json_valid(${n.result_json}) AND json_type(${n.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${n.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${n.settled_at} IS NULL OR ${n.settled_at} >= ${n.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
13
+ `)}`);let o=n.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;o?.cnt&&(a=n.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),zn(n,a),o?.cnt&&(Gn(n,i,e),Kn(n,i,e)),t(n,{migrationsFolder:i});let c=(n.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function gt(n,t){$e.has(t)||(Xn(n),$e.add(t));}var Rt=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var s=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},n=>({log_storage_check:check("tasks_log_storage_ck",sql`${n.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));var Q=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>s.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},n=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(n.task_id,n.seq)}));var sr="json_extract(metadata, '$.threadTitle.state')",ir="json_extract(metadata, '$.threadTitle.priority')",p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Rt.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(n.workspace_id,n.updated_at),idx_threads_title:index("idx_threads_title").on(n.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(n.workspace_id,sql.raw(sr)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(n.workspace_id,sql.raw(ir))}));var dr=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>dr.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},n=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(n.workspace_id,n.month)}));sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},n=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(n.workspace_id,sql`${n.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},n=>({pk:primaryKey({columns:[n.notification_id,n.user_id]})}));sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},n=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(n.workspace_id,n.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(n.workspace_id,n.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},n=>({idCheck:check("ui_instances_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128 AND ${n.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${n.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${n.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${n.definition_hash}) = 64 AND ${n.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${n.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${n.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${n.domain_ref_json}) AND json_type(${n.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${n.state_json}) AND json_type(${n.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${n.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${n.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${n.granted_capabilities_json}) AND json_type(${n.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${n.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${n.updated_at} >= ${n.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(n.workspace_id,n.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},n=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${n.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${n.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${n.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${n.actor_json}) AND json_type(${n.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${n.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${n.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${n.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${n.after_revision} IS NULL OR ${n.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${n.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${n.outcome} IS NULL OR ${n.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${n.input_json}) AND json_type(${n.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${n.result_json} IS NULL OR (json_valid(${n.result_json}) AND json_type(${n.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${n.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${n.settled_at} IS NULL OR ${n.settled_at} >= ${n.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
14
14
  (${n.status} = 'requested' AND ${n.after_revision} IS NULL AND ${n.outcome} IS NULL AND ${n.settled_at} IS NULL)
15
15
  OR
16
16
  (${n.status} = 'settled' AND ${n.after_revision} IS NOT NULL AND ${n.outcome} IS NOT NULL AND ${n.settled_at} IS NOT NULL)
17
- )`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(n.instance_id,n.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(n.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(n.requested_at)}));var Xe=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},n=>({idCheck:check("projects_id_ck",sql`${n.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${n.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${n.stages_json}) AND json_type(${n.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${n.stage_index} >= 1`)}));sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>Xe.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},n=>({idCheck:check("project_criteria_id_ck",sql`${n.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${n.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${n.evidence_json}) AND json_type(${n.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(n.project_id,n.position)}));sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>Xe.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},n=>({idCheck:check("project_events_id_ck",sql`${n.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(n.project_id,n.seq)}));sqliteTable("common_codes",{code_group:text("code_group").notNull(),code:text("code").notNull(),code_name:text("code_name"),color:text("color").notNull().default("gray"),sort_order:integer("sort_order").notNull(),workspace_id:text("workspace_id"),is_builtin:integer("is_builtin").notNull().default(0),is_archived:integer("is_archived").notNull().default(0),metadata:text("metadata"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},n=>({pk:primaryKey({columns:[n.code_group,n.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${n.metadata} IS NULL OR (json_valid(${n.metadata}) AND json_type(${n.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${n.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${n.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(n.code_group,n.is_archived,n.sort_order)}));var Qe=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted"],Ze=["user","agent","system"],tn=["auto","manual"],en=["decision","judgment","issue","result","pivot"];var S=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},n=>({typeCheck:check("thread_events_type_ck",sql`${n.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted')`),actorTypeCheck:check("thread_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(n.thread_id,n.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(n.thread_id,n.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(n.thread_id,n.seq)})),E=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},n=>({sourceCheck:check("thread_highlights_source_ck",sql`${n.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${n.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${n.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${n.status} = 'dismissed' OR (${n.text} IS NOT NULL AND length(${n.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${n.covers_from_task_id}) > 0 AND length(${n.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${n.source} = 'manual' OR (${n.source} = 'auto' AND ${n.source_task_id} IS NOT NULL AND ${n.detector_version} IS NOT NULL AND ${n.content_fingerprint} IS NOT NULL AND length(${n.source_task_id}) > 0 AND length(${n.detector_version}) > 0 AND length(${n.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(n.thread_id,n.status,n.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(n.thread_id,n.covers_from_task_id,n.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(n.thread_id,n.source_task_id,n.detector_version,n.content_fingerprint).where(sql`${n.source} = 'auto'`)}));function nn(n){let t=n.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}function dn(n,t){let e=t===void 0?"":` at index ${t}`;if(!n||typeof n!="object")throw new _("VALIDATION",`Task log entry${e} must be an object`);if(typeof n.timestamp!="string"||typeof n.level!="string"||typeof n.message!="string")throw new _("VALIDATION",`Task log entry${e} must contain string timestamp, level, and message fields`);return {timestamp:n.timestamp,level:n.level,message:n.message}}function on(n,t){if(t===null||t.trim()==="")return [];let e;try{e=JSON.parse(t);}catch(r){throw new _("DB_ERROR",`Malformed legacy task logs: ${n}`,r)}if(!Array.isArray(e))throw new _("DB_ERROR",`Malformed legacy task logs: ${n} (expected an array)`);try{return e.map((r,i)=>dn(r,i))}catch(r){throw r instanceof _?new _("DB_ERROR",`Malformed legacy task logs: ${n}`,r):r}}function cn(n){if(n.log_storage!=="blob"&&n.log_storage!=="events")throw new _("DB_ERROR",`Invalid task log storage for task: ${n.id}`);if(!Number.isInteger(n.last_log_seq)||n.last_log_seq<0)throw new _("DB_ERROR",`Invalid task log sequence for task: ${n.id}`);if(!Number.isInteger(n.log_revision)||n.log_revision<0)throw new _("DB_ERROR",`Invalid task log revision for task: ${n.id}`);return n.log_storage}function an(n){return {taskId:n.id,source:cn(n),revision:n.log_revision,lastSeq:n.last_log_seq}}function Mr(n){if(!Number.isInteger(n)||n<0)throw new _("VALIDATION","Task log tail limit must be a non-negative integer")}var Yt=class extends J{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let i=dirname(e);existsSync(i)||mkdirSync(i,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let r=b(e);if(t)try{gt(r.db,e);}catch(i){throw r.close(),i}return r}findStateRow(t,e){return t.db.select({id:s.id,log_storage:s.log_storage,last_log_seq:s.last_log_seq,log_revision:s.log_revision,logs:s.logs}).from(s).where(eq(s.id,e)).limit(1).get()}findStateRowInTransaction(t,e){return t.select({id:s.id,log_storage:s.log_storage,last_log_seq:s.last_log_seq,log_revision:s.log_revision,logs:s.logs}).from(s).where(eq(s.id,e)).limit(1).get()}requireStateRowInTransaction(t,e){let r=this.findStateRowInTransaction(t,e);if(!r)throw new _("NOT_FOUND",`Task not found: ${e}`);return r}appendLog(t,e){return this.appendLogs(t,[e])}appendLogs(t,e){let r=e.map((o,a)=>dn(o,a));if(r.length===0){let o=this.getLogState(t);if(!o)throw new _("NOT_FOUND",`Task not found: ${t}`);return o}let i=this.openHandle(true);try{return i.db.transaction(a=>{let d=this.requireStateRowInTransaction(a,t),c=cn(d);if(c==="blob"){let g=on(t,d.logs);if(a.update(s).set({logs:JSON.stringify([...g,...r]),log_revision:sql`${s.log_revision} + 1`}).where(eq(s.id,t)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:c,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let l=d.last_log_seq+1,u=d.last_log_seq+r.length;if(a.insert(Q).values(r.map((g,f)=>({task_id:t,seq:l+f,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(s).set({last_log_seq:u,log_revision:sql`${s.log_revision} + 1`}).where(eq(s.id,t)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:c,revision:d.log_revision+1,lastSeq:u}},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to append task log",o)}finally{i.close();}}getLogState(t){if(!this.dbExists())return;let e=this.openHandle(false);try{let r=this.findStateRow(e,t);return r?an(r):void 0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to read task log state",r)}finally{e.close();}}readLogs(t){return this.readLogsInternal(t)}readLogsTail(t,e){return Mr(e),this.readLogsInternal(t,e)}readTail(t,e){return this.readLogsTail(t,e)}readLogsInternal(t,e){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(i=>{let o=this.findStateRowInTransaction(i,t);if(!o)return;let a=an(o);if(a.source==="blob"){let u=on(t,o.logs);return {...a,entries:e===void 0?u:u.slice(Math.max(0,u.length-e))}}let d=i.select({seq:Q.seq,timestamp:Q.timestamp,level:Q.level,message:Q.message}).from(Q).where(eq(Q.task_id,t)).orderBy(e===void 0?asc(Q.seq):desc(Q.seq)),l=(e===void 0?d.all():d.limit(e).all()).map(({timestamp:u,level:h,message:g})=>({timestamp:u,level:h,message:g}));return e!==void 0&&l.reverse(),{...a,entries:l}},{behavior:"deferred"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to read task logs",i)}finally{r.close();}}};var ke=40,ut="2026-05-09",zr="0.8.9-rc.13",_t=10,pt=parseInt(zr.split("rc.")[1]);function ln(){let n=sql`
17
+ )`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(n.instance_id,n.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(n.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(n.requested_at)}));var Xe=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},n=>({idCheck:check("projects_id_ck",sql`${n.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${n.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${n.stages_json}) AND json_type(${n.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${n.stage_index} >= 1`)}));sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>Xe.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},n=>({idCheck:check("project_criteria_id_ck",sql`${n.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${n.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${n.evidence_json}) AND json_type(${n.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(n.project_id,n.position)}));sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>Xe.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},n=>({idCheck:check("project_events_id_ck",sql`${n.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(n.project_id,n.seq)}));sqliteTable("common_codes",{code_group:text("code_group").notNull(),code:text("code").notNull(),code_name:text("code_name"),color:text("color").notNull().default("gray"),sort_order:integer("sort_order").notNull(),workspace_id:text("workspace_id"),is_builtin:integer("is_builtin").notNull().default(0),is_archived:integer("is_archived").notNull().default(0),metadata:text("metadata"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},n=>({pk:primaryKey({columns:[n.code_group,n.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${n.metadata} IS NULL OR (json_valid(${n.metadata}) AND json_type(${n.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${n.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${n.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(n.code_group,n.is_archived,n.sort_order)}));var Qe=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted"],Ze=["user","agent","system"],tn=["auto","manual"],en=["decision","judgment","issue","result","pivot"];var S=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},n=>({typeCheck:check("thread_events_type_ck",sql`${n.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted')`),actorTypeCheck:check("thread_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(n.thread_id,n.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(n.thread_id,n.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(n.thread_id,n.seq)})),E=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},n=>({sourceCheck:check("thread_highlights_source_ck",sql`${n.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${n.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${n.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${n.status} = 'dismissed' OR (${n.text} IS NOT NULL AND length(${n.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${n.covers_from_task_id}) > 0 AND length(${n.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${n.source} = 'manual' OR (${n.source} = 'auto' AND ${n.source_task_id} IS NOT NULL AND ${n.detector_version} IS NOT NULL AND ${n.content_fingerprint} IS NOT NULL AND length(${n.source_task_id}) > 0 AND length(${n.detector_version}) > 0 AND length(${n.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(n.thread_id,n.status,n.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(n.thread_id,n.covers_from_task_id,n.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(n.thread_id,n.source_task_id,n.detector_version,n.content_fingerprint).where(sql`${n.source} = 'auto'`)}));function nn(n){let t=n.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}function dn(n,t){let e=t===void 0?"":` at index ${t}`;if(!n||typeof n!="object")throw new _("VALIDATION",`Task log entry${e} must be an object`);if(typeof n.timestamp!="string"||typeof n.level!="string"||typeof n.message!="string")throw new _("VALIDATION",`Task log entry${e} must contain string timestamp, level, and message fields`);return {timestamp:n.timestamp,level:n.level,message:n.message}}function on(n,t){if(t===null||t.trim()==="")return [];let e;try{e=JSON.parse(t);}catch(r){throw new _("DB_ERROR",`Malformed legacy task logs: ${n}`,r)}if(!Array.isArray(e))throw new _("DB_ERROR",`Malformed legacy task logs: ${n} (expected an array)`);try{return e.map((r,i)=>dn(r,i))}catch(r){throw r instanceof _?new _("DB_ERROR",`Malformed legacy task logs: ${n}`,r):r}}function cn(n){if(n.log_storage!=="blob"&&n.log_storage!=="events")throw new _("DB_ERROR",`Invalid task log storage for task: ${n.id}`);if(!Number.isInteger(n.last_log_seq)||n.last_log_seq<0)throw new _("DB_ERROR",`Invalid task log sequence for task: ${n.id}`);if(!Number.isInteger(n.log_revision)||n.log_revision<0)throw new _("DB_ERROR",`Invalid task log revision for task: ${n.id}`);return n.log_storage}function an(n){return {taskId:n.id,source:cn(n),revision:n.log_revision,lastSeq:n.last_log_seq}}function qr(n){if(!Number.isInteger(n)||n<0)throw new _("VALIDATION","Task log tail limit must be a non-negative integer")}var Yt=class extends J{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let i=dirname(e);existsSync(i)||mkdirSync(i,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let r=A(e);if(t)try{gt(r.db,e);}catch(i){throw r.close(),i}return r}findStateRow(t,e){return t.db.select({id:s.id,log_storage:s.log_storage,last_log_seq:s.last_log_seq,log_revision:s.log_revision,logs:s.logs}).from(s).where(eq(s.id,e)).limit(1).get()}findStateRowInTransaction(t,e){return t.select({id:s.id,log_storage:s.log_storage,last_log_seq:s.last_log_seq,log_revision:s.log_revision,logs:s.logs}).from(s).where(eq(s.id,e)).limit(1).get()}requireStateRowInTransaction(t,e){let r=this.findStateRowInTransaction(t,e);if(!r)throw new _("NOT_FOUND",`Task not found: ${e}`);return r}appendLog(t,e){return this.appendLogs(t,[e])}appendLogs(t,e){let r=e.map((o,a)=>dn(o,a));if(r.length===0){let o=this.getLogState(t);if(!o)throw new _("NOT_FOUND",`Task not found: ${t}`);return o}let i=this.openHandle(true);try{return i.db.transaction(a=>{let d=this.requireStateRowInTransaction(a,t),c=cn(d);if(c==="blob"){let g=on(t,d.logs);if(a.update(s).set({logs:JSON.stringify([...g,...r]),log_revision:sql`${s.log_revision} + 1`}).where(eq(s.id,t)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:c,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let l=d.last_log_seq+1,u=d.last_log_seq+r.length;if(a.insert(Q).values(r.map((g,f)=>({task_id:t,seq:l+f,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(s).set({last_log_seq:u,log_revision:sql`${s.log_revision} + 1`}).where(eq(s.id,t)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:c,revision:d.log_revision+1,lastSeq:u}},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to append task log",o)}finally{i.close();}}getLogState(t){if(!this.dbExists())return;let e=this.openHandle(false);try{let r=this.findStateRow(e,t);return r?an(r):void 0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to read task log state",r)}finally{e.close();}}readLogs(t){return this.readLogsInternal(t)}readLogsTail(t,e){return qr(e),this.readLogsInternal(t,e)}readTail(t,e){return this.readLogsTail(t,e)}readLogsInternal(t,e){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(i=>{let o=this.findStateRowInTransaction(i,t);if(!o)return;let a=an(o);if(a.source==="blob"){let u=on(t,o.logs);return {...a,entries:e===void 0?u:u.slice(Math.max(0,u.length-e))}}let d=i.select({seq:Q.seq,timestamp:Q.timestamp,level:Q.level,message:Q.message}).from(Q).where(eq(Q.task_id,t)).orderBy(e===void 0?asc(Q.seq):desc(Q.seq)),l=(e===void 0?d.all():d.limit(e).all()).map(({timestamp:u,level:h,message:g})=>({timestamp:u,level:h,message:g}));return e!==void 0&&l.reverse(),{...a,entries:l}},{behavior:"deferred"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to read task logs",i)}finally{r.close();}}};var ke=40,ut="2026-05-09",Wr="0.8.9-rc.13",_t=10,pt=parseInt(Wr.split("rc.")[1]);function ln(){let n=sql`
18
18
  CASE
19
19
  WHEN ${s.model} LIKE 'claude-%' OR ${s.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
20
20
  WHEN ${s.model} LIKE 'gpt-%' OR ${s.model} LIKE 'codex-%' THEN 'codex'
@@ -43,7 +43,7 @@ ${r.join(`
43
43
  WHEN trim(${i}) = '' THEN 'unknown'
44
44
  ELSE ${i}
45
45
  END
46
- `}var Wr=new Set(["workflow","mcp"]),un=600*1e3,Qt=class extends J{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Yt({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let i=dirname(e);existsSync(i)||mkdirSync(i,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let r=b(e);if(t)try{gt(r.db,e);}catch(i){throw r.close(),i}return r}startTask(t){let e=this.openHandle(true);try{let r={id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,project_id:t.projectId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null,log_storage:"events"},i=o=>{e.db.insert(s).values(o).onConflictDoUpdate({target:s.id,set:{pid:sql`COALESCE(excluded.pid, ${s.pid})`},setWhere:eq(s.status,"running")}).run();};try{i(r);}catch(o){let a=o instanceof Error?o.message:typeof o=="object"&&o!==null&&"message"in o?String(o.message):String(o);if(!/log_storage/i.test(a)||!/no such column|no column named/i.test(a))throw o;e.runRaw(`INSERT INTO tasks (
46
+ `}var Kr=new Set(["workflow","mcp"]),un=600*1e3,Qt=class extends J{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Yt({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let i=dirname(e);existsSync(i)||mkdirSync(i,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let r=A(e);if(t)try{gt(r.db,e);}catch(i){throw r.close(),i}return r}startTask(t){let e=this.openHandle(true);try{let r={id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,project_id:t.projectId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null,log_storage:"events"},i=o=>{e.db.insert(s).values(o).onConflictDoUpdate({target:s.id,set:{pid:sql`COALESCE(excluded.pid, ${s.pid})`},setWhere:eq(s.status,"running")}).run();};try{i(r);}catch(o){let a=o instanceof Error?o.message:typeof o=="object"&&o!==null&&"message"in o?String(o.message):String(o);if(!/log_storage/i.test(a)||!/no such column|no column named/i.test(a))throw o;e.runRaw(`INSERT INTO tasks (
47
47
  id, agent_id, prompt, mode, status, started_at, pid,
48
48
  parent_task_id, caller_agent_id, trace_id, command, metadata,
49
49
  workspace_id, project_id, platform, crewx_version, thread_id,
@@ -53,7 +53,7 @@ ${r.join(`
53
53
  WHERE tasks.status = 'running'`,[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,r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command]);}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to start task",r)}finally{e.close();}}listTasksByProjectId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(s).where(eq(s.project_id,t)).orderBy(desc(s.started_at)).all()}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to list tasks by project",r)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let r=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
54
54
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
55
55
  model=COALESCE(?, model)
56
- WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,r]);}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to finish task",r)}finally{e.close();}}appendLog(t,e){this.taskLogRepository.appendLog(t,e);}appendLogs(t,e){this.taskLogRepository.appendLogs(t,e);}readLogs(t){return this.taskLogRepository.readLogs(t)}readLogsTail(t,e){return this.taskLogRepository.readLogsTail(t,e)}getLogState(t){return this.taskLogRepository.getLogState(t)}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).where(eq(s.status,"running")).orderBy(desc(s.started_at)).all()}catch(e){throw new _("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).orderBy(desc(s.started_at)).limit(100).all()}catch(e){throw new _("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(s).where(eq(s.id,t)).limit(1).get()??void 0}catch(r){throw new _("DB_ERROR","Failed to get task",r)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let r=e.db.select({id:s.id,status:s.status,pid:s.pid}).from(s).where(eq(s.id,t)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return e.db.update(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(s.id,t),eq(s.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to kill task",r)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(eq(s.status,"running")).all(),r=Date.now(),i=new Set,o=0;for(let a of e){if(a.pid){let l=!1;try{process.kill(a.pid,0),l=!0;}catch{}l||(t.db.update(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(s.id,a.id),eq(s.status,"running"))).run(),o++);continue}if(Wr.has(a.platform??"cli"))continue;let d=`${a.id}:${a.run_epoch??0}`;i.add(d);let c=this.pidNullObservedSince.get(d);if(c===void 0){this.pidNullObservedSince.set(d,r);continue}r-c>=un&&(t.db.update(s).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(s.id,a.id),eq(s.status,"running"))).run(),o++,this.pidNullObservedSince.delete(d));}for(let a of Array.from(this.pidNullObservedSince.keys()))i.has(a)||this.pidNullObservedSince.delete(a);return o}finally{t.close();}}reapRunningWorkflowTasks(t=un){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let r=new Date(Date.now()-t).toISOString();return e.db.update(s).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(s.status,"running"),eq(s.platform,"workflow"),isNull(s.pid),lt(s.started_at,r),or(isNull(s.metadata),and(notLike(s.metadata,'%"kind":"workflow_card"%'),notLike(s.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let o=b(i);try{let a=e?eq(s.workspace_id,e):void 0,d=a?and(eq(s.id,t),a):eq(s.id,t),c=o.db.select().from(s).where(d).limit(1).get()??void 0;if(!c){let l=a?and(eq(s.thread_id,t),a):eq(s.thread_id,t);c=o.db.select().from(s).where(l).orderBy(desc(s.started_at)).limit(1).get()??void 0;}if(c)return c}catch(a){throw new _("DB_ERROR","Failed to find task status",a)}finally{o.close();}}}findChildTasks(t,e){let r=this.resolveDbPaths(),i=new Set,o=[];for(let a of r){if(!existsSync(a))continue;let d=b(a);try{let c=e?and(eq(s.parent_task_id,t),eq(s.workspace_id,e)):eq(s.parent_task_id,t),l=d.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let u of l)i.has(u.id)||(i.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find child tasks",c)}finally{d.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
56
+ WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,r]);}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to finish task",r)}finally{e.close();}}appendLog(t,e){this.taskLogRepository.appendLog(t,e);}appendLogs(t,e){this.taskLogRepository.appendLogs(t,e);}readLogs(t){return this.taskLogRepository.readLogs(t)}readLogsTail(t,e){return this.taskLogRepository.readLogsTail(t,e)}getLogState(t){return this.taskLogRepository.getLogState(t)}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).where(eq(s.status,"running")).orderBy(desc(s.started_at)).all()}catch(e){throw new _("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).orderBy(desc(s.started_at)).limit(100).all()}catch(e){throw new _("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(s).where(eq(s.id,t)).limit(1).get()??void 0}catch(r){throw new _("DB_ERROR","Failed to get task",r)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let r=e.db.select({id:s.id,status:s.status,pid:s.pid}).from(s).where(eq(s.id,t)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return e.db.update(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(s.id,t),eq(s.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to kill task",r)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(eq(s.status,"running")).all(),r=Date.now(),i=new Set,o=0;for(let a of e){if(a.pid){let l=!1;try{process.kill(a.pid,0),l=!0;}catch{}l||(t.db.update(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(s.id,a.id),eq(s.status,"running"))).run(),o++);continue}if(Kr.has(a.platform??"cli"))continue;let d=`${a.id}:${a.run_epoch??0}`;i.add(d);let c=this.pidNullObservedSince.get(d);if(c===void 0){this.pidNullObservedSince.set(d,r);continue}r-c>=un&&(t.db.update(s).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(s.id,a.id),eq(s.status,"running"))).run(),o++,this.pidNullObservedSince.delete(d));}for(let a of Array.from(this.pidNullObservedSince.keys()))i.has(a)||this.pidNullObservedSince.delete(a);return o}finally{t.close();}}reapRunningWorkflowTasks(t=un){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let r=new Date(Date.now()-t).toISOString();return e.db.update(s).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(s.status,"running"),eq(s.platform,"workflow"),isNull(s.pid),lt(s.started_at,r),or(isNull(s.metadata),and(notLike(s.metadata,'%"kind":"workflow_card"%'),notLike(s.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let o=A(i);try{let a=e?eq(s.workspace_id,e):void 0,d=a?and(eq(s.id,t),a):eq(s.id,t),c=o.db.select().from(s).where(d).limit(1).get()??void 0;if(!c){let l=a?and(eq(s.thread_id,t),a):eq(s.thread_id,t);c=o.db.select().from(s).where(l).orderBy(desc(s.started_at)).limit(1).get()??void 0;}if(c)return c}catch(a){throw new _("DB_ERROR","Failed to find task status",a)}finally{o.close();}}}findChildTasks(t,e){let r=this.resolveDbPaths(),i=new Set,o=[];for(let a of r){if(!existsSync(a))continue;let d=A(a);try{let c=e?and(eq(s.parent_task_id,t),eq(s.workspace_id,e)):eq(s.parent_task_id,t),l=d.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let u of l)i.has(u.id)||(i.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find child tasks",c)}finally{d.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
57
57
  SELECT
58
58
  COALESCE(workspace_id, 'unknown') AS workspace_id,
59
59
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -74,7 +74,7 @@ ${r.join(`
74
74
  FROM tasks
75
75
  GROUP BY workspace_id
76
76
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
77
- `)}catch(r){throw new _("DB_ERROR","Failed to get workspace usage summary",r)}finally{e.close();}}getThreadTokenUsage(t,e){let r=this.resolveDbPaths(),i=new Set,o=0,a=0,d=0;for(let c of r){if(!existsSync(c))continue;let l=b(c);try{let u=eq(s.thread_id,t),h=e?and(u,eq(s.workspace_id,e)):u,g=l.db.select({id:s.id,input_tokens:s.input_tokens,output_tokens:s.output_tokens,cost_usd:s.cost_usd}).from(s).where(h).all();for(let f of g)i.has(f.id)||(i.add(f.id),o+=f.input_tokens??0,a+=f.output_tokens??0,d+=f.cost_usd??0);}catch(u){throw new _("DB_ERROR","Failed to get thread token usage",u)}finally{l.close();}}return {inputTokens:o,outputTokens:a,costUsd:d}}findTasksByThread(t,e,r){let i=this.resolveDbPaths(),o=new Set,a=[],d=r?.projection==="activity-log";for(let c of i){if(!existsSync(c))continue;let l=b(c);try{let u=eq(s.thread_id,t),h=e?and(u,eq(s.workspace_id,e)):u,g=d?l.db.select({id:s.id,thread_id:s.thread_id,agent_id:s.agent_id,parent_task_id:s.parent_task_id,started_at:s.started_at,completed_at:s.completed_at}).from(s).where(h).orderBy(asc(s.started_at)).all():l.db.select().from(s).where(h).orderBy(asc(s.started_at)).all();for(let f of g)o.has(f.id)||(o.add(f.id),a.push(f));}catch(u){throw new _("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return a}parseWorkflowCardMetadata(t){if(!t)return {};try{let e=JSON.parse(t);return {kind:typeof e.kind=="string"?e.kind:void 0,workflowRunId:typeof e.workflowRunId=="string"?e.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let e of this.resolveDbPaths()){if(!existsSync(e))continue;let r=b(e);try{t.push(...r.db.select({id:s.id,agent_id:s.agent_id,thread_id:s.thread_id,workspace_id:s.workspace_id,platform:s.platform,status:s.status,error:s.error,completed_at:s.completed_at,duration_ms:s.duration_ms,started_at:s.started_at,metadata:s.metadata}).from(s).where(and(eq(s.platform,"workflow"),or(like(s.metadata,'%"kind":"workflow_card"%'),like(s.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(s.started_at)).all());}catch(i){throw new _("DB_ERROR","Failed to find workflow parent tasks",i)}finally{r.close();}}return t}batchFetchWorkflowCards(t,e){let r=new Map;if(t.length===0)return r;let i=new Set(t),o=new Map,a=e?eq(s.workspace_id,e):void 0,d=(c,l)=>{if(!c)return;let u=o.get(c);if(u&&l.started_at<=u)return;let h=this.parseWorkflowCardMetadata(l.metadata);h.kind!=="workflow_card"&&h.kind!=="workflow_ui_instance"||(o.set(c,l.started_at),r.set(c,{taskId:l.id,workflowRunId:h.workflowRunId,raw:l.result??void 0}));};for(let c of this.resolveDbPaths()){if(!existsSync(c))continue;let l=b(c);try{let u=and(inArray(s.thread_id,t),or(like(s.metadata,'%"kind":"workflow_card"%'),like(s.metadata,'%"kind":"workflow_ui_instance"%'))),h=l.db.select({id:s.id,thread_id:s.thread_id,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(a?and(u,a):u).all();for(let A of h)d(A.thread_id,A);let g=and(isNull(s.thread_id),or(like(s.metadata,'%"kind":"workflow_card"%'),like(s.metadata,'%"kind":"workflow_ui_instance"%'))),f=l.db.select({id:s.id,command:s.command,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(a?and(g,a):g).all();for(let A of f){let N=this.extractThreadIdFromCommand(A.command);!N||!i.has(N)||d(N,A);}}catch(u){throw new _("DB_ERROR","Failed to batch fetch workflow cards",u)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let r=[];t.workspaceId&&r.push(eq(s.workspace_id,t.workspaceId));let i=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;i&&r.push(inArray(s.agent_id,i));let o=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;o&&r.push(inArray(s.status,o));let a=t.q??t.search;a&&r.push(like(s.prompt,`%${a}%`)),t.from&&r.push(gte(s.started_at,t.from)),t.to&&r.push(lt(s.started_at,t.to));let d=r.length>0?and(...r):void 0,c=e.db.select({count:sql`count(*)`}).from(s).where(d).get(),l=(t.sortDir??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at);return {rows:e.db.select().from(s).where(d).orderBy(l).limit(t.limit).offset(t.offset).all(),total:c?.count??0}}catch(r){throw new _("DB_ERROR","Failed to find all tasks",r)}finally{e.close();}}getAgentUsage(t,e,r){if(!this.dbExists())return [];let i=this.openHandle(false);try{return i.db.all(r?sql`
77
+ `)}catch(r){throw new _("DB_ERROR","Failed to get workspace usage summary",r)}finally{e.close();}}getThreadTokenUsage(t,e){let r=this.resolveDbPaths(),i=new Set,o=0,a=0,d=0;for(let c of r){if(!existsSync(c))continue;let l=A(c);try{let u=eq(s.thread_id,t),h=e?and(u,eq(s.workspace_id,e)):u,g=l.db.select({id:s.id,input_tokens:s.input_tokens,output_tokens:s.output_tokens,cost_usd:s.cost_usd}).from(s).where(h).all();for(let f of g)i.has(f.id)||(i.add(f.id),o+=f.input_tokens??0,a+=f.output_tokens??0,d+=f.cost_usd??0);}catch(u){throw new _("DB_ERROR","Failed to get thread token usage",u)}finally{l.close();}}return {inputTokens:o,outputTokens:a,costUsd:d}}findTasksByThread(t,e,r){let i=this.resolveDbPaths(),o=new Set,a=[],d=r?.projection==="activity-log";for(let c of i){if(!existsSync(c))continue;let l=A(c);try{let u=eq(s.thread_id,t),h=e?and(u,eq(s.workspace_id,e)):u,g=d?l.db.select({id:s.id,thread_id:s.thread_id,agent_id:s.agent_id,parent_task_id:s.parent_task_id,started_at:s.started_at,completed_at:s.completed_at}).from(s).where(h).orderBy(asc(s.started_at)).all():l.db.select().from(s).where(h).orderBy(asc(s.started_at)).all();for(let f of g)o.has(f.id)||(o.add(f.id),a.push(f));}catch(u){throw new _("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return a}parseWorkflowCardMetadata(t){if(!t)return {};try{let e=JSON.parse(t);return {kind:typeof e.kind=="string"?e.kind:void 0,workflowRunId:typeof e.workflowRunId=="string"?e.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let e of this.resolveDbPaths()){if(!existsSync(e))continue;let r=A(e);try{t.push(...r.db.select({id:s.id,agent_id:s.agent_id,thread_id:s.thread_id,workspace_id:s.workspace_id,platform:s.platform,status:s.status,error:s.error,completed_at:s.completed_at,duration_ms:s.duration_ms,started_at:s.started_at,metadata:s.metadata}).from(s).where(and(eq(s.platform,"workflow"),or(like(s.metadata,'%"kind":"workflow_card"%'),like(s.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(s.started_at)).all());}catch(i){throw new _("DB_ERROR","Failed to find workflow parent tasks",i)}finally{r.close();}}return t}batchFetchWorkflowCards(t,e){let r=new Map;if(t.length===0)return r;let i=new Set(t),o=new Map,a=e?eq(s.workspace_id,e):void 0,d=(c,l)=>{if(!c)return;let u=o.get(c);if(u&&l.started_at<=u)return;let h=this.parseWorkflowCardMetadata(l.metadata);h.kind!=="workflow_card"&&h.kind!=="workflow_ui_instance"||(o.set(c,l.started_at),r.set(c,{taskId:l.id,workflowRunId:h.workflowRunId,raw:l.result??void 0}));};for(let c of this.resolveDbPaths()){if(!existsSync(c))continue;let l=A(c);try{let u=and(inArray(s.thread_id,t),or(like(s.metadata,'%"kind":"workflow_card"%'),like(s.metadata,'%"kind":"workflow_ui_instance"%'))),h=l.db.select({id:s.id,thread_id:s.thread_id,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(a?and(u,a):u).all();for(let b of h)d(b.thread_id,b);let g=and(isNull(s.thread_id),or(like(s.metadata,'%"kind":"workflow_card"%'),like(s.metadata,'%"kind":"workflow_ui_instance"%'))),f=l.db.select({id:s.id,command:s.command,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(a?and(g,a):g).all();for(let b of f){let N=this.extractThreadIdFromCommand(b.command);!N||!i.has(N)||d(N,b);}}catch(u){throw new _("DB_ERROR","Failed to batch fetch workflow cards",u)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let r=[];t.workspaceId&&r.push(eq(s.workspace_id,t.workspaceId));let i=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;i&&r.push(inArray(s.agent_id,i));let o=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;o&&r.push(inArray(s.status,o));let a=t.q??t.search;a&&r.push(like(s.prompt,`%${a}%`)),t.from&&r.push(gte(s.started_at,t.from)),t.to&&r.push(lt(s.started_at,t.to));let d=r.length>0?and(...r):void 0,c=e.db.select({count:sql`count(*)`}).from(s).where(d).get(),l=(t.sortDir??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at);return {rows:e.db.select().from(s).where(d).orderBy(l).limit(t.limit).offset(t.offset).all(),total:c?.count??0}}catch(r){throw new _("DB_ERROR","Failed to find all tasks",r)}finally{e.close();}}getAgentUsage(t,e,r){if(!this.dbExists())return [];let i=this.openHandle(false);try{return i.db.all(r?sql`
78
78
  SELECT
79
79
  t.agent_id,
80
80
  t.workspace_id,
@@ -212,7 +212,7 @@ ${r.join(`
212
212
  AND t.started_at < ${e}
213
213
  GROUP BY date(t.started_at), t.agent_id
214
214
  ORDER BY date(t.started_at) ASC
215
- `).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(o){throw new _("DB_ERROR","Failed to get agent usage trend",o)}finally{i.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(s).where(and(eq(s.id,t),eq(s.workspace_id,e))).limit(1).get()??void 0}catch(i){throw new _("DB_ERROR","Failed to find task for stop",i)}finally{r.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let e=this.openHandle(false);try{return e.db.select({id:s.id,thread_id:s.thread_id,status:s.status,result:s.result,error:s.error,started_at:s.started_at,completed_at:s.completed_at,metadata:s.metadata}).from(s).where(and(eq(s.agent_id,t.agentId),eq(s.workspace_id,t.workspaceId),sql`${s.metadata} IS NOT NULL AND json_valid(${s.metadata}) AND json_extract(${s.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(s.started_at)).limit(1).get()??null}catch(r){throw new _("DB_ERROR","Failed to find latest task by metadata",r)}finally{e.close();}}markTaskFailed(t,e,r){if(!this.dbExists())return;let i=this.openHandle(true);try{let o=new Date().toISOString(),a=r?and(eq(s.id,t),eq(s.status,"running"),eq(s.workspace_id,r)):and(eq(s.id,t),eq(s.status,"running"));i.db.update(s).set({status:"failed",error:e,completed_at:o}).where(a).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to mark task failed",o)}finally{i.close();}}findTasksByPromptHint(t,e){let r=this.resolveDbPaths(),i=new Set,o=[];for(let a of r){if(!existsSync(a))continue;let d=b(a);try{let c=e?and(like(s.prompt,`%${t}%`),eq(s.workspace_id,e)):like(s.prompt,`%${t}%`),l=d.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let u of l)i.has(u.id)||(i.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{d.close();}}return o}getProviderUsage(t,e,r){if(!this.dbExists())return [];let i=this.openHandle(false);try{let o=ln(),a=sql`
215
+ `).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(o){throw new _("DB_ERROR","Failed to get agent usage trend",o)}finally{i.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(s).where(and(eq(s.id,t),eq(s.workspace_id,e))).limit(1).get()??void 0}catch(i){throw new _("DB_ERROR","Failed to find task for stop",i)}finally{r.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let e=this.openHandle(false);try{return e.db.select({id:s.id,thread_id:s.thread_id,status:s.status,result:s.result,error:s.error,started_at:s.started_at,completed_at:s.completed_at,metadata:s.metadata}).from(s).where(and(eq(s.agent_id,t.agentId),eq(s.workspace_id,t.workspaceId),sql`${s.metadata} IS NOT NULL AND json_valid(${s.metadata}) AND json_extract(${s.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(s.started_at)).limit(1).get()??null}catch(r){throw new _("DB_ERROR","Failed to find latest task by metadata",r)}finally{e.close();}}markTaskFailed(t,e,r){if(!this.dbExists())return;let i=this.openHandle(true);try{let o=new Date().toISOString(),a=r?and(eq(s.id,t),eq(s.status,"running"),eq(s.workspace_id,r)):and(eq(s.id,t),eq(s.status,"running"));i.db.update(s).set({status:"failed",error:e,completed_at:o}).where(a).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to mark task failed",o)}finally{i.close();}}findTasksByPromptHint(t,e){let r=this.resolveDbPaths(),i=new Set,o=[];for(let a of r){if(!existsSync(a))continue;let d=A(a);try{let c=e?and(like(s.prompt,`%${t}%`),eq(s.workspace_id,e)):like(s.prompt,`%${t}%`),l=d.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let u of l)i.has(u.id)||(i.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{d.close();}}return o}getProviderUsage(t,e,r){if(!this.dbExists())return [];let i=this.openHandle(false);try{let o=ln(),a=sql`
216
216
  COALESCE(${s.input_tokens}, 0)
217
217
  + CASE
218
218
  WHEN ${s.started_at} >= ${ut}
@@ -299,11 +299,11 @@ ${r.join(`
299
299
  GROUP BY ${s.caller_agent_id}, ${s.agent_id}
300
300
  ORDER BY task_count DESC, ${s.caller_agent_id} ASC, ${s.agent_id} ASC
301
301
  LIMIT ${ke+1}
302
- `),c=d.length>ke;return {edges:d.slice(0,ke).map(u=>({callerAgentId:u.caller_agent_id??null,agentId:u.agent_id,taskCount:u.task_count,totalTokens:u.input_tokens+u.output_tokens,outputTokens:u.output_tokens})),truncated:c}}catch(o){throw new _("DB_ERROR","Failed to get delegation matrix",o)}finally{i.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=[];t.workspaceId&&r.push(eq(s.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&r.push(inArray(s.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&r.push(inArray(s.status,t.statuses)),t.from&&r.push(gte(s.started_at,t.from)),t.to&&r.push(lt(s.started_at,t.to));let i=r.length>0?and(...r):void 0,o=(t.order??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at),a={id:s.id,agent_id:s.agent_id,status:s.status,prompt:s.prompt,started_at:s.started_at,completed_at:s.completed_at,thread_id:s.thread_id};return t.limit?e.db.select(a).from(s).where(i).orderBy(o).limit(t.limit).all():e.db.select(a).from(s).where(i).orderBy(o).all()}catch(r){throw new _("DB_ERROR","Failed to find task evidence",r)}finally{e.close();}}findThreadChains(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=t.maxThreads??8,i=t.maxTurnsPerThread??4,o=[isNotNull(s.thread_id),isNull(s.parent_task_id),isNull(s.caller_agent_id),or(isNull(s.platform),ne$1(s.platform,"workflow")),or(isNull(s.metadata),and(notLike(s.metadata,'%"kind":"workflow_card"%'),notLike(s.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(s.metadata),notLike(s.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&o.push(eq(s.workspace_id,t.workspaceId)),t.from&&o.push(gte(s.started_at,t.from)),t.to&&o.push(lt(s.started_at,t.to));let a=e.db.select({id:s.id,agent_id:s.agent_id,status:s.status,prompt:s.prompt,started_at:s.started_at,completed_at:s.completed_at,thread_id:s.thread_id}).from(s).where(and(...o)).orderBy(asc(s.started_at),asc(s.id)).all(),d=new Map;for(let l of a){if(!l.thread_id)continue;let u={id:l.id,agentId:l.agent_id,status:l.status,prompt:l.prompt,startedAt:l.started_at,completedAt:l.completed_at},h=d.get(l.thread_id);h?h.push(u):d.set(l.thread_id,[u]);}let c=[];for(let[l,u]of d){let h=u.filter(g=>g.agentId===t.targetAgentId).length;h<2||c.push({threadId:l,targetAgentTurnCount:h,turns:u});}return c.sort((l,u)=>{let h=l.turns[l.turns.length-1].startedAt,g=u.turns[u.turns.length-1].startedAt;return h<g?1:h>g?-1:0}),c.slice(0,r).map(l=>({threadId:l.threadId,targetAgentTurnCount:l.targetAgentTurnCount,turns:l.turns.slice(-i)}))}catch(r){throw new _("DB_ERROR","Failed to find thread chains",r)}finally{e.close();}}};var we=class extends ht{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new Qt({dbPath:this.dbPath}),r=process.cwd(),o=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))?$e(r):null,a=process.argv.join(" ");this.unsubs.push(t.on("task:start",d=>{try{let c=d.callerAgentId??null,l=d.parentTaskId??null,u=d.rootTraceId??d.traceId,h=d.metadata?JSON.stringify(d.metadata):JSON.stringify({provider:d.provider??"cli/claude"});e.startTask({id:d.traceId,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:d.pid??null,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:a,codingAgentCommand:d.codingAgentCommand??null,workspaceId:d.workspaceId??o,projectId:d.projectId??null,callerAgentId:c,parentTaskId:l,traceId:u,metadata:h,threadId:d.threadId??null});}catch{}}),t.on("task:output",d=>{try{e.appendLog(d.traceId,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch{}}),t.on("task:end",d=>{try{let c=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null,l=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{}}):null;e.finishTask({id:d.traceId,status:d.error?"failed":"success",result:d.result??null,error:l,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch:c});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var It=class extends _{reason;constructor(t,e=t){super("VALIDATION",e),this.name="ThreadTitleMetadataPatchError",this.reason=t;}};function Ht(n){if(!n)return {};try{let t=JSON.parse(n);return !t||typeof t!="object"||Array.isArray(t)?{}:t}catch{return {}}}function Jr(n){let e=Ht(n).threadTitle;if(!e||typeof e!="object"||Array.isArray(e))return {priority:null,state:null};let r=e;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}var Zt=class extends J{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let i=dirname(e);existsSync(i)||mkdirSync(i,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let r=b(e);if(t)try{gt(r.db,e);}catch(i){throw r.close(),i}return r}validateWorkspaceId(t,e){return t.db.select({id:Rt.id}).from(Rt).where(eq(Rt.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
302
+ `),c=d.length>ke;return {edges:d.slice(0,ke).map(u=>({callerAgentId:u.caller_agent_id??null,agentId:u.agent_id,taskCount:u.task_count,totalTokens:u.input_tokens+u.output_tokens,outputTokens:u.output_tokens})),truncated:c}}catch(o){throw new _("DB_ERROR","Failed to get delegation matrix",o)}finally{i.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=[];t.workspaceId&&r.push(eq(s.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&r.push(inArray(s.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&r.push(inArray(s.status,t.statuses)),t.from&&r.push(gte(s.started_at,t.from)),t.to&&r.push(lt(s.started_at,t.to));let i=r.length>0?and(...r):void 0,o=(t.order??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at),a={id:s.id,agent_id:s.agent_id,status:s.status,prompt:s.prompt,started_at:s.started_at,completed_at:s.completed_at,thread_id:s.thread_id};return t.limit?e.db.select(a).from(s).where(i).orderBy(o).limit(t.limit).all():e.db.select(a).from(s).where(i).orderBy(o).all()}catch(r){throw new _("DB_ERROR","Failed to find task evidence",r)}finally{e.close();}}findThreadChains(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=t.maxThreads??8,i=t.maxTurnsPerThread??4,o=[isNotNull(s.thread_id),isNull(s.parent_task_id),isNull(s.caller_agent_id),or(isNull(s.platform),ne$1(s.platform,"workflow")),or(isNull(s.metadata),and(notLike(s.metadata,'%"kind":"workflow_card"%'),notLike(s.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(s.metadata),notLike(s.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&o.push(eq(s.workspace_id,t.workspaceId)),t.from&&o.push(gte(s.started_at,t.from)),t.to&&o.push(lt(s.started_at,t.to));let a=e.db.select({id:s.id,agent_id:s.agent_id,status:s.status,prompt:s.prompt,started_at:s.started_at,completed_at:s.completed_at,thread_id:s.thread_id}).from(s).where(and(...o)).orderBy(asc(s.started_at),asc(s.id)).all(),d=new Map;for(let l of a){if(!l.thread_id)continue;let u={id:l.id,agentId:l.agent_id,status:l.status,prompt:l.prompt,startedAt:l.started_at,completedAt:l.completed_at},h=d.get(l.thread_id);h?h.push(u):d.set(l.thread_id,[u]);}let c=[];for(let[l,u]of d){let h=u.filter(g=>g.agentId===t.targetAgentId).length;h<2||c.push({threadId:l,targetAgentTurnCount:h,turns:u});}return c.sort((l,u)=>{let h=l.turns[l.turns.length-1].startedAt,g=u.turns[u.turns.length-1].startedAt;return h<g?1:h>g?-1:0}),c.slice(0,r).map(l=>({threadId:l.threadId,targetAgentTurnCount:l.targetAgentTurnCount,turns:l.turns.slice(-i)}))}catch(r){throw new _("DB_ERROR","Failed to find thread chains",r)}finally{e.close();}}};var Xr=200,Vr=200;function Yr(n){if(typeof n!="object"||n===null||!("code"in n))return;let t=n.code;return typeof t=="string"&&t.length>0?t:void 0}function Jr(n){let t=n instanceof _?n.code:void 0,e=n instanceof _?n.cause:n,r=Yr(e);return {code:t??r??"DB_ERROR",cause:r??(e instanceof Error?e.name:t??typeof e)}}function pn(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}var we=class extends ht{name="sqlite-tracing";unsubs=[];dbPath;version;taskRepo;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new Qt({dbPath:this.dbPath});this.taskRepo=e;let r=process.cwd(),o=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))?Le(r):null,a=process.argv.join(" ");this.unsubs.push(t.on("task:start",d=>{try{let c=d.callerAgentId??null,l=d.parentTaskId??null,u=d.rootTraceId??d.traceId,h=d.metadata?JSON.stringify(d.metadata):JSON.stringify({provider:d.provider??"cli/claude"});e.startTask({id:d.traceId,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:d.pid??null,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:a,codingAgentCommand:d.codingAgentCommand??null,workspaceId:d.workspaceId??o,projectId:d.projectId??null,callerAgentId:c,parentTaskId:l,traceId:u,metadata:h,threadId:d.threadId??null});}catch{}}),t.on("task:output",d=>{try{this.enqueueLog(d.traceId,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(c){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(c,[l],pn(l));}}),t.on("task:end",d=>{try{this.flushTaskLogs(d.traceId);let c=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null,l=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{}}):null;e.finishTask({id:d.traceId,status:d.error?"failed":"success",result:d.result??null,error:l,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch:c});}catch{}}));}detach(t){try{this.flushAllTaskLogs();}finally{this.clearAllTimers(),this.unsubs.forEach(e=>e()),this.unsubs=[],this.queues.clear(),this.taskRepo=void 0;}}getMetrics(){let t=0,e=0;for(let r of this.queues.values())t+=r.entries.length,e+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:t,pendingQueueBytes:e}}enqueueLog(t,e){let r=this.queues.get(t);if(r||(r={entries:[],bytes:0},this.queues.set(t,r)),r.entries.push(e),r.bytes+=pn(e),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=Xr){this.flushTaskLogs(t);return}if(!r.timer){let i=setTimeout(()=>{let o=this.queues.get(t);!o||o.timer!==i||(o.timer=void 0,this.flushTaskLogs(t));},Vr);r.timer=i;}}flushTaskLogs(t){let e=this.queues.get(t);if(!e||e.entries.length===0){e?.timer&&clearTimeout(e.timer),this.queues.delete(t);return}e.timer&&(clearTimeout(e.timer),e.timer=void 0);let r=e.entries,i=e.bytes;e.entries=[],e.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(t,r),this.metrics.flushedEntries+=r.length;}catch(a){this.recordAppendFailure(a,r,i);}let o=this.queues.get(t);o&&o.entries.length===0&&(o.timer&&clearTimeout(o.timer),this.queues.delete(t));}flushAllTaskLogs(){for(let t of [...this.queues.keys()])this.flushTaskLogs(t);}clearAllTimers(){for(let t of this.queues.values())t.timer&&(clearTimeout(t.timer),t.timer=void 0);}recordAppendFailure(t,e,r){let i=Jr(t);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=e.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[i.code]=(this.metrics.appendFailureByCode[i.code]??0)+1,this.metrics.appendFailureByCause[i.cause]=(this.metrics.appendFailureByCause[i.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:i.code,cause:i.cause,pendingEntries:e.length,pendingBytes:r});}};var It=class extends _{reason;constructor(t,e=t){super("VALIDATION",e),this.name="ThreadTitleMetadataPatchError",this.reason=t;}};function Ht(n){if(!n)return {};try{let t=JSON.parse(n);return !t||typeof t!="object"||Array.isArray(t)?{}:t}catch{return {}}}function ns(n){let e=Ht(n).threadTitle;if(!e||typeof e!="object"||Array.isArray(e))return {priority:null,state:null};let r=e;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}var Zt=class extends J{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let i=dirname(e);existsSync(i)||mkdirSync(i,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let r=A(e);if(t)try{gt(r.db,e);}catch(i){throw r.close(),i}return r}validateWorkspaceId(t,e){return t.db.select({id:Rt.id}).from(Rt).where(eq(Rt.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
303
303
  SELECT 1 FROM tasks parent
304
304
  WHERE parent.id = ${t}.parent_task_id
305
305
  AND parent.thread_id = ${t}.thread_id
306
- )`)}findAllThreads(t){let e=this.resolveDbPaths(),r=new Set,i=[];for(let o of e){if(!existsSync(o))continue;let a=b(o);try{let d=t?eq(p.workspace_id,t):void 0,c=a.db.select().from(p).where(d).orderBy(desc(p.updated_at)).all();for(let l of c)r.has(l.id)||(r.add(l.id),i.push(l));}catch(d){throw new _("DB_ERROR","Failed to find all threads",d)}finally{a.close();}}return i}findThreadsByIdsOrTitles(t,e){if(t.length===0)return [];let r=this.resolveDbPaths(),i=new Set,o=[];for(let a of r){if(!existsSync(a))continue;let d=b(a);try{let c=or(inArray(p.id,t),inArray(p.title,t)),l=e?and(c,eq(p.workspace_id,e)):c,u=d.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let h of u)i.has(h.id)||(i.add(h.id),o.push(h));}catch(c){throw new _("DB_ERROR","Failed to find threads by ids or titles",c)}finally{d.close();}}return o}findThreadById(t,e){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let o=b(i);try{let a=eq(p.id,t),d=e?and(a,eq(p.workspace_id,e)):a,c=o.db.select().from(p).where(d).limit(1).get()??void 0;if(c)return c}catch(a){throw new _("DB_ERROR","Failed to find thread by id",a)}finally{o.close();}}}threadExists(t,e){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let o=b(i);try{let a=eq(p.id,t),d=e?and(a,eq(p.workspace_id,e)):a;if(o.db.select({id:p.id}).from(p).where(d).limit(1).get())return !0}catch(a){throw new _("DB_ERROR","Failed to check thread existence",a)}finally{o.close();}}return false}aggregateTaskStats(t,e){let r=this.resolveDbPaths(),i=0,o=0,a=0,d=0,c=0,l=new Set;for(let u of r){if(!existsSync(u))continue;let h=b(u);try{let g=h.db.get(sql`
306
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),r=new Set,i=[];for(let o of e){if(!existsSync(o))continue;let a=A(o);try{let d=t?eq(p.workspace_id,t):void 0,c=a.db.select().from(p).where(d).orderBy(desc(p.updated_at)).all();for(let l of c)r.has(l.id)||(r.add(l.id),i.push(l));}catch(d){throw new _("DB_ERROR","Failed to find all threads",d)}finally{a.close();}}return i}findThreadsByIdsOrTitles(t,e){if(t.length===0)return [];let r=this.resolveDbPaths(),i=new Set,o=[];for(let a of r){if(!existsSync(a))continue;let d=A(a);try{let c=or(inArray(p.id,t),inArray(p.title,t)),l=e?and(c,eq(p.workspace_id,e)):c,u=d.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let h of u)i.has(h.id)||(i.add(h.id),o.push(h));}catch(c){throw new _("DB_ERROR","Failed to find threads by ids or titles",c)}finally{d.close();}}return o}findThreadById(t,e){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let o=A(i);try{let a=eq(p.id,t),d=e?and(a,eq(p.workspace_id,e)):a,c=o.db.select().from(p).where(d).limit(1).get()??void 0;if(c)return c}catch(a){throw new _("DB_ERROR","Failed to find thread by id",a)}finally{o.close();}}}threadExists(t,e){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let o=A(i);try{let a=eq(p.id,t),d=e?and(a,eq(p.workspace_id,e)):a;if(o.db.select({id:p.id}).from(p).where(d).limit(1).get())return !0}catch(a){throw new _("DB_ERROR","Failed to check thread existence",a)}finally{o.close();}}return false}aggregateTaskStats(t,e){let r=this.resolveDbPaths(),i=0,o=0,a=0,d=0,c=0,l=new Set;for(let u of r){if(!existsSync(u))continue;let h=A(u);try{let g=h.db.get(sql`
307
307
  SELECT
308
308
  count(*) AS cnt,
309
309
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -320,7 +320,7 @@ ${r.join(`
320
320
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
321
321
  AND ${this.topLevelTaskPredicateSql()}
322
322
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
323
- `);for(let A of f)l.add(A.agent_id);}catch(g){throw new _("DB_ERROR","Failed to aggregate task stats",g)}finally{h.close();}}return {taskCount:i,inputTokens:o,outputTokens:a,cachedInputTokens:d,costUsd:c,agentIds:Array.from(l)}}findTopLevelTasks(t,e,r){let i=this.resolveDbPaths(),o=new Set,a=[];for(let d of i){if(!existsSync(d))continue;let c=b(d);try{let l;r!==void 0?l=c.db.all(sql`
323
+ `);for(let b of f)l.add(b.agent_id);}catch(g){throw new _("DB_ERROR","Failed to aggregate task stats",g)}finally{h.close();}}return {taskCount:i,inputTokens:o,outputTokens:a,cachedInputTokens:d,costUsd:c,agentIds:Array.from(l)}}findTopLevelTasks(t,e,r){let i=this.resolveDbPaths(),o=new Set,a=[];for(let d of i){if(!existsSync(d))continue;let c=A(d);try{let l;r!==void 0?l=c.db.all(sql`
324
324
  SELECT * FROM (
325
325
  SELECT child.*,
326
326
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -337,7 +337,7 @@ ${r.join(`
337
337
  AND ${this.topLevelTaskPredicateSql()}
338
338
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
339
339
  ORDER BY child.started_at ASC
340
- `);for(let u of l)o.has(u.id)||(o.add(u.id),a.push(u));}catch(l){throw new _("DB_ERROR","Failed to find top-level tasks",l)}finally{c.close();}}if(r!==void 0&&i.length>1){let d=new Map;for(let c of a){let l=c.agent_id??"";d.has(l)||d.set(l,[]),d.get(l).push(c);}a=[];for(let c of d.values())c.sort((l,u)=>(u.started_at??"").localeCompare(l.started_at??"")),a.push(...c.slice(0,r));a.sort((c,l)=>(c.started_at??"").localeCompare(l.started_at??""));}return a}findAllTasks(t,e){let r=this.resolveDbPaths(),i=new Set,o=[];for(let a of r){if(!existsSync(a))continue;let d=b(a);try{let c=eq(s.thread_id,t),l=e?and(c,eq(s.workspace_id,e)):c,u=d.db.select().from(s).where(l).orderBy(asc(s.started_at)).all();for(let h of u)i.has(h.id)||(i.add(h.id),o.push(h));}catch(c){throw new _("DB_ERROR","Failed to find all tasks for thread",c)}finally{d.close();}}return o}findTaskById(t,e,r){let i=this.resolveDbPaths();for(let o of i){if(!existsSync(o))continue;let a=b(o);try{let d=and(eq(s.id,e),eq(s.thread_id,t)),c=r?and(d,eq(s.workspace_id,r)):d,l=a.db.select().from(s).where(c).limit(1).get();if(!l)continue;let u=a.db.select().from(s).where(eq(s.parent_task_id,l.id)).orderBy(asc(s.started_at)).all();return {task:l,children:u}}catch(d){throw new _("DB_ERROR","Failed to find task by id",d)}finally{a.close();}}}batchFetchTasksQuery(t,e){return sql`
340
+ `);for(let u of l)o.has(u.id)||(o.add(u.id),a.push(u));}catch(l){throw new _("DB_ERROR","Failed to find top-level tasks",l)}finally{c.close();}}if(r!==void 0&&i.length>1){let d=new Map;for(let c of a){let l=c.agent_id??"";d.has(l)||d.set(l,[]),d.get(l).push(c);}a=[];for(let c of d.values())c.sort((l,u)=>(u.started_at??"").localeCompare(l.started_at??"")),a.push(...c.slice(0,r));a.sort((c,l)=>(c.started_at??"").localeCompare(l.started_at??""));}return a}findAllTasks(t,e){let r=this.resolveDbPaths(),i=new Set,o=[];for(let a of r){if(!existsSync(a))continue;let d=A(a);try{let c=eq(s.thread_id,t),l=e?and(c,eq(s.workspace_id,e)):c,u=d.db.select().from(s).where(l).orderBy(asc(s.started_at)).all();for(let h of u)i.has(h.id)||(i.add(h.id),o.push(h));}catch(c){throw new _("DB_ERROR","Failed to find all tasks for thread",c)}finally{d.close();}}return o}findTaskById(t,e,r){let i=this.resolveDbPaths();for(let o of i){if(!existsSync(o))continue;let a=A(o);try{let d=and(eq(s.id,e),eq(s.thread_id,t)),c=r?and(d,eq(s.workspace_id,r)):d,l=a.db.select().from(s).where(c).limit(1).get();if(!l)continue;let u=a.db.select().from(s).where(eq(s.parent_task_id,l.id)).orderBy(asc(s.started_at)).all();return {task:l,children:u}}catch(d){throw new _("DB_ERROR","Failed to find task by id",d)}finally{a.close();}}}batchFetchTasksQuery(t,e){return sql`
341
341
  SELECT child.id, child.thread_id, child.agent_id, child.status,
342
342
  child.parent_task_id, child.started_at, child.completed_at,
343
343
  child.duration_ms, child.input_tokens, child.output_tokens,
@@ -347,7 +347,7 @@ ${r.join(`
347
347
  AND ${this.topLevelTaskPredicateSql()}
348
348
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
349
349
  ORDER BY child.started_at ASC
350
- `}batchFetchTasks(t,e){let r=new Map;if(t.length===0)return r;let i=this.resolveDbPaths();for(let o of i){if(!existsSync(o))continue;let a=b(o);try{let d=a.db.all(this.batchFetchTasksQuery(t,e));for(let c of d){let l=c.thread_id;r.has(l)||r.set(l,[]),r.get(l).push(c);}}catch(d){throw new _("DB_ERROR","Failed to batch fetch tasks",d)}finally{a.close();}}return r}explainBatchFetchTasksPlan(t,e){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let o=b(i);try{return o.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,e)}`).map(d=>d.detail)}finally{o.close();}}return []}updateThreadTitle(t,e,r){if(!this.dbExists())return;let i=this.openHandle(true);try{let o=eq(p.id,t),a=r?and(o,eq(p.workspace_id,r)):o;if(!i.db.select({id:p.id}).from(p).where(a).limit(1).get())return;i.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to update thread title",o)}finally{i.close();}}upsertThread(t,e){let r=this.openHandle(true);try{let i=e.workspaceId?this.validateWorkspaceId(r,e.workspaceId):null,o=new Date().toISOString();if(r.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let d={updated_at:o};e.title!==void 0&&(d.title=e.title),e.titleLocked!==void 0&&(d.title_locked=e.titleLocked?1:0),r.db.update(p).set(d).where(eq(p.id,t)).run();}else r.db.insert(p).values({id:t,platform:e.platform,workspace_id:i,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:o,updated_at:o}).run();}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to upsert thread",i)}finally{r.close();}}ensureThread(t,e,r){let i=this.openHandle(true);try{let o=r?this.validateWorkspaceId(i,r):null,a=i.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get();if(a){o&&!a.workspace_id&&i.db.update(p).set({workspace_id:o}).where(eq(p.id,t)).run();return}let d=new Date().toISOString();i.db.insert(p).values({id:t,platform:e,workspace_id:o,message_count:0,created_at:d,updated_at:d}).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to ensure thread",o)}finally{i.close();}}saveUserMessage(t,e,r){if(!this.dbExists())return {firstMessage:false};let i=this.openHandle(true);try{let o=new Date().toISOString();return {firstMessage:i.db.transaction(d=>{let l=d.select({message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()?.message_count===0;return d.run(sql`
350
+ `}batchFetchTasks(t,e){let r=new Map;if(t.length===0)return r;let i=this.resolveDbPaths();for(let o of i){if(!existsSync(o))continue;let a=A(o);try{let d=a.db.all(this.batchFetchTasksQuery(t,e));for(let c of d){let l=c.thread_id;r.has(l)||r.set(l,[]),r.get(l).push(c);}}catch(d){throw new _("DB_ERROR","Failed to batch fetch tasks",d)}finally{a.close();}}return r}explainBatchFetchTasksPlan(t,e){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let o=A(i);try{return o.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,e)}`).map(d=>d.detail)}finally{o.close();}}return []}updateThreadTitle(t,e,r){if(!this.dbExists())return;let i=this.openHandle(true);try{let o=eq(p.id,t),a=r?and(o,eq(p.workspace_id,r)):o;if(!i.db.select({id:p.id}).from(p).where(a).limit(1).get())return;i.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to update thread title",o)}finally{i.close();}}upsertThread(t,e){let r=this.openHandle(true);try{let i=e.workspaceId?this.validateWorkspaceId(r,e.workspaceId):null,o=new Date().toISOString();if(r.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let d={updated_at:o};e.title!==void 0&&(d.title=e.title),e.titleLocked!==void 0&&(d.title_locked=e.titleLocked?1:0),r.db.update(p).set(d).where(eq(p.id,t)).run();}else r.db.insert(p).values({id:t,platform:e.platform,workspace_id:i,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:o,updated_at:o}).run();}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to upsert thread",i)}finally{r.close();}}ensureThread(t,e,r){let i=this.openHandle(true);try{let o=r?this.validateWorkspaceId(i,r):null,a=i.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get();if(a){o&&!a.workspace_id&&i.db.update(p).set({workspace_id:o}).where(eq(p.id,t)).run();return}let d=new Date().toISOString();i.db.insert(p).values({id:t,platform:e,workspace_id:o,message_count:0,created_at:d,updated_at:d}).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to ensure thread",o)}finally{i.close();}}saveUserMessage(t,e,r){if(!this.dbExists())return {firstMessage:false};let i=this.openHandle(true);try{let o=new Date().toISOString();return {firstMessage:i.db.transaction(d=>{let l=d.select({message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()?.message_count===0;return d.run(sql`
351
351
  UPDATE threads
352
352
  SET first_message = COALESCE(first_message, ${e}),
353
353
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -355,11 +355,11 @@ ${r.join(`
355
355
  message_count = message_count + 1,
356
356
  updated_at = ${o}
357
357
  WHERE id = ${t}
358
- `),l},{behavior:"immediate"})}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save user message",o)}finally{i.close();}}saveAssistantMessage(t,e,r){if(!this.dbExists())return;let i=this.openHandle(true);try{let o=new Date().toISOString();i.db.update(p).set({last_message:e,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save assistant message",o)}finally{i.close();}}updateThread(t,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let i={updated_at:new Date().toISOString()};e.title!==void 0&&(i.title=e.title,i.title_locked=1),e.titleLocked!==void 0&&(i.title_locked=e.titleLocked?1:0),r.db.update(p).set(i).where(eq(p.id,t)).run();}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to update thread",i)}finally{r.close();}}patchThreadTitleMetadata(t,e,r){let i=e;if(!i||typeof i!="object"||Array.isArray(i))return new It("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(i).some(c=>c!=="priority"&&c!=="state"))return new It("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let a=i;if(a.priority===void 0&&a.state===void 0)return new It("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let c of [a.priority,a.state])if(c!=null&&(typeof c!="string"||c.length===0))return new It("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let c=r?and(eq(p.id,t),eq(p.workspace_id,r)):eq(p.id,t);return d.db.transaction(l=>{let u=l.select({metadata:p.metadata}).from(p).where(c).get();if(!u)return null;let h=Ht(u.metadata),g=h.threadTitle,f=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};a.priority===null?delete f.priority:a.priority!==void 0&&(f.priority=a.priority),a.state===null?delete f.state:a.state!==void 0&&(f.state=a.state),Object.keys(f).length>0?h.threadTitle=f:delete h.threadTitle;let A=Object.keys(h).length>0?JSON.stringify(h):null,N=new Date().toISOString();l.update(p).set({metadata:A,updated_at:N}).where(c).run();let I=l.select({metadata:p.metadata}).from(p).where(c).get();if(!I)throw new _("DB_ERROR","Thread-title metadata update could not be read back");let P=Jr(I.metadata);return {threadId:t,priority:P.priority,state:P.state}},{behavior:"immediate"})}catch(c){throw c instanceof _?c:new _("DB_ERROR","Failed to patch thread-title metadata",c)}finally{d.close();}}togglePin(t,e){let r=this.openHandle(true);try{let i=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return r.db.transaction(o=>{let a=o.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(i).get();if(!a)return null;let d=a.pinned?0:1,c=Ht(a.metadata);if(d){let l=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),u=o.select({metadata:p.metadata}).from(p).where(l).all(),h=null;for(let g of u){let f=Ht(g.metadata);typeof f.pinOrder=="number"&&(h===null||f.pinOrder<h)&&(h=f.pinOrder);}c.pinOrder=h===null?0:h-1;}else delete c.pinOrder;return o.update(p).set({pinned:d,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(i).run(),{pinned:!!d}},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to toggle pin",i)}finally{r.close();}}reorderPins(t,e){let r=this.openHandle(true);try{r.db.transaction(i=>{for(let o=0;o<t.length;o++){let a=e?and(eq(p.id,t[o]),eq(p.workspace_id,e)):eq(p.id,t[o]),d=i.select({metadata:p.metadata}).from(p).where(a).get();if(!d)continue;let c=Ht(d.metadata);c.pinOrder=o+1,i.update(p).set({metadata:JSON.stringify(c)}).where(a).run();}},{behavior:"immediate"});}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to reorder pins",i)}finally{r.close();}}toggleStar(t,e){let r=this.openHandle(true);try{let i=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=r.db.select({starred:p.starred}).from(p).where(i).get();if(!o)return null;let a=o.starred?0:1;return r.db.update(p).set({starred:a}).where(i).run(),{starred:!!a}}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to toggle star",i)}finally{r.close();}}resolveOverdriveForRequest(t,e,r,i){let a=this.openHandle(true);try{let d=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return a.db.transaction(l=>{let u=l.select({metadata:p.metadata}).from(p).where(d).get();if(!u)return null;let h=u.metadata?JSON.parse(u.metadata):{},g=h.overdrive??{},f=i?.defaultTurns??g.defaultTurns??3,A=i?.updatedBy??"ui",N=new Date().toISOString(),I,P,j,Nt;switch(r){case "enable-count":{let Ct=i?.turns??f,Dt=i?.consumeCurrent?Math.max(Ct-1,0):Ct;I=Dt>0?"count":"off",P=Dt,j=!0,Nt="count";break}case "enable-latch":{I="latch",P=0,j=!0,Nt="latch";break}case "disable":{I="off",P=0,j=!1;break}default:{let Ct=g.state??"off",Dt=typeof g.remaining=="number"?g.remaining:0;if(Ct==="count"&&Dt>0){let be=Dt-1;be<=0?(I="off",P=0):(I="count",P=be),j=!0,Nt="count";}else Ct==="latch"?(I="latch",P=0,j=!0,Nt="latch"):(I="off",P=0,j=!1);break}}return h.overdrive={state:I,remaining:P,defaultTurns:f,updatedAt:N,updatedBy:A},l.update(p).set({metadata:JSON.stringify(h),updated_at:N}).where(d).run(),{applied:j,appliedMode:Nt,state:I,remaining:P}},{behavior:"immediate"})}catch(d){throw d instanceof _?d:new _("DB_ERROR","Failed to resolve overdrive",d)}finally{a.close();}}};var mn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Qr(n){let t=randomBytes(n*2),e="";for(let r=0;r<t.length&&e.length<n;r++){let i=t[r];i<248&&(e+=mn[i%62]);}for(;e.length<n;)e+=mn[randomBytes(1)[0]%62];return e}function ye(n){return `${n}_${Qr(8)}`}var Zr=["urgent","high","medium","low"],ts=["investigating","in-progress","in-review","on-hold","done"],kn="custom:";var es=new Set(Zr),ns=new Set(ts);function Ee(n){return typeof n=="string"&&es.has(n)}function Se(n){if(typeof n!="string")return false;if(ns.has(n))return true;if(n.startsWith("c_"))return n.length>2;if(!n.startsWith(kn))return false;let t=n.slice(kn.length);return t.length>=1&&t.length<=20}function Tn(n){if(!n)return null;try{let t=JSON.parse(n);return !t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}function Re(n){let t=Tn(n);if(!t)return {};let e=t.threadTitle;if(!e||typeof e!="object"||Array.isArray(e))return {};let r=e,i={};return Ee(r.priority)&&(i.priority=r.priority),Se(r.state)&&(i.state=r.state),i}function wn(n,t){let e=Tn(n)??{},r={...Re(n)};return t.priority===null?delete r.priority:t.priority!==void 0&&(r.priority=t.priority),t.state===null?delete r.state:t.state!==void 0&&(r.state=t.state),r.priority===void 0&&r.state===void 0?delete e.threadTitle:e.threadTitle=r,Object.keys(e).length===0?null:JSON.stringify(e)}var xe=class extends _{threadId;highlightId;expectedRevision;currentRevision;constructor(t,e,r,i){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${i}`),this.name="ThreadHistoryConflictError",this.threadId=t,this.highlightId=e,this.expectedRevision=r,this.currentRevision=i;}},qt=class extends xe{},os=new Set(Ze),as=new Set(Qe),ds=new Set(tn),cs=new Set(en),ls=50,Rn=100,vn=280;function O(n){throw new _("VALIDATION",n)}function At(n){throw new _("NOT_FOUND",n)}function L(n,t){(typeof n!="string"||n.trim().length===0)&&O(`${t} is required`);}function te(n={}){let t=n.actor??n,e=t.actorType??"system";return os.has(e)||O(`invalid actorType: ${String(e)}`),t.actorId!==void 0&&t.actorId!==null&&typeof t.actorId!="string"&&O("actorId must be a string or null"),{actorType:e,actorId:t.actorId??null}}function us(n){L(n.threadId,"threadId"),n.workspaceId!==void 0&&n.workspaceId!==null&&L(n.workspaceId,"workspaceId"),n.title!==void 0&&n.title!==null&&((typeof n.title!="string"||n.title.trim().length===0)&&O("title must not be empty"),n.title.length>120&&O("title must be at most 120 characters")),n.priority!==void 0&&n.priority!==null&&!Ee(n.priority)&&O(`invalid priority: ${String(n.priority)}`),n.state!==void 0&&n.state!==null&&!Se(n.state)&&O(`invalid state: ${String(n.state)}`);}function _s(n){n.beforeSeq!==void 0&&n.afterSeq!==void 0&&O("beforeSeq and afterSeq cannot be used together");for(let[e,r]of [["beforeSeq",n.beforeSeq],["afterSeq",n.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&O(`${e} must be a non-negative integer`);let t=n.limit??ls;return (!Number.isInteger(t)||t<1||t>Rn)&&O(`limit must be between 1 and ${Rn}`),t}function In(n){typeof n!="string"&&O("text is required");let t=n.trim();return t.length===0&&O("text must not be empty"),t.length>vn&&O(`text must be at most ${vn} characters`),t}function bt(n,t){return L(n??"",t),n}function xn(n){cs.has(n)||O(`invalid highlight kind: ${String(n)}`);}function ps(n){ds.has(n)||O(`invalid highlight source: ${String(n)}`);}function hs(n){L(n.threadId,"threadId"),L(n.workspaceId,"workspaceId");let t=n.source??"manual";ps(t),xn(n.kind);let e=In(n.text),r=n.coversFromTaskId??n.fromTaskId??n.taskId,i=n.coversToTaskId??n.toTaskId??n.taskId;if(t==="manual"){let u=n.taskId??(r&&i&&r===i?r:void 0),h=bt(u,"taskId");return (r!==h||i!==h)&&O("manual highlights must cover exactly one task"),{source:t,kind:n.kind,text:e,coversFromTaskId:h,coversToTaskId:h,agentId:n.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let o=bt(r,"coversFromTaskId"),a=bt(i,"coversToTaskId"),d=n.sourceTaskId??o,c=n.detectorVersion??(n.idempotencyKey!==void 0?"default":null),l=n.contentFingerprint??n.idempotencyKey??null;return bt(d??void 0,"sourceTaskId"),bt(c??void 0,"detectorVersion"),bt(l??void 0,"contentFingerprint"),{source:t,kind:n.kind,text:e,coversFromTaskId:o,coversToTaskId:a,agentId:n.agentId??null,sourceTaskId:d,detectorVersion:c,contentFingerprint:l}}function se(n){let t=Re(n.metadata);return {threadId:n.id,workspaceId:n.workspace_id,title:n.title,priority:t.priority??null,state:t.state??null,metadata:n.metadata,titleLocked:n.title_locked===1,updatedAt:n.updated_at}}function gs(n){try{let t=JSON.stringify(n);return (!t||t==="null"||t.startsWith("["))&&O("event payload must be a JSON object"),t}catch(t){throw new _("VALIDATION","event payload must be JSON serializable",t)}}function ee(n,t){return n.select({maxSeq:sql`COALESCE(MAX(${S.seq}), 0)`}).from(S).where(eq(S.thread_id,t)).get()?.maxSeq??0}function ne(n,t){return !!n.select({id:S.id}).from(S).where(eq(S.thread_id,t)).limit(1).get()}function Ut(n,t){as.has(t.type)||O(`invalid thread event type: ${String(t.type)}`);let e=ye("the");n.insert(S).values({id:e,thread_id:t.threadId,seq:t.seq,type:t.type,actor_type:t.actorType,actor_id:t.actorId,task_id:t.taskId??null,highlight_id:t.highlightId??null,payload_json:gs(t.payload),created_at:t.createdAt}).run();let r=n.select().from(S).where(eq(S.id,e)).get();if(!r)throw new _("DB_ERROR","Thread event insert did not return a row");return r}function re(n,t,e,r,i){let o=se(t);Ut(n,{threadId:t.id,seq:i,type:"thread.snapshot.imported",actorType:e.actorType,actorId:e.actorId,createdAt:r,payload:{title:o.title,priority:o.priority,state:o.state}});}function ve(n){return {highlightId:n.id,source:n.source,kind:n.kind,status:n.status,coversFromTaskId:n.covers_from_task_id,coversToTaskId:n.covers_to_task_id,revision:n.revision,...n.dismissed_at===null?{}:{dismissedAt:n.dismissed_at}}}function Ie(n,t,e,r,i,o,a){let d=i==="thread.highlight.created"?ve(t):{before:a?ve({...t,...a,id:t.id}):void 0,after:ve(t)};return Ut(n,{threadId:t.thread_id,seq:o,type:i,actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.source==="manual"?t.covers_from_task_id:t.source_task_id??t.covers_from_task_id,highlightId:t.id,payload:d})}var ie=class extends J{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(!t&&!existsSync(e))throw new _("NOT_FOUND","Database not found");if(t){let i=dirname(e);existsSync(i)||mkdirSync(i,{recursive:true});}let r=b(e);if(t)try{gt(r.db,e);}catch(i){throw r.close(),i}return r}findThread(t,e,r){let i=eq(p.id,e),o=r===void 0?i:r===null?and(i,isNull(p.workspace_id)):and(i,eq(p.workspace_id,r));return t.select().from(p).where(o).limit(1).get()}resolveWorkspaceId(t){if(L(t,"threadId"),!existsSync(this.resolveDbPath()))return null;let e=this.openHandle(false);try{return e.db.select({workspaceId:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to resolve thread workspace",r)}finally{e.close();}}updateSnapshot(t){us(t);let e=te(t),r=new Date().toISOString(),i=this.openHandle(true);try{return i.db.transaction(o=>{let a=this.findThread(o,t.threadId,t.workspaceId);a||At(`Thread ${t.threadId} not found`);let d=se(a),c=t.title!==void 0,l=c&&t.title!==d.title,u=c&&a.title_locked!==1,h=t.priority!==void 0&&t.priority!==d.priority,g=t.state!==void 0&&t.state!==d.state,f=l||h||g;if(!f&&!u)return d;let A=a.metadata;(h||g)&&(A=wn(a.metadata,{priority:t.priority,state:t.state}));let N={};if(f&&(N.metadata=A,N.updated_at=r),l&&(N.title=t.title),c&&(N.title_locked=1),o.update(p).set(N).where(t.workspaceId===void 0?eq(p.id,t.threadId):t.workspaceId===null?and(eq(p.id,t.threadId),isNull(p.workspace_id)):and(eq(p.id,t.threadId),eq(p.workspace_id,t.workspaceId))).run(),!f){let j={...a,title_locked:1};return se(j)}let I=ee(o,a.id)+1;ne(o,a.id)||(re(o,a,e,r,I),I+=1),l&&(Ut(o,{threadId:a.id,seq:I,type:"thread.title.changed",actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.taskId,payload:{before:d.title,after:t.title}}),I+=1),h&&(Ut(o,{threadId:a.id,seq:I,type:"thread.priority.changed",actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.taskId,payload:{before:d.priority,after:t.priority}}),I+=1),g&&Ut(o,{threadId:a.id,seq:I,type:"thread.state.changed",actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.taskId,payload:{before:d.state,after:t.state}});let P={...a,title:l?t.title:a.title,metadata:A,title_locked:c?1:a.title_locked,updated_at:r};return se(P)},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to update thread snapshot",o)}finally{i.close();}}mutateSnapshot(t){return this.updateSnapshot(t)}updateThreadSnapshot(t){return this.updateSnapshot(t)}getLatestSeq(t,e){if(L(t,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,t,e)?r.db.select({maxSeq:sql`COALESCE(MAX(${S.seq}), 0)`}).from(S).where(eq(S.thread_id,t)).get()?.maxSeq??0:null}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to read latest thread event sequence",i)}finally{r.close();}}listTimeline(t,e,r={}){let i=typeof t=="string"?{...r,threadId:t,workspaceId:e}:t;L(i.threadId,"threadId"),L(i.workspaceId,"workspaceId");let o=_s(i);if(!existsSync(this.resolveDbPath()))return null;let a=this.openHandle(false);try{if(!this.findThread(a.db,i.threadId,i.workspaceId))return null;let d=a.db.select({maxSeq:sql`COALESCE(MAX(${S.seq}), 0)`}).from(S).where(eq(S.thread_id,i.threadId)).get()?.maxSeq??0,c;i.beforeSeq!==void 0?c=a.db.select().from(S).where(and(eq(S.thread_id,i.threadId),lt(S.seq,i.beforeSeq))).orderBy(desc(S.seq)).limit(o+1).all().reverse():i.afterSeq!==void 0?c=a.db.select().from(S).where(and(eq(S.thread_id,i.threadId),sql`${S.seq} > ${i.afterSeq}`)).orderBy(asc(S.seq)).limit(o+1).all():c=a.db.select().from(S).where(eq(S.thread_id,i.threadId)).orderBy(desc(S.seq)).limit(o+1).all().reverse();let l=c.length>o,u=i.afterSeq!==void 0?c.slice(0,o):l?c.slice(1):c,h=!1,g=u[0];return g&&(h=!!a.db.select({id:S.id}).from(S).where(and(eq(S.thread_id,i.threadId),lt(S.seq,g.seq))).limit(1).get()),{items:u,latestSeq:d,hasMoreOlder:h}}catch(d){throw d instanceof _?d:new _("DB_ERROR","Failed to list thread timeline",d)}finally{a.close();}}listEvents(t,e,r){return this.listTimeline(t,e,r)}getTimeline(t,e,r){return this.listTimeline(t,e,r)}createHighlight(t){let e=hs(t),r=te(t),i=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(a=>{let d=this.findThread(a,t.threadId,t.workspaceId);if(d||At(`Thread ${t.threadId} not found`),e.source==="auto"){let g=a.select().from(E).where(and(eq(E.thread_id,t.threadId),eq(E.source_task_id,e.sourceTaskId),eq(E.detector_version,e.detectorVersion),eq(E.content_fingerprint,e.contentFingerprint))).orderBy(asc(E.created_at),asc(E.id)).limit(1).get();if(g)return g}let c=t.id??ye("thl"),l={id:c,thread_id:t.threadId,source:e.source,kind:e.kind,status:"active",text:e.text,covers_from_task_id:e.coversFromTaskId,covers_to_task_id:e.coversToTaskId,revision:0,created_at:i,updated_at:i,agent_id:e.agentId,source_task_id:e.sourceTaskId,detector_version:e.detectorVersion,content_fingerprint:e.contentFingerprint,dismissed_at:null};a.insert(E).values(l).run();let u=a.select().from(E).where(eq(E.id,c)).get();if(!u)throw new _("DB_ERROR","Highlight insert did not return a row");let h=ee(a,d.id)+1;return ne(a,d.id)||(re(a,d,r,i,h),h+=1),Ie(a,u,r,i,"thread.highlight.created",h),u},{behavior:"immediate"})}catch(a){throw a instanceof _?a:new _("DB_ERROR","Failed to create thread highlight",a)}finally{o.close();}}updateHighlight(t){L(t.threadId,"threadId"),L(t.workspaceId,"workspaceId"),L(t.highlightId,"highlightId"),(!Number.isInteger(t.expectedRevision)||t.expectedRevision<0)&&O("expectedRevision must be a non-negative integer"),t.text===void 0&&t.kind===void 0&&t.coversFromTaskId===void 0&&t.coversToTaskId===void 0&&O("highlight update requires at least one field"),t.kind!==void 0&&xn(t.kind);let e=t.text===void 0?void 0:In(t.text),r=te(t),i=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(a=>{let d=this.findThread(a,t.threadId,t.workspaceId);d||At(`Thread ${t.threadId} not found`);let c=a.select().from(E).where(and(eq(E.id,t.highlightId),eq(E.thread_id,d.id))).limit(1).get();if(c||At(`Highlight ${t.highlightId} not found`),c.revision!==t.expectedRevision)throw new qt(d.id,c.id,t.expectedRevision,c.revision);if(c.status!=="active")throw new qt(d.id,c.id,t.expectedRevision,c.revision);let l=t.kind??c.kind,u=e??c.text,h=t.coversFromTaskId??c.covers_from_task_id,g=t.coversToTaskId??c.covers_to_task_id;(!u||h.length===0||g.length===0)&&O("highlight projection is incomplete");let f=l!==c.kind||u!==c.text||h!==c.covers_from_task_id||g!==c.covers_to_task_id,A=r.actorType==="user"&&c.source==="auto"&&f?"manual":c.source;if(!(f||A!==c.source))return c;let I=c.revision+1;a.update(E).set({source:A,kind:l,text:u,covers_from_task_id:h,covers_to_task_id:g,revision:I,updated_at:i}).where(and(eq(E.id,c.id),eq(E.revision,c.revision))).run();let P=a.select().from(E).where(eq(E.id,c.id)).get();if(!P)throw new _("DB_ERROR","Highlight update did not return a row");let j=ee(a,d.id)+1;return ne(a,d.id)||(re(a,d,r,i,j),j+=1),Ie(a,P,r,i,"thread.highlight.updated",j,c),P},{behavior:"immediate"})}catch(a){throw a instanceof _?a:new _("DB_ERROR","Failed to update thread highlight",a)}finally{o.close();}}dismissHighlight(t){L(t.threadId,"threadId"),L(t.workspaceId,"workspaceId"),L(t.highlightId,"highlightId"),(!Number.isInteger(t.expectedRevision)||t.expectedRevision<0)&&O("expectedRevision must be a non-negative integer");let e=te(t),r=new Date().toISOString(),i=this.openHandle(true);try{return i.db.transaction(o=>{let a=this.findThread(o,t.threadId,t.workspaceId);a||At(`Thread ${t.threadId} not found`);let d=o.select().from(E).where(and(eq(E.id,t.highlightId),eq(E.thread_id,a.id))).limit(1).get();if(d||At(`Highlight ${t.highlightId} not found`),d.revision!==t.expectedRevision)throw new qt(a.id,d.id,t.expectedRevision,d.revision);if(d.status==="dismissed")return d;let c=d.revision+1;o.update(E).set({status:"dismissed",text:null,revision:c,updated_at:r,dismissed_at:r}).where(and(eq(E.id,d.id),eq(E.revision,d.revision))).run();let l=o.select().from(E).where(eq(E.id,d.id)).get();if(!l)throw new _("DB_ERROR","Highlight dismissal did not return a row");let u=ee(o,a.id)+1;return ne(o,a.id)||(re(o,a,e,r,u),u+=1),Ie(o,l,e,r,"thread.highlight.deleted",u,d),l},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to dismiss thread highlight",o)}finally{i.close();}}listActiveHighlights(t,e,r={}){if(L(t,"threadId"),L(e,"workspaceId"),r.taskId!==void 0&&L(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&L(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&L(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,t,e))return null;let a=i.db.select().from(E).where(and(eq(E.thread_id,t),eq(E.status,"active"))).orderBy(asc(E.created_at),asc(E.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return a;let d=i.db.all(sql`
358
+ `),l},{behavior:"immediate"})}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save user message",o)}finally{i.close();}}saveAssistantMessage(t,e,r){if(!this.dbExists())return;let i=this.openHandle(true);try{let o=new Date().toISOString();i.db.update(p).set({last_message:e,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save assistant message",o)}finally{i.close();}}updateThread(t,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let i={updated_at:new Date().toISOString()};e.title!==void 0&&(i.title=e.title,i.title_locked=1),e.titleLocked!==void 0&&(i.title_locked=e.titleLocked?1:0),r.db.update(p).set(i).where(eq(p.id,t)).run();}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to update thread",i)}finally{r.close();}}patchThreadTitleMetadata(t,e,r){let i=e;if(!i||typeof i!="object"||Array.isArray(i))return new It("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(i).some(c=>c!=="priority"&&c!=="state"))return new It("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let a=i;if(a.priority===void 0&&a.state===void 0)return new It("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let c of [a.priority,a.state])if(c!=null&&(typeof c!="string"||c.length===0))return new It("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let c=r?and(eq(p.id,t),eq(p.workspace_id,r)):eq(p.id,t);return d.db.transaction(l=>{let u=l.select({metadata:p.metadata}).from(p).where(c).get();if(!u)return null;let h=Ht(u.metadata),g=h.threadTitle,f=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};a.priority===null?delete f.priority:a.priority!==void 0&&(f.priority=a.priority),a.state===null?delete f.state:a.state!==void 0&&(f.state=a.state),Object.keys(f).length>0?h.threadTitle=f:delete h.threadTitle;let b=Object.keys(h).length>0?JSON.stringify(h):null,N=new Date().toISOString();l.update(p).set({metadata:b,updated_at:N}).where(c).run();let I=l.select({metadata:p.metadata}).from(p).where(c).get();if(!I)throw new _("DB_ERROR","Thread-title metadata update could not be read back");let P=ns(I.metadata);return {threadId:t,priority:P.priority,state:P.state}},{behavior:"immediate"})}catch(c){throw c instanceof _?c:new _("DB_ERROR","Failed to patch thread-title metadata",c)}finally{d.close();}}togglePin(t,e){let r=this.openHandle(true);try{let i=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return r.db.transaction(o=>{let a=o.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(i).get();if(!a)return null;let d=a.pinned?0:1,c=Ht(a.metadata);if(d){let l=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),u=o.select({metadata:p.metadata}).from(p).where(l).all(),h=null;for(let g of u){let f=Ht(g.metadata);typeof f.pinOrder=="number"&&(h===null||f.pinOrder<h)&&(h=f.pinOrder);}c.pinOrder=h===null?0:h-1;}else delete c.pinOrder;return o.update(p).set({pinned:d,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(i).run(),{pinned:!!d}},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to toggle pin",i)}finally{r.close();}}reorderPins(t,e){let r=this.openHandle(true);try{r.db.transaction(i=>{for(let o=0;o<t.length;o++){let a=e?and(eq(p.id,t[o]),eq(p.workspace_id,e)):eq(p.id,t[o]),d=i.select({metadata:p.metadata}).from(p).where(a).get();if(!d)continue;let c=Ht(d.metadata);c.pinOrder=o+1,i.update(p).set({metadata:JSON.stringify(c)}).where(a).run();}},{behavior:"immediate"});}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to reorder pins",i)}finally{r.close();}}toggleStar(t,e){let r=this.openHandle(true);try{let i=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=r.db.select({starred:p.starred}).from(p).where(i).get();if(!o)return null;let a=o.starred?0:1;return r.db.update(p).set({starred:a}).where(i).run(),{starred:!!a}}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to toggle star",i)}finally{r.close();}}resolveOverdriveForRequest(t,e,r,i){let a=this.openHandle(true);try{let d=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return a.db.transaction(l=>{let u=l.select({metadata:p.metadata}).from(p).where(d).get();if(!u)return null;let h=u.metadata?JSON.parse(u.metadata):{},g=h.overdrive??{},f=i?.defaultTurns??g.defaultTurns??3,b=i?.updatedBy??"ui",N=new Date().toISOString(),I,P,q,Nt;switch(r){case "enable-count":{let Ct=i?.turns??f,Dt=i?.consumeCurrent?Math.max(Ct-1,0):Ct;I=Dt>0?"count":"off",P=Dt,q=!0,Nt="count";break}case "enable-latch":{I="latch",P=0,q=!0,Nt="latch";break}case "disable":{I="off",P=0,q=!1;break}default:{let Ct=g.state??"off",Dt=typeof g.remaining=="number"?g.remaining:0;if(Ct==="count"&&Dt>0){let Ae=Dt-1;Ae<=0?(I="off",P=0):(I="count",P=Ae),q=!0,Nt="count";}else Ct==="latch"?(I="latch",P=0,q=!0,Nt="latch"):(I="off",P=0,q=!1);break}}return h.overdrive={state:I,remaining:P,defaultTurns:f,updatedAt:N,updatedBy:b},l.update(p).set({metadata:JSON.stringify(h),updated_at:N}).where(d).run(),{applied:q,appliedMode:Nt,state:I,remaining:P}},{behavior:"immediate"})}catch(d){throw d instanceof _?d:new _("DB_ERROR","Failed to resolve overdrive",d)}finally{a.close();}}};var kn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function rs(n){let t=randomBytes(n*2),e="";for(let r=0;r<t.length&&e.length<n;r++){let i=t[r];i<248&&(e+=kn[i%62]);}for(;e.length<n;)e+=kn[randomBytes(1)[0]%62];return e}function ye(n){return `${n}_${rs(8)}`}var ss=["urgent","high","medium","low"],is=["investigating","in-progress","in-review","on-hold","done"],Tn="custom:";var os=new Set(ss),as=new Set(is);function Ee(n){return typeof n=="string"&&os.has(n)}function Se(n){if(typeof n!="string")return false;if(as.has(n))return true;if(n.startsWith("c_"))return n.length>2;if(!n.startsWith(Tn))return false;let t=n.slice(Tn.length);return t.length>=1&&t.length<=20}function wn(n){if(!n)return null;try{let t=JSON.parse(n);return !t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}function Re(n){let t=wn(n);if(!t)return {};let e=t.threadTitle;if(!e||typeof e!="object"||Array.isArray(e))return {};let r=e,i={};return Ee(r.priority)&&(i.priority=r.priority),Se(r.state)&&(i.state=r.state),i}function yn(n,t){let e=wn(n)??{},r={...Re(n)};return t.priority===null?delete r.priority:t.priority!==void 0&&(r.priority=t.priority),t.state===null?delete r.state:t.state!==void 0&&(r.state=t.state),r.priority===void 0&&r.state===void 0?delete e.threadTitle:e.threadTitle=r,Object.keys(e).length===0?null:JSON.stringify(e)}var xe=class extends _{threadId;highlightId;expectedRevision;currentRevision;constructor(t,e,r,i){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${i}`),this.name="ThreadHistoryConflictError",this.threadId=t,this.highlightId=e,this.expectedRevision=r,this.currentRevision=i;}},jt=class extends xe{},us=new Set(Ze),_s=new Set(Qe),ps=new Set(tn),hs=new Set(en),gs=50,vn=100,In=280;function O(n){throw new _("VALIDATION",n)}function bt(n){throw new _("NOT_FOUND",n)}function $(n,t){(typeof n!="string"||n.trim().length===0)&&O(`${t} is required`);}function te(n={}){let t=n.actor??n,e=t.actorType??"system";return us.has(e)||O(`invalid actorType: ${String(e)}`),t.actorId!==void 0&&t.actorId!==null&&typeof t.actorId!="string"&&O("actorId must be a string or null"),{actorType:e,actorId:t.actorId??null}}function fs(n){$(n.threadId,"threadId"),n.workspaceId!==void 0&&n.workspaceId!==null&&$(n.workspaceId,"workspaceId"),n.title!==void 0&&n.title!==null&&((typeof n.title!="string"||n.title.trim().length===0)&&O("title must not be empty"),n.title.length>120&&O("title must be at most 120 characters")),n.priority!==void 0&&n.priority!==null&&!Ee(n.priority)&&O(`invalid priority: ${String(n.priority)}`),n.state!==void 0&&n.state!==null&&!Se(n.state)&&O(`invalid state: ${String(n.state)}`);}function ms(n){n.beforeSeq!==void 0&&n.afterSeq!==void 0&&O("beforeSeq and afterSeq cannot be used together");for(let[e,r]of [["beforeSeq",n.beforeSeq],["afterSeq",n.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&O(`${e} must be a non-negative integer`);let t=n.limit??gs;return (!Number.isInteger(t)||t<1||t>vn)&&O(`limit must be between 1 and ${vn}`),t}function xn(n){typeof n!="string"&&O("text is required");let t=n.trim();return t.length===0&&O("text must not be empty"),t.length>In&&O(`text must be at most ${In} characters`),t}function At(n,t){return $(n??"",t),n}function bn(n){hs.has(n)||O(`invalid highlight kind: ${String(n)}`);}function ks(n){ps.has(n)||O(`invalid highlight source: ${String(n)}`);}function Ts(n){$(n.threadId,"threadId"),$(n.workspaceId,"workspaceId");let t=n.source??"manual";ks(t),bn(n.kind);let e=xn(n.text),r=n.coversFromTaskId??n.fromTaskId??n.taskId,i=n.coversToTaskId??n.toTaskId??n.taskId;if(t==="manual"){let u=n.taskId??(r&&i&&r===i?r:void 0),h=At(u,"taskId");return (r!==h||i!==h)&&O("manual highlights must cover exactly one task"),{source:t,kind:n.kind,text:e,coversFromTaskId:h,coversToTaskId:h,agentId:n.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let o=At(r,"coversFromTaskId"),a=At(i,"coversToTaskId"),d=n.sourceTaskId??o,c=n.detectorVersion??(n.idempotencyKey!==void 0?"default":null),l=n.contentFingerprint??n.idempotencyKey??null;return At(d??void 0,"sourceTaskId"),At(c??void 0,"detectorVersion"),At(l??void 0,"contentFingerprint"),{source:t,kind:n.kind,text:e,coversFromTaskId:o,coversToTaskId:a,agentId:n.agentId??null,sourceTaskId:d,detectorVersion:c,contentFingerprint:l}}function se(n){let t=Re(n.metadata);return {threadId:n.id,workspaceId:n.workspace_id,title:n.title,priority:t.priority??null,state:t.state??null,metadata:n.metadata,titleLocked:n.title_locked===1,updatedAt:n.updated_at}}function ws(n){try{let t=JSON.stringify(n);return (!t||t==="null"||t.startsWith("["))&&O("event payload must be a JSON object"),t}catch(t){throw new _("VALIDATION","event payload must be JSON serializable",t)}}function ee(n,t){return n.select({maxSeq:sql`COALESCE(MAX(${S.seq}), 0)`}).from(S).where(eq(S.thread_id,t)).get()?.maxSeq??0}function ne(n,t){return !!n.select({id:S.id}).from(S).where(eq(S.thread_id,t)).limit(1).get()}function Bt(n,t){_s.has(t.type)||O(`invalid thread event type: ${String(t.type)}`);let e=ye("the");n.insert(S).values({id:e,thread_id:t.threadId,seq:t.seq,type:t.type,actor_type:t.actorType,actor_id:t.actorId,task_id:t.taskId??null,highlight_id:t.highlightId??null,payload_json:ws(t.payload),created_at:t.createdAt}).run();let r=n.select().from(S).where(eq(S.id,e)).get();if(!r)throw new _("DB_ERROR","Thread event insert did not return a row");return r}function re(n,t,e,r,i){let o=se(t);Bt(n,{threadId:t.id,seq:i,type:"thread.snapshot.imported",actorType:e.actorType,actorId:e.actorId,createdAt:r,payload:{title:o.title,priority:o.priority,state:o.state}});}function ve(n){return {highlightId:n.id,source:n.source,kind:n.kind,status:n.status,coversFromTaskId:n.covers_from_task_id,coversToTaskId:n.covers_to_task_id,revision:n.revision,...n.dismissed_at===null?{}:{dismissedAt:n.dismissed_at}}}function Ie(n,t,e,r,i,o,a){let d=i==="thread.highlight.created"?ve(t):{before:a?ve({...t,...a,id:t.id}):void 0,after:ve(t)};return Bt(n,{threadId:t.thread_id,seq:o,type:i,actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.source==="manual"?t.covers_from_task_id:t.source_task_id??t.covers_from_task_id,highlightId:t.id,payload:d})}var ie=class extends J{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(!t&&!existsSync(e))throw new _("NOT_FOUND","Database not found");if(t){let i=dirname(e);existsSync(i)||mkdirSync(i,{recursive:true});}let r=A(e);if(t)try{gt(r.db,e);}catch(i){throw r.close(),i}return r}findThread(t,e,r){let i=eq(p.id,e),o=r===void 0?i:r===null?and(i,isNull(p.workspace_id)):and(i,eq(p.workspace_id,r));return t.select().from(p).where(o).limit(1).get()}resolveWorkspaceId(t){if($(t,"threadId"),!existsSync(this.resolveDbPath()))return null;let e=this.openHandle(false);try{return e.db.select({workspaceId:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to resolve thread workspace",r)}finally{e.close();}}updateSnapshot(t){fs(t);let e=te(t),r=new Date().toISOString(),i=this.openHandle(true);try{return i.db.transaction(o=>{let a=this.findThread(o,t.threadId,t.workspaceId);a||bt(`Thread ${t.threadId} not found`);let d=se(a),c=t.title!==void 0,l=c&&t.title!==d.title,u=c&&a.title_locked!==1,h=t.priority!==void 0&&t.priority!==d.priority,g=t.state!==void 0&&t.state!==d.state,f=l||h||g;if(!f&&!u)return d;let b=a.metadata;(h||g)&&(b=yn(a.metadata,{priority:t.priority,state:t.state}));let N={};if(f&&(N.metadata=b,N.updated_at=r),l&&(N.title=t.title),c&&(N.title_locked=1),o.update(p).set(N).where(t.workspaceId===void 0?eq(p.id,t.threadId):t.workspaceId===null?and(eq(p.id,t.threadId),isNull(p.workspace_id)):and(eq(p.id,t.threadId),eq(p.workspace_id,t.workspaceId))).run(),!f){let q={...a,title_locked:1};return se(q)}let I=ee(o,a.id)+1;ne(o,a.id)||(re(o,a,e,r,I),I+=1),l&&(Bt(o,{threadId:a.id,seq:I,type:"thread.title.changed",actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.taskId,payload:{before:d.title,after:t.title}}),I+=1),h&&(Bt(o,{threadId:a.id,seq:I,type:"thread.priority.changed",actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.taskId,payload:{before:d.priority,after:t.priority}}),I+=1),g&&Bt(o,{threadId:a.id,seq:I,type:"thread.state.changed",actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.taskId,payload:{before:d.state,after:t.state}});let P={...a,title:l?t.title:a.title,metadata:b,title_locked:c?1:a.title_locked,updated_at:r};return se(P)},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to update thread snapshot",o)}finally{i.close();}}mutateSnapshot(t){return this.updateSnapshot(t)}updateThreadSnapshot(t){return this.updateSnapshot(t)}getLatestSeq(t,e){if($(t,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,t,e)?r.db.select({maxSeq:sql`COALESCE(MAX(${S.seq}), 0)`}).from(S).where(eq(S.thread_id,t)).get()?.maxSeq??0:null}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to read latest thread event sequence",i)}finally{r.close();}}listTimeline(t,e,r={}){let i=typeof t=="string"?{...r,threadId:t,workspaceId:e}:t;$(i.threadId,"threadId"),$(i.workspaceId,"workspaceId");let o=ms(i);if(!existsSync(this.resolveDbPath()))return null;let a=this.openHandle(false);try{if(!this.findThread(a.db,i.threadId,i.workspaceId))return null;let d=a.db.select({maxSeq:sql`COALESCE(MAX(${S.seq}), 0)`}).from(S).where(eq(S.thread_id,i.threadId)).get()?.maxSeq??0,c;i.beforeSeq!==void 0?c=a.db.select().from(S).where(and(eq(S.thread_id,i.threadId),lt(S.seq,i.beforeSeq))).orderBy(desc(S.seq)).limit(o+1).all().reverse():i.afterSeq!==void 0?c=a.db.select().from(S).where(and(eq(S.thread_id,i.threadId),sql`${S.seq} > ${i.afterSeq}`)).orderBy(asc(S.seq)).limit(o+1).all():c=a.db.select().from(S).where(eq(S.thread_id,i.threadId)).orderBy(desc(S.seq)).limit(o+1).all().reverse();let l=c.length>o,u=i.afterSeq!==void 0?c.slice(0,o):l?c.slice(1):c,h=!1,g=u[0];return g&&(h=!!a.db.select({id:S.id}).from(S).where(and(eq(S.thread_id,i.threadId),lt(S.seq,g.seq))).limit(1).get()),{items:u,latestSeq:d,hasMoreOlder:h}}catch(d){throw d instanceof _?d:new _("DB_ERROR","Failed to list thread timeline",d)}finally{a.close();}}listEvents(t,e,r){return this.listTimeline(t,e,r)}getTimeline(t,e,r){return this.listTimeline(t,e,r)}createHighlight(t){let e=Ts(t),r=te(t),i=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(a=>{let d=this.findThread(a,t.threadId,t.workspaceId);if(d||bt(`Thread ${t.threadId} not found`),e.source==="auto"){let g=a.select().from(E).where(and(eq(E.thread_id,t.threadId),eq(E.source_task_id,e.sourceTaskId),eq(E.detector_version,e.detectorVersion),eq(E.content_fingerprint,e.contentFingerprint))).orderBy(asc(E.created_at),asc(E.id)).limit(1).get();if(g)return g}let c=t.id??ye("thl"),l={id:c,thread_id:t.threadId,source:e.source,kind:e.kind,status:"active",text:e.text,covers_from_task_id:e.coversFromTaskId,covers_to_task_id:e.coversToTaskId,revision:0,created_at:i,updated_at:i,agent_id:e.agentId,source_task_id:e.sourceTaskId,detector_version:e.detectorVersion,content_fingerprint:e.contentFingerprint,dismissed_at:null};a.insert(E).values(l).run();let u=a.select().from(E).where(eq(E.id,c)).get();if(!u)throw new _("DB_ERROR","Highlight insert did not return a row");let h=ee(a,d.id)+1;return ne(a,d.id)||(re(a,d,r,i,h),h+=1),Ie(a,u,r,i,"thread.highlight.created",h),u},{behavior:"immediate"})}catch(a){throw a instanceof _?a:new _("DB_ERROR","Failed to create thread highlight",a)}finally{o.close();}}updateHighlight(t){$(t.threadId,"threadId"),$(t.workspaceId,"workspaceId"),$(t.highlightId,"highlightId"),(!Number.isInteger(t.expectedRevision)||t.expectedRevision<0)&&O("expectedRevision must be a non-negative integer"),t.text===void 0&&t.kind===void 0&&t.coversFromTaskId===void 0&&t.coversToTaskId===void 0&&O("highlight update requires at least one field"),t.kind!==void 0&&bn(t.kind);let e=t.text===void 0?void 0:xn(t.text),r=te(t),i=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(a=>{let d=this.findThread(a,t.threadId,t.workspaceId);d||bt(`Thread ${t.threadId} not found`);let c=a.select().from(E).where(and(eq(E.id,t.highlightId),eq(E.thread_id,d.id))).limit(1).get();if(c||bt(`Highlight ${t.highlightId} not found`),c.revision!==t.expectedRevision)throw new jt(d.id,c.id,t.expectedRevision,c.revision);if(c.status!=="active")throw new jt(d.id,c.id,t.expectedRevision,c.revision);let l=t.kind??c.kind,u=e??c.text,h=t.coversFromTaskId??c.covers_from_task_id,g=t.coversToTaskId??c.covers_to_task_id;(!u||h.length===0||g.length===0)&&O("highlight projection is incomplete");let f=l!==c.kind||u!==c.text||h!==c.covers_from_task_id||g!==c.covers_to_task_id,b=r.actorType==="user"&&c.source==="auto"&&f?"manual":c.source;if(!(f||b!==c.source))return c;let I=c.revision+1;a.update(E).set({source:b,kind:l,text:u,covers_from_task_id:h,covers_to_task_id:g,revision:I,updated_at:i}).where(and(eq(E.id,c.id),eq(E.revision,c.revision))).run();let P=a.select().from(E).where(eq(E.id,c.id)).get();if(!P)throw new _("DB_ERROR","Highlight update did not return a row");let q=ee(a,d.id)+1;return ne(a,d.id)||(re(a,d,r,i,q),q+=1),Ie(a,P,r,i,"thread.highlight.updated",q,c),P},{behavior:"immediate"})}catch(a){throw a instanceof _?a:new _("DB_ERROR","Failed to update thread highlight",a)}finally{o.close();}}dismissHighlight(t){$(t.threadId,"threadId"),$(t.workspaceId,"workspaceId"),$(t.highlightId,"highlightId"),(!Number.isInteger(t.expectedRevision)||t.expectedRevision<0)&&O("expectedRevision must be a non-negative integer");let e=te(t),r=new Date().toISOString(),i=this.openHandle(true);try{return i.db.transaction(o=>{let a=this.findThread(o,t.threadId,t.workspaceId);a||bt(`Thread ${t.threadId} not found`);let d=o.select().from(E).where(and(eq(E.id,t.highlightId),eq(E.thread_id,a.id))).limit(1).get();if(d||bt(`Highlight ${t.highlightId} not found`),d.revision!==t.expectedRevision)throw new jt(a.id,d.id,t.expectedRevision,d.revision);if(d.status==="dismissed")return d;let c=d.revision+1;o.update(E).set({status:"dismissed",text:null,revision:c,updated_at:r,dismissed_at:r}).where(and(eq(E.id,d.id),eq(E.revision,d.revision))).run();let l=o.select().from(E).where(eq(E.id,d.id)).get();if(!l)throw new _("DB_ERROR","Highlight dismissal did not return a row");let u=ee(o,a.id)+1;return ne(o,a.id)||(re(o,a,e,r,u),u+=1),Ie(o,l,e,r,"thread.highlight.deleted",u,d),l},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to dismiss thread highlight",o)}finally{i.close();}}listActiveHighlights(t,e,r={}){if($(t,"threadId"),$(e,"workspaceId"),r.taskId!==void 0&&$(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&$(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&$(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,t,e))return null;let a=i.db.select().from(E).where(and(eq(E.thread_id,t),eq(E.status,"active"))).orderBy(asc(E.created_at),asc(E.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return a;let d=i.db.all(sql`
359
359
  SELECT id, started_at FROM tasks WHERE thread_id = ${t}
360
360
  ORDER BY started_at ASC, id ASC
361
- `),c=new Map(d.map((g,f)=>[g.id,f])),l=r.taskId===void 0?void 0:c.get(r.taskId),u=r.coversFromTaskId===void 0?void 0:c.get(r.coversFromTaskId),h=r.coversToTaskId===void 0?void 0:c.get(r.coversToTaskId);return a.filter(g=>{let f=c.get(g.covers_from_task_id),A=c.get(g.covers_to_task_id);if(f===void 0||A===void 0)return !1;let N=Math.min(f,A),I=Math.max(f,A);return !(l!==void 0&&(l<N||l>I)||u!==void 0&&I<u||h!==void 0&&N>h)})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to list active thread highlights",o)}finally{i.close();}}listHighlights(t,e,r){return this.listActiveHighlights(t,e,r)}getActiveHighlights(t,e,r){return this.listActiveHighlights(t,e,r)}};function ks(n){return n.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
361
+ `),c=new Map(d.map((g,f)=>[g.id,f])),l=r.taskId===void 0?void 0:c.get(r.taskId),u=r.coversFromTaskId===void 0?void 0:c.get(r.coversFromTaskId),h=r.coversToTaskId===void 0?void 0:c.get(r.coversToTaskId);return a.filter(g=>{let f=c.get(g.covers_from_task_id),b=c.get(g.covers_to_task_id);if(f===void 0||b===void 0)return !1;let N=Math.min(f,b),I=Math.max(f,b);return !(l!==void 0&&(l<N||l>I)||u!==void 0&&I<u||h!==void 0&&N>h)})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to list active thread highlights",o)}finally{i.close();}}listHighlights(t,e,r){return this.listActiveHighlights(t,e,r)}getActiveHighlights(t,e,r){return this.listActiveHighlights(t,e,r)}};function Ss(n){return n.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
362
362
  `).filter(i=>!(i.startsWith("Loaded ")&&i.includes("layouts from")||i.includes("[dotenv@")||i.includes("[Nest]")&&i.includes("DEBUG")||i.startsWith("Registered custom layout:")||i.startsWith("Updated custom layout:"))).join(`
363
- `).trim()}function Ts(n){if(!n)return "";let t=n;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(r=>r?.type==="text"&&r?.text).map(r=>r.text).join(`
364
- `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=ks(t);}return t}var oe=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Zt({dbPath:this.dbPath})}getThreadHistoryRepo(){return new ie({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,r){let i=this.getThreadRepo(),o=i.findThreadById(t);if(o){if(o.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${o.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return i.ensureThread(t,e,r),{created:true}}async fetchHistory(t,e){let r=e?.limit??100,i=this.getThreadRepo(),o=i.findThreadById(t),a=i.findTopLevelTasks(t,void 0,r),d=new Set(["queued","cancelled"]);a=a.filter(h=>(!h.status||!d.has(h.status))&&(!e?.currentTraceId||h.trace_id!==e.currentTraceId));let c=o?.platform??"cli",l=this.rowsToMessages(a),u=this.readActiveHighlights(t,o?.workspace_id??null);return {threadId:t,platform:c,messages:l,...u?{highlights:u}:{},metadata:{title:o?.title??void 0,firstMessage:o?.first_message??void 0,lastMessage:o?.last_message??void 0,messageCount:o?.message_count??0,updatedAt:o?.updated_at?new Date(o.updated_at).getTime():void 0}}}async fetchHighlights(t){let e=this.getThreadRepo().findThreadById(t);return this.readActiveHighlights(t,e?.workspace_id??null)}async saveUserMessage(t,e,r,i){let{firstMessage:o}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:o}}async saveAssistantMessage(t,e,r,i){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}close(){}normalizeStatus(t){if(t&&!["success","completed","done"].includes(t)){if(["failed","error"].includes(t))return "failed";if(t==="running")return "running"}}readActiveHighlights(t,e){if(!e)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(t,e)??[]).filter(i=>typeof i.text=="string"&&i.text.length>0).map(i=>({id:i.id,text:i.text,kind:i.kind,source:i.source,coversFromTaskId:i.covers_from_task_id,coversToTaskId:i.covers_to_task_id,createdAt:i.created_at}))}catch{return}}rowsToMessages(t){let e=[];for(let r of t){r.prompt&&e.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let i=Ts(r.result),o=this.normalizeStatus(r.status);if(i||o==="running"||o==="failed"){let a={agent_id:r.agent_id,task_id:r.id};o&&(a.status=o),o==="failed"&&r.error&&(a.reason=r.error.split(`
365
- `)[0].slice(0,200)),e.push({id:`${r.id}-assistant`,text:i,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:a});}}return e}};var Ae=class extends ht{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new oe(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,r,i){}async afterAssistantMessage(t,e,r){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let r=e.platform??"cli";try{let i=await this._provider.ensureThread(e.threadId,r,e.workspaceId),o=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,o.id,i.created||o.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let r=e.metadata?.threadId;if(!r)return;let i=e.agentRef?.replace(/^@/,"")??"";try{let{id:o}=await this._provider.saveAssistantMessage(r,e.result,i);await this.afterAssistantMessage(r,o,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{Ae as ConversationPlugin,de as FileLoggerPlugin,we as SqliteTracingPlugin};
363
+ `).trim()}function Rs(n){if(!n)return "";let t=n;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(r=>r?.type==="text"&&r?.text).map(r=>r.text).join(`
364
+ `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=Ss(t);}return t}var oe=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Zt({dbPath:this.dbPath})}getThreadHistoryRepo(){return new ie({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,r){let i=this.getThreadRepo(),o=i.findThreadById(t);if(o){if(o.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${o.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return i.ensureThread(t,e,r),{created:true}}async fetchHistory(t,e){let r=e?.limit??100,i=this.getThreadRepo(),o=i.findThreadById(t),a=i.findTopLevelTasks(t,void 0,r),d=new Set(["queued","cancelled"]);a=a.filter(h=>(!h.status||!d.has(h.status))&&(!e?.currentTraceId||h.trace_id!==e.currentTraceId));let c=o?.platform??"cli",l=this.rowsToMessages(a),u=this.readActiveHighlights(t,o?.workspace_id??null);return {threadId:t,platform:c,messages:l,...u?{highlights:u}:{},metadata:{title:o?.title??void 0,firstMessage:o?.first_message??void 0,lastMessage:o?.last_message??void 0,messageCount:o?.message_count??0,updatedAt:o?.updated_at?new Date(o.updated_at).getTime():void 0}}}async fetchHighlights(t){let e=this.getThreadRepo().findThreadById(t);return this.readActiveHighlights(t,e?.workspace_id??null)}async saveUserMessage(t,e,r,i){let{firstMessage:o}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:o}}async saveAssistantMessage(t,e,r,i){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}close(){}normalizeStatus(t){if(t&&!["success","completed","done"].includes(t)){if(["failed","error"].includes(t))return "failed";if(t==="running")return "running"}}readActiveHighlights(t,e){if(!e)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(t,e)??[]).filter(i=>typeof i.text=="string"&&i.text.length>0).map(i=>({id:i.id,text:i.text,kind:i.kind,source:i.source,coversFromTaskId:i.covers_from_task_id,coversToTaskId:i.covers_to_task_id,createdAt:i.created_at}))}catch{return}}rowsToMessages(t){let e=[];for(let r of t){r.prompt&&e.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let i=Rs(r.result),o=this.normalizeStatus(r.status);if(i||o==="running"||o==="failed"){let a={agent_id:r.agent_id,task_id:r.id};o&&(a.status=o),o==="failed"&&r.error&&(a.reason=r.error.split(`
365
+ `)[0].slice(0,200)),e.push({id:`${r.id}-assistant`,text:i,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:a});}}return e}};var be=class extends ht{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new oe(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,r,i){}async afterAssistantMessage(t,e,r){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let r=e.platform??"cli";try{let i=await this._provider.ensureThread(e.threadId,r,e.workspaceId),o=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,o.id,i.created||o.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let r=e.metadata?.threadId;if(!r)return;let i=e.agentRef?.replace(/^@/,"")??"";try{let{id:o}=await this._provider.saveAssistantMessage(r,e.result,i);await this.afterAssistantMessage(r,o,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{be as ConversationPlugin,de as FileLoggerPlugin,we as SqliteTracingPlugin};