@crewx/sdk 0.8.9-rc.0 → 0.8.9-rc.2

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 M from'path';import M__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import Ut,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,or,isNull,like,asc,inArray,gte,lt}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique}from'drizzle-orm/sqlite-core';var j=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var Dt=()=>fileURLToPath(import.meta.url),Ot=()=>M__default.dirname(Dt()),k=Ot();var v=class{detach(t){}};function ut(d){let t=e=>String(e).padStart(2,"0");return `${d.getFullYear()}${t(d.getMonth()+1)}${t(d.getDate())}T${t(d.getHours())}${t(d.getMinutes())}${t(d.getSeconds())}`}var st=class extends v{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 s=ut(e.timestamp),n=join(this.logsDir,`${s}_${e.traceId}.log`);this.logFiles.set(e.traceId,n);let r=`=== TASK LOG: ${e.traceId} ===
1
+ import*as N from'path';import N__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import Mt,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,or,isNull,like,asc,inArray,gte,lt}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique}from'drizzle-orm/sqlite-core';var H=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var xt=()=>fileURLToPath(import.meta.url),Ct=()=>N__default.dirname(xt()),g=Ct();var v=class{detach(t){}};function at(d){let t=e=>String(e).padStart(2,"0");return `${d.getFullYear()}${t(d.getMonth()+1)}${t(d.getDate())}T${t(d.getHours())}${t(d.getMinutes())}${t(d.getSeconds())}`}var Z=class extends v{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 s=at(e.timestamp),n=join(this.logsDir,`${s}_${e.traceId}.log`);this.logFiles.set(e.traceId,n);let r=`=== TASK LOG: ${e.traceId} ===
2
2
  CrewX Version: ${this.version}
3
3
  Mode: ${e.mode}
4
4
  Agent: ${e.agentRef}
@@ -6,13 +6,13 @@ Started: ${e.timestamp.toLocaleString()}
6
6
  Message: ${e.message}
7
7
 
8
8
  `;writeFileSync(n,r,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toISOString();appendFileSync(s,`[${n}] STDOUT: ${e.output}
9
- `,"utf8");}catch{}}),t.on("task:end",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toLocaleString(),r=e.error?`failed: ${e.error.message}`:"completed successfully",i=`[${n}] INFO: Task ${r} in ${e.durationMs}ms
9
+ `,"utf8");}catch{}}),t.on("task:end",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toLocaleString(),r=e.error?`failed: ${e.error.message}`:"completed successfully",o=`[${n}] INFO: Task ${r} in ${e.durationMs}ms
10
10
  [${n}] INFO: Process closed with exit code: ${e.error?1:0}
11
- `;appendFileSync(s,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Lt(d){let t=M.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function ft(d){let t=Lt(d);return createHash("sha256").update(t).digest("hex")}var B=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ut.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())}};function b(d){let t=j("better-sqlite3"),{drizzle:e}=j("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),{db:e(s),runRaw:(n,r=[])=>s.prepare(n).run(...r),close:()=>s.close()}}var gt=new Set,Ft={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"};function Bt(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function zt(d,t){if(t>0||!Bt(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),s=new Set(e.map(n=>n.name));for(let[n,r]of Object.entries(Ft))s.has(n)||d.run(`ALTER TABLE tasks ADD COLUMN ${n} ${r}`);}function qt(d,t,e){let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(i=>i.hash)),r=JSON.parse(readFileSync(M__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let a=M__default.join(t,`${i.tag}.sql`);if(!existsSync(a))continue;let c=readFileSync(a,"utf-8"),p=createHash("sha256").update(c).digest("hex");if(n.has(p))continue;let m=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],T;for(;(T=m.exec(c))!==null;)f.push({table:T[1],column:T[2]});if(f.length===0||!c.split(/-->\s*statement-breakpoint/).map(L=>L.trim()).filter(Boolean).every(L=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(L)))continue;f.every(({table:L,column:et})=>d.all(`PRAGMA table_info("${L}")`).some(Rt=>Rt.name===et))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${i.when})`);}}function Ht(d){let{migrate:t}=j("drizzle-orm/better-sqlite3/migrator"),{sql:e}=j("drizzle-orm"),s=[M__default.join(k,"../migrations"),M__default.join(k,"migrations"),M__default.join(k,"../../../../drizzle/migrations"),M__default.join(process.cwd(),"drizzle/migrations")],n=s.find(p=>existsSync(M__default.join(p,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
11
+ `;appendFileSync(s,o,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Pt(d){let t=N.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function ut(d){let t=Pt(d);return createHash("sha256").update(t).digest("hex")}var U=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Mt.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())}};function y(d){let t=H("better-sqlite3"),{drizzle:e}=H("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),{db:e(s),runRaw:(n,r=[])=>s.prepare(n).run(...r),close:()=>s.close()}}var _t=new Set,It={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"};function Ut(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Ft(d,t){if(t>0||!Ut(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),s=new Set(e.map(n=>n.name));for(let[n,r]of Object.entries(It))s.has(n)||d.run(`ALTER TABLE tasks ADD COLUMN ${n} ${r}`);}function Bt(d,t,e){let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(o=>o.hash)),r=JSON.parse(readFileSync(N__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let i=N__default.join(t,`${o.tag}.sql`);if(!existsSync(i))continue;let c=readFileSync(i,"utf-8"),p=createHash("sha256").update(c).digest("hex");if(n.has(p))continue;let _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,k=[],b;for(;(b=_.exec(c))!==null;)k.push({table:b[1],column:b[2]});if(k.length===0||!c.split(/-->\s*statement-breakpoint/).map(z=>z.trim()).filter(Boolean).every(z=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(z)))continue;k.every(({table:z,column:Et})=>d.all(`PRAGMA table_info("${z}")`).some(Tt=>Tt.name===Et))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${o.when})`);}}function qt(d){let{migrate:t}=H("drizzle-orm/better-sqlite3/migrator"),{sql:e}=H("drizzle-orm"),s=[N__default.join(g,"../migrations"),N__default.join(g,"migrations"),N__default.join(g,"../../../../drizzle/migrations"),N__default.join(process.cwd(),"drizzle/migrations")],n=s.find(p=>existsSync(N__default.join(p,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
12
12
  ${s.join(`
13
- `)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),zt(d,i),r?.cnt&&qt(d,n,e),t(d,{migrationsFolder:n});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${c} migration${c>1?"s":""} applied).`);}}function W(d,t){gt.has(t)||(Ht(d),gt.add(t));}var u=class extends Error{code;cause;constructor(t,e,s){super(e),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var z=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 o=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"),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)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var l=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>z.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)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var Vt=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Vt.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")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.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()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>l.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()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.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")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));var V=class extends B{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 n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new u("NOT_FOUND","Database not found");let s=b(e);if(t)try{W(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({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,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}).onConflictDoNothing().run();}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
13
+ `)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;r?.cnt&&(o=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ft(d,o),r?.cnt&&Bt(d,n,e),t(d,{migrationsFolder:n});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(c>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${c} migration${c>1?"s":""} applied).`);}}function j(d,t){_t.has(t)||(qt(d),_t.add(t));}var u=class extends Error{code;cause;constructor(t,e,s){super(e),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var F=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 a=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"),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)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var l=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>F.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)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var Jt=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Jt.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")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>l.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()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.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")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));var K=class extends U{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 n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new u("NOT_FOUND","Database not found");let s=y(e);if(t)try{j(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(a).values({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,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}).onConflictDoNothing().run();}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
14
14
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
15
- model=COALESCE(?, model) WHERE id=?`,[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]);}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),n.update(o).set({logs:JSON.stringify(i)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new u("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(o).orderBy(desc(o.started_at)).limit(100).all()}catch(e){throw new u("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(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new u("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(eq(o.status,"running")).all(),s=0;for(let n of e){if(!n.pid)continue;let r=!1;try{process.kill(n.pid,0),r=!0;}catch{}r||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,n.id),eq(o.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let i=e?eq(o.workspace_id,e):void 0,a=i?and(eq(o.id,t),i):eq(o.id,t),c=r.db.select().from(o).where(a).limit(1).get()??void 0;if(!c){let p=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),m=i?and(p,i):p;c=r.db.select().from(o).where(m).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new u("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let a=b(i);try{let c=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),p=a.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let m of p)n.has(m.id)||(n.add(m.id),r.push(m));}catch(c){throw new u("DB_ERROR","Failed to find child tasks",c)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
15
+ model=COALESCE(?, model) WHERE id=?`,[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]);}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:a.logs}).from(a).where(eq(a.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),n.update(a).set({logs:JSON.stringify(o)}).where(eq(a.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(a).where(eq(a.status,"running")).orderBy(desc(a.started_at)).all()}catch(e){throw new u("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(a).orderBy(desc(a.started_at)).limit(100).all()}catch(e){throw new u("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(a).where(eq(a.id,t)).limit(1).get()??void 0}catch(s){throw new u("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:a.id,status:a.status,pid:a.pid}).from(a).where(eq(a.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(a).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(a.id,t),eq(a.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:a.id,pid:a.pid}).from(a).where(eq(a.status,"running")).all(),s=0;for(let n of e){if(!n.pid)continue;let r=!1;try{process.kill(n.pid,0),r=!0;}catch{}r||(t.db.update(a).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(a.id,n.id),eq(a.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=y(n);try{let o=e?eq(a.workspace_id,e):void 0,i=o?and(eq(a.id,t),o):eq(a.id,t),c=r.db.select().from(a).where(i).limit(1).get()??void 0;if(!c){let p=or(eq(a.thread_id,t),and(isNull(a.thread_id),like(a.command,`%--thread=${t}%`))),_=o?and(p,o):p;c=r.db.select().from(a).where(_).orderBy(desc(a.started_at)).limit(1).get()??void 0;}if(c)return c}catch(o){throw new u("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let c=e?and(eq(a.parent_task_id,t),eq(a.workspace_id,e)):eq(a.parent_task_id,t),p=i.db.select().from(a).where(c).orderBy(asc(a.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(c){throw new u("DB_ERROR","Failed to find child tasks",c)}finally{i.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
16
16
  SELECT
17
17
  COALESCE(workspace_id, 'unknown') AS workspace_id,
18
18
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -33,7 +33,7 @@ ${s.join(`
33
33
  FROM tasks
34
34
  GROUP BY workspace_id
35
35
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
36
- `)}catch(s){throw new u("DB_ERROR","Failed to get workspace usage summary",s)}finally{e.close();}}getThreadTokenUsage(t,e){let s=this.resolveDbPaths(),n=new Set,r=0,i=0,a=0;for(let c of s){if(!existsSync(c))continue;let p=b(c);try{let m=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),f=e?and(m,eq(o.workspace_id,e)):m,T=p.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(f).all();for(let A of T)n.has(A.id)||(n.add(A.id),r+=A.input_tokens??0,i+=A.output_tokens??0,a+=A.cost_usd??0);}catch(m){throw new u("DB_ERROR","Failed to get thread token usage",m)}finally{p.close();}}return {inputTokens:r,outputTokens:i,costUsd:a}}findTasksByThread(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let a=b(i);try{let c=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),p=e?and(c,eq(o.workspace_id,e)):c,m=a.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let f of m)n.has(f.id)||(n.add(f.id),r.push(f));}catch(c){throw new u("DB_ERROR","Failed to find tasks by thread",c)}finally{a.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(o.workspace_id,t.workspaceId));let n=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;n&&s.push(inArray(o.agent_id,n));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&s.push(inArray(o.status,r));let i=t.q??t.search;i&&s.push(like(o.prompt,`%${i}%`)),t.from&&s.push(gte(o.started_at,t.from)),t.to&&s.push(lt(o.started_at,t.to));let a=s.length>0?and(...s):void 0,c=e.db.select({count:sql`count(*)`}).from(o).where(a).get(),p=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(a).orderBy(p).limit(t.limit).offset(t.offset).all(),total:c?.count??0}}catch(s){throw new u("DB_ERROR","Failed to find all tasks",s)}finally{e.close();}}getAgentUsage(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
36
+ `)}catch(s){throw new u("DB_ERROR","Failed to get workspace usage summary",s)}finally{e.close();}}getThreadTokenUsage(t,e){let s=this.resolveDbPaths(),n=new Set,r=0,o=0,i=0;for(let c of s){if(!existsSync(c))continue;let p=y(c);try{let _=or(eq(a.thread_id,t),and(isNull(a.thread_id),like(a.command,`%--thread=${t}%`))),k=e?and(_,eq(a.workspace_id,e)):_,b=p.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(k).all();for(let A of b)n.has(A.id)||(n.add(A.id),r+=A.input_tokens??0,o+=A.output_tokens??0,i+=A.cost_usd??0);}catch(_){throw new u("DB_ERROR","Failed to get thread token usage",_)}finally{p.close();}}return {inputTokens:r,outputTokens:o,costUsd:i}}findTasksByThread(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let c=or(eq(a.thread_id,t),and(isNull(a.thread_id),like(a.command,`%--thread=${t}%`))),p=e?and(c,eq(a.workspace_id,e)):c,_=i.db.select().from(a).where(p).orderBy(asc(a.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(c){throw new u("DB_ERROR","Failed to find tasks by thread",c)}finally{i.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(a.workspace_id,t.workspaceId));let n=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;n&&s.push(inArray(a.agent_id,n));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&s.push(inArray(a.status,r));let o=t.q??t.search;o&&s.push(like(a.prompt,`%${o}%`)),t.from&&s.push(gte(a.started_at,t.from)),t.to&&s.push(lt(a.started_at,t.to));let i=s.length>0?and(...s):void 0,c=e.db.select({count:sql`count(*)`}).from(a).where(i).get(),p=(t.sortDir??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at);return {rows:e.db.select().from(a).where(i).orderBy(p).limit(t.limit).offset(t.offset).all(),total:c?.count??0}}catch(s){throw new u("DB_ERROR","Failed to find all tasks",s)}finally{e.close();}}getAgentUsage(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
37
37
  SELECT
38
38
  t.agent_id,
39
39
  t.workspace_id,
@@ -64,7 +64,7 @@ ${s.join(`
64
64
  AND t.started_at < ${e}
65
65
  GROUP BY t.agent_id, t.workspace_id
66
66
  ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
67
- `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new u("DB_ERROR","Failed to get agent usage",r)}finally{n.close();}}getAgentUsageTrendRaw(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
67
+ `).map(o=>({agentId:o.agent_id,workspaceId:o.workspace_id??null,totalTasks:o.total_tasks,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new u("DB_ERROR","Failed to get agent usage",r)}finally{n.close();}}getAgentUsageTrendRaw(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
68
68
  SELECT
69
69
  date(t.started_at) AS date,
70
70
  t.agent_id,
@@ -93,13 +93,44 @@ ${s.join(`
93
93
  AND t.started_at < ${e}
94
94
  GROUP BY date(t.started_at), t.agent_id
95
95
  ORDER BY date(t.started_at) ASC
96
- `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new u("DB_ERROR","Failed to get agent usage trend",r)}finally{n.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(o).where(and(eq(o.id,t),eq(o.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new u("DB_ERROR","Failed to find task for stop",n)}finally{s.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString(),i=s?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,s)):and(eq(o.id,t),eq(o.status,"running"));n.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let a=b(i);try{let c=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),p=a.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let m of p)n.has(m.id)||(n.add(m.id),r.push(m));}catch(c){throw new u("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{a.close();}}return r}};var at=class extends v{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 V({dbPath:this.dbPath}),s=process.cwd(),r=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?ft(s):null,i=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let c=a.callerAgentId??null,p=a.parentTaskId??null,m=a.rootTraceId??a.traceId,f=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});e.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:i,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??r,callerAgentId:c,parentTaskId:p,traceId:m,metadata:f,threadId:a.threadId??null});}catch{}}),t.on("task:output",a=>{try{e.appendLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch{}}),t.on("task:end",a=>{try{e.finishTask({id:a.traceId,status:a.error?"failed":"success",result:a.result??null,error:a.error?JSON.stringify(a.error):null,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var Z=class extends B{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 n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new u("NOT_FOUND","Database not found");let s=b(e);if(t)try{W(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:z.id}).from(z).where(eq(z.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!existsSync(r))continue;let i=b(r);try{let a=t?eq(l.workspace_id,t):void 0,c=i.db.select().from(l).where(a).orderBy(desc(l.updated_at)).all();for(let p of c)s.has(p.id)||(s.add(p.id),n.push(p));}catch(a){throw new u("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let i=eq(l.id,t),a=e?and(i,eq(l.workspace_id,e)):i,c=r.db.select().from(l).where(a).limit(1).get()??void 0;if(c)return c}catch(i){throw new u("DB_ERROR","Failed to find thread by id",i)}finally{r.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let i=eq(l.id,t),a=e?and(i,eq(l.workspace_id,e)):i;if(r.db.select({id:l.id}).from(l).where(a).limit(1).get())return !0}catch(i){throw new u("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),n=0,r=0,i=0,a=0,c=0,p=new Set;for(let m of s){if(!existsSync(m))continue;let f=b(m);try{let T=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),A=e?and(T,eq(o.workspace_id,e)):T,N=f.db.select({cnt:sql`count(*)`,total_input:sql`COALESCE(SUM(input_tokens), 0)`,total_output:sql`COALESCE(SUM(output_tokens), 0)`,total_cached:sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:sql`COALESCE(SUM(cost_usd), 0)`}).from(o).where(A).get();N&&(n+=N.cnt,r+=N.total_input,i+=N.total_output,a+=N.total_cached,c+=N.total_cost);let L=f.db.all(sql`
97
- SELECT DISTINCT agent_id FROM tasks
98
- WHERE thread_id = ${t}
99
- AND agent_id IS NOT NULL AND agent_id != ''
100
- AND (parent_task_id IS NULL OR parent_task_id = '')
101
- ${e?sql`AND workspace_id = ${e}`:sql``}
102
- `);for(let et of L)p.add(et.agent_id);}catch(T){throw new u("DB_ERROR","Failed to aggregate task stats",T)}finally{f.close();}}return {taskCount:n,inputTokens:r,outputTokens:i,cachedInputTokens:a,costUsd:c,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let a=b(i);try{let c=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),p=e?and(c,eq(o.workspace_id,e)):c,m=a.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let f of m)n.has(f.id)||(n.add(f.id),r.push(f));}catch(c){throw new u("DB_ERROR","Failed to find top-level tasks",c)}finally{a.close();}}return r}findAllTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let a=b(i);try{let c=eq(o.thread_id,t),p=e?and(c,eq(o.workspace_id,e)):c,m=a.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let f of m)n.has(f.id)||(n.add(f.id),r.push(f));}catch(c){throw new u("DB_ERROR","Failed to find all tasks for thread",c)}finally{a.close();}}return r}findTaskById(t,e,s){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let i=b(r);try{let a=and(eq(o.id,e),eq(o.thread_id,t)),c=s?and(a,eq(o.workspace_id,s)):a,p=i.db.select().from(o).where(c).limit(1).get();if(!p)continue;let m=i.db.select().from(o).where(eq(o.parent_task_id,p.id)).orderBy(asc(o.started_at)).all();return {task:p,children:m}}catch(a){throw new u("DB_ERROR","Failed to find task by id",a)}finally{i.close();}}}batchFetchTasks(t,e){let s=new Map;if(t.length===0)return s;let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let i=b(r);try{let a=and(inArray(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),c=e?and(a,eq(o.workspace_id,e)):a,p=i.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let m of p){let f=m.thread_id;s.has(f)||s.set(f,[]),s.get(f).push(m);}}catch(a){throw new u("DB_ERROR","Failed to batch fetch tasks",a)}finally{i.close();}}return s}updateThreadTitle(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=eq(l.id,t),i=s?and(r,eq(l.workspace_id,s)):r;if(!n.db.select({id:l.id}).from(l).where(i).limit(1).get())return;n.db.update(l).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(l.id,t)).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to update thread title",r)}finally{n.close();}}upsertThread(t,e){let s=this.openHandle(true);try{let n=e.workspaceId?this.validateWorkspaceId(s,e.workspaceId):null,r=new Date().toISOString();if(s.db.select({id:l.id,message_count:l.message_count}).from(l).where(eq(l.id,t)).limit(1).get()){let a={updated_at:r};e.title!==void 0&&(a.title=e.title),e.titleLocked!==void 0&&(a.title_locked=e.titleLocked?1:0),s.db.update(l).set(a).where(eq(l.id,t)).run();}else s.db.insert(l).values({id:t,platform:e.platform,workspace_id:n,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to upsert thread",n)}finally{s.close();}}ensureThread(t,e,s){let n=this.openHandle(true);try{let r=s?this.validateWorkspaceId(n,s):null,i=n.db.select({id:l.id,platform:l.platform,workspace_id:l.workspace_id}).from(l).where(eq(l.id,t)).limit(1).get();if(i){r&&!i.workspace_id&&n.db.update(l).set({workspace_id:r}).where(eq(l.id,t)).run();return}let a=new Date().toISOString();n.db.insert(l).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:a,updated_at:a}).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to ensure thread",r)}finally{n.close();}}saveUserMessage(t,e,s){if(!this.dbExists())return {firstMessage:false};let n=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:n.db.transaction(a=>{let p=a.select({message_count:l.message_count}).from(l).where(eq(l.id,t)).limit(1).get()?.message_count===0;return a.run(sql`
96
+ `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new u("DB_ERROR","Failed to get agent usage trend",r)}finally{n.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(a).where(and(eq(a.id,t),eq(a.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new u("DB_ERROR","Failed to find task for stop",n)}finally{s.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString(),o=s?and(eq(a.id,t),eq(a.status,"running"),eq(a.workspace_id,s)):and(eq(a.id,t),eq(a.status,"running"));n.db.update(a).set({status:"failed",error:e,completed_at:r}).where(o).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let c=e?and(like(a.prompt,`%${t}%`),eq(a.workspace_id,e)):like(a.prompt,`%${t}%`),p=i.db.select().from(a).where(c).orderBy(asc(a.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(c){throw new u("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{i.close();}}return r}};var rt=class extends v{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 K({dbPath:this.dbPath}),s=process.cwd(),r=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?ut(s):null,o=process.argv.join(" ");this.unsubs.push(t.on("task:start",i=>{try{let c=i.callerAgentId??null,p=i.parentTaskId??null,_=i.rootTraceId??i.traceId,k=i.metadata?JSON.stringify(i.metadata):JSON.stringify({provider:i.provider??"cli/claude"});e.startTask({id:i.traceId,agentId:i.agentRef.replace(/^@/,""),prompt:i.message,mode:i.mode,status:"running",pid:i.pid??null,startedAt:i.timestamp.toISOString(),crewxVersion:this.version,platform:i.platform??"cli",model:i.model??null,renderedPrompt:i.renderedPrompt??null,command:o,codingAgentCommand:i.codingAgentCommand??null,workspaceId:i.workspaceId??r,callerAgentId:c,parentTaskId:p,traceId:_,metadata:k,threadId:i.threadId??null});}catch{}}),t.on("task:output",i=>{try{e.appendLog(i.traceId,{timestamp:i.timestamp.toISOString(),level:i.level??"stdout",message:i.output});}catch{}}),t.on("task:end",i=>{try{e.finishTask({id:i.traceId,status:i.error?"failed":"success",result:i.result??null,error:i.error?JSON.stringify(i.error):null,completedAt:i.timestamp.toISOString(),durationMs:i.durationMs,exitCode:i.exitCode??null,inputTokens:i.inputTokens??0,outputTokens:i.outputTokens??0,cachedInputTokens:i.cachedInputTokens??0,costUsd:i.costUsd??0,model:i.model??null});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var V=class extends U{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 n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new u("NOT_FOUND","Database not found");let s=y(e);if(t)try{j(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:F.id}).from(F).where(eq(F.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
97
+ ${t}.parent_task_id IS NULL
98
+ OR ${t}.parent_task_id = ''
99
+ OR NOT EXISTS (
100
+ SELECT 1 FROM tasks parent
101
+ WHERE parent.id = ${t}.parent_task_id
102
+ AND parent.thread_id = ${t}.thread_id
103
+ )
104
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!existsSync(r))continue;let o=y(r);try{let i=t?eq(l.workspace_id,t):void 0,c=o.db.select().from(l).where(i).orderBy(desc(l.updated_at)).all();for(let p of c)s.has(p.id)||(s.add(p.id),n.push(p));}catch(i){throw new u("DB_ERROR","Failed to find all threads",i)}finally{o.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=y(n);try{let o=eq(l.id,t),i=e?and(o,eq(l.workspace_id,e)):o,c=r.db.select().from(l).where(i).limit(1).get()??void 0;if(c)return c}catch(o){throw new u("DB_ERROR","Failed to find thread by id",o)}finally{r.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=y(n);try{let o=eq(l.id,t),i=e?and(o,eq(l.workspace_id,e)):o;if(r.db.select({id:l.id}).from(l).where(i).limit(1).get())return !0}catch(o){throw new u("DB_ERROR","Failed to check thread existence",o)}finally{r.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),n=0,r=0,o=0,i=0,c=0,p=new Set;for(let _ of s){if(!existsSync(_))continue;let k=y(_);try{let b=k.db.get(sql`
105
+ SELECT
106
+ count(*) AS cnt,
107
+ COALESCE(SUM(child.input_tokens), 0) AS total_input,
108
+ COALESCE(SUM(child.output_tokens), 0) AS total_output,
109
+ COALESCE(SUM(child.cached_input_tokens), 0) AS total_cached,
110
+ COALESCE(SUM(child.cost_usd), 0) AS total_cost
111
+ FROM tasks child
112
+ WHERE child.thread_id = ${t}
113
+ AND ${this.topLevelTaskPredicateSql()}
114
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
115
+ `);b&&(n+=b.cnt,r+=b.total_input,o+=b.total_output,i+=b.total_cached,c+=b.total_cost);let A=k.db.all(sql`
116
+ SELECT DISTINCT child.agent_id FROM tasks child
117
+ WHERE child.thread_id = ${t}
118
+ AND child.agent_id IS NOT NULL AND child.agent_id != ''
119
+ AND ${this.topLevelTaskPredicateSql()}
120
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
121
+ `);for(let it of A)p.add(it.agent_id);}catch(b){throw new u("DB_ERROR","Failed to aggregate task stats",b)}finally{k.close();}}return {taskCount:n,inputTokens:r,outputTokens:o,cachedInputTokens:i,costUsd:c,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let c=i.db.all(sql`
122
+ SELECT child.* FROM tasks child
123
+ WHERE child.thread_id = ${t}
124
+ AND ${this.topLevelTaskPredicateSql()}
125
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
126
+ ORDER BY child.started_at ASC
127
+ `);for(let p of c)n.has(p.id)||(n.add(p.id),r.push(p));}catch(c){throw new u("DB_ERROR","Failed to find top-level tasks",c)}finally{i.close();}}return r}findAllTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let c=eq(a.thread_id,t),p=e?and(c,eq(a.workspace_id,e)):c,_=i.db.select().from(a).where(p).orderBy(asc(a.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(c){throw new u("DB_ERROR","Failed to find all tasks for thread",c)}finally{i.close();}}return r}findTaskById(t,e,s){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=and(eq(a.id,e),eq(a.thread_id,t)),c=s?and(i,eq(a.workspace_id,s)):i,p=o.db.select().from(a).where(c).limit(1).get();if(!p)continue;let _=o.db.select().from(a).where(eq(a.parent_task_id,p.id)).orderBy(asc(a.started_at)).all();return {task:p,children:_}}catch(i){throw new u("DB_ERROR","Failed to find task by id",i)}finally{o.close();}}}batchFetchTasks(t,e){let s=new Map;if(t.length===0)return s;let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=o.db.all(sql`
128
+ SELECT child.* FROM tasks child
129
+ WHERE child.thread_id IN (${sql.join(t.map(c=>sql`${c}`),sql`, `)})
130
+ AND ${this.topLevelTaskPredicateSql()}
131
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
132
+ ORDER BY child.started_at ASC
133
+ `);for(let c of i){let p=c.thread_id;s.has(p)||s.set(p,[]),s.get(p).push(c);}}catch(i){throw new u("DB_ERROR","Failed to batch fetch tasks",i)}finally{o.close();}}return s}updateThreadTitle(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=eq(l.id,t),o=s?and(r,eq(l.workspace_id,s)):r;if(!n.db.select({id:l.id}).from(l).where(o).limit(1).get())return;n.db.update(l).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(l.id,t)).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to update thread title",r)}finally{n.close();}}upsertThread(t,e){let s=this.openHandle(true);try{let n=e.workspaceId?this.validateWorkspaceId(s,e.workspaceId):null,r=new Date().toISOString();if(s.db.select({id:l.id,message_count:l.message_count}).from(l).where(eq(l.id,t)).limit(1).get()){let i={updated_at:r};e.title!==void 0&&(i.title=e.title),e.titleLocked!==void 0&&(i.title_locked=e.titleLocked?1:0),s.db.update(l).set(i).where(eq(l.id,t)).run();}else s.db.insert(l).values({id:t,platform:e.platform,workspace_id:n,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to upsert thread",n)}finally{s.close();}}ensureThread(t,e,s){let n=this.openHandle(true);try{let r=s?this.validateWorkspaceId(n,s):null,o=n.db.select({id:l.id,platform:l.platform,workspace_id:l.workspace_id}).from(l).where(eq(l.id,t)).limit(1).get();if(o){r&&!o.workspace_id&&n.db.update(l).set({workspace_id:r}).where(eq(l.id,t)).run();return}let i=new Date().toISOString();n.db.insert(l).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:i,updated_at:i}).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to ensure thread",r)}finally{n.close();}}saveUserMessage(t,e,s){if(!this.dbExists())return {firstMessage:false};let n=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:n.db.transaction(i=>{let p=i.select({message_count:l.message_count}).from(l).where(eq(l.id,t)).limit(1).get()?.message_count===0;return i.run(sql`
103
134
  UPDATE threads
104
135
  SET first_message = COALESCE(first_message, ${e}),
105
136
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -107,7 +138,7 @@ ${s.join(`
107
138
  message_count = message_count + 1,
108
139
  updated_at = ${r}
109
140
  WHERE id = ${t}
110
- `),p},{behavior:"immediate"})}}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to save user message",r)}finally{n.close();}}saveAssistantMessage(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString();n.db.update(l).set({last_message:e,updated_at:r}).where(eq(l.id,t)).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to save assistant message",r)}finally{n.close();}}updateThread(t,e){if(!this.dbExists())return;let s=this.openHandle(true);try{let n={updated_at:new Date().toISOString()};e.title!==void 0&&(n.title=e.title,n.title_locked=1),e.titleLocked!==void 0&&(n.title_locked=e.titleLocked?1:0),s.db.update(l).set(n).where(eq(l.id,t)).run();}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to update thread",n)}finally{s.close();}}togglePin(t,e){let s=this.openHandle(true);try{let n=e?and(eq(l.id,t),eq(l.workspace_id,e)):eq(l.id,t),r=s.db.select({pinned:l.pinned,metadata:l.metadata}).from(l).where(n).get();if(!r)return null;let i=r.pinned?0:1,a=r.metadata?JSON.parse(r.metadata):{};if(i){let c=e?and(eq(l.pinned,1),eq(l.workspace_id,e)):eq(l.pinned,1),p=s.db.select({metadata:l.metadata}).from(l).where(c).all(),m=0;for(let f of p){let T=f.metadata?JSON.parse(f.metadata):{};typeof T.pinOrder=="number"&&T.pinOrder>m&&(m=T.pinOrder);}a.pinOrder=m+1;}else delete a.pinOrder;return s.db.update(l).set({pinned:i,metadata:Object.keys(a).length>0?JSON.stringify(a):null}).where(n).run(),{pinned:!!i}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to toggle pin",n)}finally{s.close();}}reorderPins(t,e){let s=this.openHandle(true);try{for(let n=0;n<t.length;n++){let r=e?and(eq(l.id,t[n]),eq(l.workspace_id,e)):eq(l.id,t[n]),i=s.db.select({metadata:l.metadata}).from(l).where(r).get();if(!i)continue;let a=i.metadata?JSON.parse(i.metadata):{};a.pinOrder=n+1,s.db.update(l).set({metadata:JSON.stringify(a)}).where(r).run();}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to reorder pins",n)}finally{s.close();}}toggleStar(t,e){let s=this.openHandle(true);try{let n=e?and(eq(l.id,t),eq(l.workspace_id,e)):eq(l.id,t),r=s.db.select({starred:l.starred}).from(l).where(n).get();if(!r)return null;let i=r.starred?0:1;return s.db.update(l).set({starred:i}).where(n).run(),{starred:!!i}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to toggle star",n)}finally{s.close();}}};function ge(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
141
+ `),p},{behavior:"immediate"})}}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to save user message",r)}finally{n.close();}}saveAssistantMessage(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString();n.db.update(l).set({last_message:e,updated_at:r}).where(eq(l.id,t)).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to save assistant message",r)}finally{n.close();}}updateThread(t,e){if(!this.dbExists())return;let s=this.openHandle(true);try{let n={updated_at:new Date().toISOString()};e.title!==void 0&&(n.title=e.title,n.title_locked=1),e.titleLocked!==void 0&&(n.title_locked=e.titleLocked?1:0),s.db.update(l).set(n).where(eq(l.id,t)).run();}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to update thread",n)}finally{s.close();}}togglePin(t,e){let s=this.openHandle(true);try{let n=e?and(eq(l.id,t),eq(l.workspace_id,e)):eq(l.id,t),r=s.db.select({pinned:l.pinned,metadata:l.metadata}).from(l).where(n).get();if(!r)return null;let o=r.pinned?0:1,i=r.metadata?JSON.parse(r.metadata):{};if(o){let c=e?and(eq(l.pinned,1),eq(l.workspace_id,e)):eq(l.pinned,1),p=s.db.select({metadata:l.metadata}).from(l).where(c).all(),_=0;for(let k of p){let b=k.metadata?JSON.parse(k.metadata):{};typeof b.pinOrder=="number"&&b.pinOrder>_&&(_=b.pinOrder);}i.pinOrder=_+1;}else delete i.pinOrder;return s.db.update(l).set({pinned:o,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(n).run(),{pinned:!!o}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to toggle pin",n)}finally{s.close();}}reorderPins(t,e){let s=this.openHandle(true);try{for(let n=0;n<t.length;n++){let r=e?and(eq(l.id,t[n]),eq(l.workspace_id,e)):eq(l.id,t[n]),o=s.db.select({metadata:l.metadata}).from(l).where(r).get();if(!o)continue;let i=o.metadata?JSON.parse(o.metadata):{};i.pinOrder=n+1,s.db.update(l).set({metadata:JSON.stringify(i)}).where(r).run();}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to reorder pins",n)}finally{s.close();}}toggleStar(t,e){let s=this.openHandle(true);try{let n=e?and(eq(l.id,t),eq(l.workspace_id,e)):eq(l.id,t),r=s.db.select({starred:l.starred}).from(l).where(n).get();if(!r)return null;let o=r.starred?0:1;return s.db.update(l).set({starred:o}).where(n).run(),{starred:!!o}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to toggle star",n)}finally{s.close();}}};function he(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
111
142
  `).filter(n=>!(n.startsWith("Loaded ")&&n.includes("layouts from")||n.includes("[dotenv@")||n.includes("[Nest]")&&n.includes("DEBUG")||n.startsWith("Registered custom layout:")||n.startsWith("Updated custom layout:"))).join(`
112
- `).trim()}function ke(d){if(!d)return "";let t=d;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
113
- `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=ge(t);}return t}var tt=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Z({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let n=this.getThreadRepo(),r=n.findThreadById(t);if(r){if(r.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${r.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return n.ensureThread(t,e,s),{created:true}}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),i=n.findTopLevelTasks(t),a=new Set(["done","completed","success"]);i=i.filter(m=>(!m.status||a.has(m.status))&&(!e?.currentTraceId||m.trace_id!==e.currentTraceId)),i=i.slice(0,s);let c=r?.platform??"cli",p=this.rowsToMessages(i);return {threadId:t,platform:c,messages:p,metadata:{title:r?.title??void 0,firstMessage:r?.first_message??void 0,lastMessage:r?.last_message??void 0,messageCount:r?.message_count??0,updatedAt:r?.updated_at?new Date(r.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,n){let{firstMessage:r}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:r}}async saveAssistantMessage(t,e,s,n){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}close(){}rowsToMessages(t){let e=[];for(let s of t){s.prompt&&e.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime()});let n=ke(s.result);n&&e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:{agent_id:s.agent_id,task_id:s.id}});}return e}};var ct=class extends v{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new tt(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,s,n){}async afterAssistantMessage(t,e,s){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{let n=await this._provider.ensureThread(e.threadId,s,e.workspaceId),r=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,r.id,n.created||r.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let n=e.agentRef?.replace(/^@/,"")??"";try{let{id:r}=await this._provider.saveAssistantMessage(s,e.result,n);await this.afterAssistantMessage(s,r,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{ct as ConversationPlugin,st as FileLoggerPlugin,at as SqliteTracingPlugin};
143
+ `).trim()}function me(d){if(!d)return "";let t=d;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
144
+ `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=he(t);}return t}var Q=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new V({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let n=this.getThreadRepo(),r=n.findThreadById(t);if(r){if(r.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${r.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return n.ensureThread(t,e,s),{created:true}}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),o=n.findTopLevelTasks(t),i=new Set(["done","completed","success"]);o=o.filter(_=>(!_.status||i.has(_.status))&&(!e?.currentTraceId||_.trace_id!==e.currentTraceId)),o=o.slice(0,s);let c=r?.platform??"cli",p=this.rowsToMessages(o);return {threadId:t,platform:c,messages:p,metadata:{title:r?.title??void 0,firstMessage:r?.first_message??void 0,lastMessage:r?.last_message??void 0,messageCount:r?.message_count??0,updatedAt:r?.updated_at?new Date(r.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,n){let{firstMessage:r}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:r}}async saveAssistantMessage(t,e,s,n){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}close(){}rowsToMessages(t){let e=[];for(let s of t){s.prompt&&e.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime()});let n=me(s.result);n&&e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:{agent_id:s.agent_id,task_id:s.id}});}return e}};var ot=class extends v{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new Q(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,s,n){}async afterAssistantMessage(t,e,s){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{let n=await this._provider.ensureThread(e.threadId,s,e.workspaceId),r=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,r.id,n.created||r.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let n=e.agentRef?.replace(/^@/,"")??"";try{let{id:r}=await this._provider.saveAssistantMessage(s,e.result,n);await this.afterAssistantMessage(s,r,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{ot as ConversationPlugin,Z as FileLoggerPlugin,rt as SqliteTracingPlugin};
@@ -1,13 +1,13 @@
1
- import*as $ from'path';import $__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import qt,{existsSync,mkdirSync,readFileSync}from'fs';import te from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,getTableConfig}from'drizzle-orm/sqlite-core';var tt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var Jt=()=>fileURLToPath(import.meta.url),Vt=()=>$__default.dirname(Jt()),b=Vt();var E=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(te.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 d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=tt("better-sqlite3"),{drizzle:e}=tt("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(s,r=[])=>n.prepare(s).run(...r),close:()=>n.close()}}var Tt=new Set,ne={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"};function se(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function re(a,t){if(t>0||!se(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(s=>s.name));for(let[s,r]of Object.entries(ne))n.has(s)||a.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}function oe(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(readFileSync($__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=$__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),p=createHash("sha256").update(u).digest("hex");if(s.has(p))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],y;for(;(y=h.exec(u))!==null;)m.push({table:y[1],column:y[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(q=>q.trim()).filter(Boolean).every(q=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(q)))continue;m.every(({table:q,column:V})=>a.all(`PRAGMA table_info("${q}")`).some(ct=>ct.name===V))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${o.when})`);}}function Y(a){let{migrate:t}=tt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=tt("drizzle-orm"),n=[$__default.join(b,"../migrations"),$__default.join(b,"migrations"),$__default.join(b,"../../../../drizzle/migrations"),$__default.join(process.cwd(),"drizzle/migrations")],s=n.find(p=>existsSync($__default.join(p,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
1
+ import*as M from'path';import M__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Bt,{existsSync,mkdirSync,readFileSync}from'fs';import Qt from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,getTableConfig}from'drizzle-orm/sqlite-core';var Z=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var Gt=()=>fileURLToPath(import.meta.url),Kt=()=>M__default.dirname(Gt()),R=Kt();var E=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Qt.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 a=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function k(i){let t=Z("better-sqlite3"),{drizzle:e}=Z("drizzle-orm/better-sqlite3"),n=new t(i);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(s,r=[])=>n.prepare(s).run(...r),close:()=>n.close()}}var St=new Set,te={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"};function ee(i,t){return (i.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ne(i,t){if(t>0||!ee(i,"tasks"))return;let e=i.all("PRAGMA table_info(tasks)"),n=new Set(e.map(s=>s.name));for(let[s,r]of Object.entries(te))n.has(s)||i.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}function se(i,t,e){let n=i.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(readFileSync(M__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=M__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),p=createHash("sha256").update(u).digest("hex");if(s.has(p))continue;let f=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],w;for(;(w=f.exec(u))!==null;)m.push({table:w[1],column:w[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(H=>H.trim()).filter(Boolean).every(H=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(H)))continue;m.every(({table:H,column:dt})=>i.all(`PRAGMA table_info("${H}")`).some(lt=>lt.name===dt))&&i.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${o.when})`);}}function Y(i){let{migrate:t}=Z("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Z("drizzle-orm"),n=[M__default.join(R,"../migrations"),M__default.join(R,"migrations"),M__default.join(R,"../../../../drizzle/migrations"),M__default.join(process.cwd(),"drizzle/migrations")],s=n.find(p=>existsSync(M__default.join(p,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
3
- `)}`);let r=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;r?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),re(a,o),r?.cnt&&oe(a,s,e),t(a,{migrationsFolder:s});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${u} migration${u>1?"s":""} applied).`);}}function O(a,t){Tt.has(t)||(Y(a),Tt.add(t));}var f=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 i=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"),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)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var c=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>f.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)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id)}));var H=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>H.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")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var z=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.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()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var N=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>c.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()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var K=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")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));function pt(a){let t=$.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function vt(a){let t=pt(a);return createHash("sha256").update(t).digest("hex")}function rt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var _t=class extends E{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{Y(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=rt(basename(n)),o=`${rt(basename(dirname(n)))}-${s}`,l=[s,o];try{let u=p=>t.select({id:f.id}).from(f).where(and(eq(f.slug,p),ne$1(f.id,e))).limit(1).all().length>0;for(let p of l)if(!u(p))return p;for(let p=2;p<1e3;p+=1){let h=`${o}-${p}`;if(!u(h))return h}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:f.id,slug:f.slug}).from(f).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=rt(s.slug.replace(/\//g,"-"));t.db.update(f).set({slug:r,updated_at:new Date().toISOString()}).where(eq(f.id,s.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:s,name:r,workspacePath:o}=e,l=new Date().toISOString();t.insert(f).values({id:n,slug:s,name:r,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(f).set({workspace_path:o,updated_at:l}).where(and(eq(f.id,n),isNull(f.workspace_path))).run();}registerWorkspace(t){let e=pt(t),n=this.openHandle(true);try{let s=vt(e),r=basename(e),o=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:o,name:r,workspacePath:e}),{id:s,slug:o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to register workspace",s)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(f.is_active,t.isActive?1:0):void 0,s=e.db.select({count:sql`count(*)`}).from(f).where(n).get();return {rows:e.db.select().from(f).where(n).orderBy(desc(f.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(f).where(eq(f.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(s=>s.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let s=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
3
+ `)}`);let r=i.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;r?.cnt&&(o=i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ne(i,o),r?.cnt&&se(i,s,e),t(i,{migrationsFolder:s});let u=(i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${u} migration${u>1?"s":""} applied).`);}}function O(i,t){St.has(t)||(Y(i),St.add(t));}var h=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 d=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"),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)},i=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(i.agent_id),idx_tasks_status:index("idx_tasks_status").on(i.status),idx_tasks_started_at:index("idx_tasks_started_at").on(i.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(i.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(i.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(i.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(i.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(i.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(i.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(i.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(i.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(i.workspace_id,i.started_at)}));var c=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>h.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)},i=>({idx_threads_updated_at:index("idx_threads_updated_at").on(i.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(i.workspace_id)}));var q=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>d.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>q.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")},i=>({idx_spans_task_id:index("idx_spans_task_id").on(i.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(i.parent_span_id)}));var B=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>d.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()},i=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(i.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(i.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(i.timestamp)}));var P=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>c.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()},i=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(i.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(i.thread_id,i.seq),uniq_thread_boxes_thread_seq:unique().on(i.thread_id,i.seq)}));var G=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},i=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(i.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(i.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(i.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(i.partition_key)}));function ut(i){let t=M.resolve(i);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Nt(i){let t=ut(i);return createHash("sha256").update(t).digest("hex")}function st(i){return i.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var ft=class extends E{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{Y(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=st(basename(n)),o=`${st(basename(dirname(n)))}-${s}`,l=[s,o];try{let u=p=>t.select({id:h.id}).from(h).where(and(eq(h.slug,p),ne$1(h.id,e))).limit(1).all().length>0;for(let p of l)if(!u(p))return p;for(let p=2;p<1e3;p+=1){let f=`${o}-${p}`;if(!u(f))return f}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=st(s.slug.replace(/\//g,"-"));t.db.update(h).set({slug:r,updated_at:new Date().toISOString()}).where(eq(h.id,s.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:s,name:r,workspacePath:o}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:s,name:r,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:o,updated_at:l}).where(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(t){let e=ut(t),n=this.openHandle(true);try{let s=Nt(e),r=basename(e),o=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:o,name:r,workspacePath:e}),{id:s,slug:o}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to register workspace",s)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(h.is_active,t.isActive?1:0):void 0,s=e.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new a("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(s=>s.agent_id)}catch(n){throw new a("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let s=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
4
4
  (SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
5
5
  FROM threads t
6
6
  WHERE t.workspace_id = ${t}
7
7
  ORDER BY t.updated_at DESC
8
- LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new d("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(f).where(eq(f.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?and(eq(f.slug,t),ne$1(f.id,e)):eq(f.slug,t);return !!n.db.select({id:f.id}).from(f).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(f).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(f).where(eq(f.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(f).where(eq(f.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:f.id,workspace_path:f.workspace_path}).from(f).where(and(eq(f.is_active,1),isNotNull(f.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))||(t.db.update(f).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(f.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(f).where(eq(f.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Ht=[f,i,c,H,z,N,K];function Te(){return $__default.join(te.homedir(),".crewx","crewx.db")}function Oe(a){if(!qt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return qt.copyFileSync(a,e),e}function Mt(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Ce(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function Ae(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Ce(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Pe(a,t){let e=t?.dbPath??Te(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Oe(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Mt(a);if(!s)try{Y(a);}catch(m){let y=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!y.includes("duplicate column"))throw m}let l,u;s?(l=Ht.map(y=>getTableConfig(y).name).filter(y=>!o.has(y)),u=o):(u=Mt(a),l=[...u].filter(m=>!o.has(m)));let p=[],h=[];for(let m of Ht){let y=getTableConfig(m),S=y.name;if(!u.has(S))continue;let v=a.all(`PRAGMA table_info("${S}")`),q=new Set(v.map(B=>B.name)),V=new Set(y.columns.map(B=>B.name));for(let B of y.columns)if(!q.has(B.name)){if(!s){let ct=Ae(B);a.run(`ALTER TABLE "${S}" ADD COLUMN ${ct}`);}p.push({table:S,column:B.name});}for(let B of v)V.has(B.name)||h.push(`${S}.${B.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:h,backupPath:r}}var wt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({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,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}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new a("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?and(eq(h.slug,t),ne$1(h.id,e)):eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).where(s).limit(1).get()}catch(s){throw new a("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(h).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!l)throw new a("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof a?o:new a("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!r)throw new a("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(and(eq(h.is_active,1),isNotNull(h.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(h.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(eq(h.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var zt=[h,d,c,q,B,P,G];function xe(){return M__default.join(Qt.homedir(),".crewx","crewx.db")}function De(i){if(!Bt.existsSync(i))return null;let t=Math.floor(Date.now()/1e3),e=`${i}.bak-${t}`;return Bt.copyFileSync(i,e),e}function $t(i){let t=i.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Te(i){return i==null||typeof i=="object"&&"queryChunks"in i?null:typeof i=="number"?String(i):typeof i=="boolean"?i?"1":"0":typeof i=="string"?`'${i.replace(/'/g,"''")}'`:String(i)}function Oe(i){let t=i.getSQLType(),e=`"${i.name}" ${t}`,n=Te(i.default);return n!==null&&(e+=` DEFAULT ${n}`),i.notNull&&(e+=" NOT NULL"),e}function Ae(i,t){let e=t?.dbPath??xe(),n=t?.force??false,s=t?.dryRun??false,r=s?null:De(e);if(n&&!s)try{i.run("DELETE FROM __drizzle_migrations");}catch{}let o=$t(i);if(!s)try{Y(i);}catch(m){let w=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!w.includes("duplicate column"))throw m}let l,u;s?(l=zt.map(w=>getTableConfig(w).name).filter(w=>!o.has(w)),u=o):(u=$t(i),l=[...u].filter(m=>!o.has(m)));let p=[],f=[];for(let m of zt){let w=getTableConfig(m),D=w.name;if(!u.has(D))continue;let J=i.all(`PRAGMA table_info("${D}")`),H=new Set(J.map(v=>v.name)),dt=new Set(w.columns.map(v=>v.name));for(let v of w.columns)if(!H.has(v.name)){if(!s){let lt=Oe(v);i.run(`ALTER TABLE "${D}" ADD COLUMN ${lt}`);}p.push({table:D,column:v.name});}for(let v of J)dt.has(v.name)||f.push(`${D}.${v.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:f,backupPath:r}}var gt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(d).values({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,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}).onConflictDoNothing().run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
9
9
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
10
- model=COALESCE(?, model) WHERE id=?`,[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]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all()}catch(e){throw new d("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(i).orderBy(desc(i.started_at)).limit(100).all()}catch(e){throw new d("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(i).where(eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,t),eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(eq(i.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,s.id),eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=w(s);try{let o=e?eq(i.workspace_id,e):void 0,l=o?and(eq(i.id,t),o):eq(i.id,t),u=r.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let p=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),h=o?and(p,o):p;u=r.db.select().from(i).where(h).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=e?and(eq(i.parent_task_id,t),eq(i.workspace_id,e)):eq(i.parent_task_id,t),p=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of p)s.has(h.id)||(s.add(h.id),r.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
10
+ model=COALESCE(?, model) WHERE id=?`,[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]);}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:d.logs}).from(d).where(eq(d.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(d).set({logs:JSON.stringify(o)}).where(eq(d.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(d).where(eq(d.status,"running")).orderBy(desc(d.started_at)).all()}catch(e){throw new a("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(d).orderBy(desc(d.started_at)).limit(100).all()}catch(e){throw new a("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(d).where(eq(d.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:d.id,status:d.status,pid:d.pid}).from(d).where(eq(d.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(d).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(d.id,t),eq(d.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:d.id,pid:d.pid}).from(d).where(eq(d.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(d).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(d.id,s.id),eq(d.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=k(s);try{let o=e?eq(d.workspace_id,e):void 0,l=o?and(eq(d.id,t),o):eq(d.id,t),u=r.db.select().from(d).where(l).limit(1).get()??void 0;if(!u){let p=or(eq(d.thread_id,t),and(isNull(d.thread_id),like(d.command,`%--thread=${t}%`))),f=o?and(p,o):p;u=r.db.select().from(d).where(f).orderBy(desc(d.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new a("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=e?and(eq(d.parent_task_id,t),eq(d.workspace_id,e)):eq(d.parent_task_id,t),p=l.db.select().from(d).where(u).orderBy(asc(d.started_at)).all();for(let f of p)s.has(f.id)||(s.add(f.id),r.push(f));}catch(u){throw new a("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
11
11
  SELECT
12
12
  COALESCE(workspace_id, 'unknown') AS workspace_id,
13
13
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -28,7 +28,7 @@ ${n.join(`
28
28
  FROM tasks
29
29
  GROUP BY workspace_id
30
30
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
31
- `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),s=new Set,r=0,o=0,l=0;for(let u of n){if(!existsSync(u))continue;let p=w(u);try{let h=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),m=e?and(h,eq(i.workspace_id,e)):h,y=p.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(m).all();for(let S of y)s.has(S.id)||(s.add(S.id),r+=S.input_tokens??0,o+=S.output_tokens??0,l+=S.cost_usd??0);}catch(h){throw new d("DB_ERROR","Failed to get thread token usage",h)}finally{p.close();}}return {inputTokens:r,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),p=e?and(u,eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(p).orderBy(asc(i.started_at)).all();for(let m of h)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(i.workspace_id,t.workspaceId));let s=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;s&&n.push(inArray(i.agent_id,s));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&n.push(inArray(i.status,r));let o=t.q??t.search;o&&n.push(like(i.prompt,`%${o}%`)),t.from&&n.push(gte(i.started_at,t.from)),t.to&&n.push(lt(i.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(i).where(l).get(),p=(t.sortDir??"DESC")==="ASC"?asc(i.started_at):desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(p).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
31
+ `)}catch(n){throw new a("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),s=new Set,r=0,o=0,l=0;for(let u of n){if(!existsSync(u))continue;let p=k(u);try{let f=or(eq(d.thread_id,t),and(isNull(d.thread_id),like(d.command,`%--thread=${t}%`))),m=e?and(f,eq(d.workspace_id,e)):f,w=p.db.select({id:d.id,input_tokens:d.input_tokens,output_tokens:d.output_tokens,cost_usd:d.cost_usd}).from(d).where(m).all();for(let D of w)s.has(D.id)||(s.add(D.id),r+=D.input_tokens??0,o+=D.output_tokens??0,l+=D.cost_usd??0);}catch(f){throw new a("DB_ERROR","Failed to get thread token usage",f)}finally{p.close();}}return {inputTokens:r,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=or(eq(d.thread_id,t),and(isNull(d.thread_id),like(d.command,`%--thread=${t}%`))),p=e?and(u,eq(d.workspace_id,e)):u,f=l.db.select().from(d).where(p).orderBy(asc(d.started_at)).all();for(let m of f)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new a("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(d.workspace_id,t.workspaceId));let s=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;s&&n.push(inArray(d.agent_id,s));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&n.push(inArray(d.status,r));let o=t.q??t.search;o&&n.push(like(d.prompt,`%${o}%`)),t.from&&n.push(gte(d.started_at,t.from)),t.to&&n.push(lt(d.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(d).where(l).get(),p=(t.sortDir??"DESC")==="ASC"?asc(d.started_at):desc(d.started_at);return {rows:e.db.select().from(d).where(l).orderBy(p).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new a("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
32
32
  SELECT
33
33
  t.agent_id,
34
34
  t.workspace_id,
@@ -59,7 +59,7 @@ ${n.join(`
59
59
  AND t.started_at < ${e}
60
60
  GROUP BY t.agent_id, t.workspace_id
61
61
  ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
62
- `).map(o=>({agentId:o.agent_id,workspaceId:o.workspace_id??null,totalTasks:o.total_tasks,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new d("DB_ERROR","Failed to get agent usage",r)}finally{s.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
62
+ `).map(o=>({agentId:o.agent_id,workspaceId:o.workspace_id??null,totalTasks:o.total_tasks,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new a("DB_ERROR","Failed to get agent usage",r)}finally{s.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
63
63
  SELECT
64
64
  date(t.started_at) AS date,
65
65
  t.agent_id,
@@ -88,13 +88,44 @@ ${n.join(`
88
88
  AND t.started_at < ${e}
89
89
  GROUP BY date(t.started_at), t.agent_id
90
90
  ORDER BY date(t.started_at) ASC
91
- `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new d("DB_ERROR","Failed to get agent usage trend",r)}finally{s.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(and(eq(i.id,t),eq(i.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new d("DB_ERROR","Failed to find task for stop",s)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString(),o=n?and(eq(i.id,t),eq(i.status,"running"),eq(i.workspace_id,n)):and(eq(i.id,t),eq(i.status,"running"));s.db.update(i).set({status:"failed",error:e,completed_at:r}).where(o).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to mark task failed",r)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=e?and(like(i.prompt,`%${t}%`),eq(i.workspace_id,e)):like(i.prompt,`%${t}%`),p=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of p)s.has(h.id)||(s.add(h.id),r.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return r}};var yt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:f.id}).from(f).where(eq(f.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!existsSync(r))continue;let o=w(r);try{let l=t?eq(c.workspace_id,t):void 0,u=o.db.select().from(c).where(l).orderBy(desc(c.updated_at)).all();for(let p of u)n.has(p.id)||(n.add(p.id),s.push(p));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=w(s);try{let o=eq(c.id,t),l=e?and(o,eq(c.workspace_id,e)):o,u=r.db.select().from(c).where(l).limit(1).get()??void 0;if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find thread by id",o)}finally{r.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=w(s);try{let o=eq(c.id,t),l=e?and(o,eq(c.workspace_id,e)):o;if(r.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(o){throw new d("DB_ERROR","Failed to check thread existence",o)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,o=0,l=0,u=0,p=new Set;for(let h of n){if(!existsSync(h))continue;let m=w(h);try{let y=and(eq(i.thread_id,t),or(isNull(i.parent_task_id),eq(i.parent_task_id,""))),S=e?and(y,eq(i.workspace_id,e)):y,v=m.db.select({cnt:sql`count(*)`,total_input:sql`COALESCE(SUM(input_tokens), 0)`,total_output:sql`COALESCE(SUM(output_tokens), 0)`,total_cached:sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:sql`COALESCE(SUM(cost_usd), 0)`}).from(i).where(S).get();v&&(s+=v.cnt,r+=v.total_input,o+=v.total_output,l+=v.total_cached,u+=v.total_cost);let q=m.db.all(sql`
92
- SELECT DISTINCT agent_id FROM tasks
93
- WHERE thread_id = ${t}
94
- AND agent_id IS NOT NULL AND agent_id != ''
95
- AND (parent_task_id IS NULL OR parent_task_id = '')
96
- ${e?sql`AND workspace_id = ${e}`:sql``}
97
- `);for(let V of q)p.add(V.agent_id);}catch(y){throw new d("DB_ERROR","Failed to aggregate task stats",y)}finally{m.close();}}return {taskCount:s,inputTokens:r,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=and(eq(i.thread_id,t),or(isNull(i.parent_task_id),eq(i.parent_task_id,""))),p=e?and(u,eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(p).orderBy(asc(i.started_at)).all();for(let m of h)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new d("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return r}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=eq(i.thread_id,t),p=e?and(u,eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(p).orderBy(asc(i.started_at)).all();for(let m of h)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return r}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let o=w(r);try{let l=and(eq(i.id,e),eq(i.thread_id,t)),u=n?and(l,eq(i.workspace_id,n)):l,p=o.db.select().from(i).where(u).limit(1).get();if(!p)continue;let h=o.db.select().from(i).where(eq(i.parent_task_id,p.id)).orderBy(asc(i.started_at)).all();return {task:p,children:h}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{o.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let o=w(r);try{let l=and(inArray(i.thread_id,t),or(isNull(i.parent_task_id),eq(i.parent_task_id,""))),u=e?and(l,eq(i.workspace_id,e)):l,p=o.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of p){let m=h.thread_id;n.has(m)||n.set(m,[]),n.get(m).push(h);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{o.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=eq(c.id,t),o=n?and(r,eq(c.workspace_id,n)):r;if(!s.db.select({id:c.id}).from(c).where(o).limit(1).get())return;s.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(c.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread title",r)}finally{s.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let s=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,r=new Date().toISOString();if(n.db.select({id:c.id,message_count:c.message_count}).from(c).where(eq(c.id,t)).limit(1).get()){let l={updated_at:r};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(c).set(l).where(eq(c.id,t)).run();}else n.db.insert(c).values({id:t,platform:e.platform,workspace_id:s,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to upsert thread",s)}finally{n.close();}}ensureThread(t,e,n){let s=this.openHandle(true);try{let r=n?this.validateWorkspaceId(s,n):null,o=s.db.select({id:c.id,platform:c.platform,workspace_id:c.workspace_id}).from(c).where(eq(c.id,t)).limit(1).get();if(o){r&&!o.workspace_id&&s.db.update(c).set({workspace_id:r}).where(eq(c.id,t)).run();return}let l=new Date().toISOString();s.db.insert(c).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to ensure thread",r)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let s=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:s.db.transaction(l=>{let p=l.select({message_count:c.message_count}).from(c).where(eq(c.id,t)).limit(1).get()?.message_count===0;return l.run(sql`
91
+ `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new a("DB_ERROR","Failed to get agent usage trend",r)}finally{s.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(d).where(and(eq(d.id,t),eq(d.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new a("DB_ERROR","Failed to find task for stop",s)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString(),o=n?and(eq(d.id,t),eq(d.status,"running"),eq(d.workspace_id,n)):and(eq(d.id,t),eq(d.status,"running"));s.db.update(d).set({status:"failed",error:e,completed_at:r}).where(o).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to mark task failed",r)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=e?and(like(d.prompt,`%${t}%`),eq(d.workspace_id,e)):like(d.prompt,`%${t}%`),p=l.db.select().from(d).where(u).orderBy(asc(d.started_at)).all();for(let f of p)s.has(f.id)||(s.add(f.id),r.push(f));}catch(u){throw new a("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return r}};var wt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(eq(h.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
92
+ ${t}.parent_task_id IS NULL
93
+ OR ${t}.parent_task_id = ''
94
+ OR NOT EXISTS (
95
+ SELECT 1 FROM tasks parent
96
+ WHERE parent.id = ${t}.parent_task_id
97
+ AND parent.thread_id = ${t}.thread_id
98
+ )
99
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!existsSync(r))continue;let o=k(r);try{let l=t?eq(c.workspace_id,t):void 0,u=o.db.select().from(c).where(l).orderBy(desc(c.updated_at)).all();for(let p of u)n.has(p.id)||(n.add(p.id),s.push(p));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=k(s);try{let o=eq(c.id,t),l=e?and(o,eq(c.workspace_id,e)):o,u=r.db.select().from(c).where(l).limit(1).get()??void 0;if(u)return u}catch(o){throw new a("DB_ERROR","Failed to find thread by id",o)}finally{r.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=k(s);try{let o=eq(c.id,t),l=e?and(o,eq(c.workspace_id,e)):o;if(r.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(o){throw new a("DB_ERROR","Failed to check thread existence",o)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,o=0,l=0,u=0,p=new Set;for(let f of n){if(!existsSync(f))continue;let m=k(f);try{let w=m.db.get(sql`
100
+ SELECT
101
+ count(*) AS cnt,
102
+ COALESCE(SUM(child.input_tokens), 0) AS total_input,
103
+ COALESCE(SUM(child.output_tokens), 0) AS total_output,
104
+ COALESCE(SUM(child.cached_input_tokens), 0) AS total_cached,
105
+ COALESCE(SUM(child.cost_usd), 0) AS total_cost
106
+ FROM tasks child
107
+ WHERE child.thread_id = ${t}
108
+ AND ${this.topLevelTaskPredicateSql()}
109
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
110
+ `);w&&(s+=w.cnt,r+=w.total_input,o+=w.total_output,l+=w.total_cached,u+=w.total_cost);let D=m.db.all(sql`
111
+ SELECT DISTINCT child.agent_id FROM tasks child
112
+ WHERE child.thread_id = ${t}
113
+ AND child.agent_id IS NOT NULL AND child.agent_id != ''
114
+ AND ${this.topLevelTaskPredicateSql()}
115
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
116
+ `);for(let J of D)p.add(J.agent_id);}catch(w){throw new a("DB_ERROR","Failed to aggregate task stats",w)}finally{m.close();}}return {taskCount:s,inputTokens:r,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=l.db.all(sql`
117
+ SELECT child.* FROM tasks child
118
+ WHERE child.thread_id = ${t}
119
+ AND ${this.topLevelTaskPredicateSql()}
120
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
121
+ ORDER BY child.started_at ASC
122
+ `);for(let p of u)s.has(p.id)||(s.add(p.id),r.push(p));}catch(u){throw new a("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return r}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=eq(d.thread_id,t),p=e?and(u,eq(d.workspace_id,e)):u,f=l.db.select().from(d).where(p).orderBy(asc(d.started_at)).all();for(let m of f)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new a("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return r}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let o=k(r);try{let l=and(eq(d.id,e),eq(d.thread_id,t)),u=n?and(l,eq(d.workspace_id,n)):l,p=o.db.select().from(d).where(u).limit(1).get();if(!p)continue;let f=o.db.select().from(d).where(eq(d.parent_task_id,p.id)).orderBy(asc(d.started_at)).all();return {task:p,children:f}}catch(l){throw new a("DB_ERROR","Failed to find task by id",l)}finally{o.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let o=k(r);try{let l=o.db.all(sql`
123
+ SELECT child.* FROM tasks child
124
+ WHERE child.thread_id IN (${sql.join(t.map(u=>sql`${u}`),sql`, `)})
125
+ AND ${this.topLevelTaskPredicateSql()}
126
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
127
+ ORDER BY child.started_at ASC
128
+ `);for(let u of l){let p=u.thread_id;n.has(p)||n.set(p,[]),n.get(p).push(u);}}catch(l){throw new a("DB_ERROR","Failed to batch fetch tasks",l)}finally{o.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=eq(c.id,t),o=n?and(r,eq(c.workspace_id,n)):r;if(!s.db.select({id:c.id}).from(c).where(o).limit(1).get())return;s.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(c.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update thread title",r)}finally{s.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let s=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,r=new Date().toISOString();if(n.db.select({id:c.id,message_count:c.message_count}).from(c).where(eq(c.id,t)).limit(1).get()){let l={updated_at:r};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(c).set(l).where(eq(c.id,t)).run();}else n.db.insert(c).values({id:t,platform:e.platform,workspace_id:s,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to upsert thread",s)}finally{n.close();}}ensureThread(t,e,n){let s=this.openHandle(true);try{let r=n?this.validateWorkspaceId(s,n):null,o=s.db.select({id:c.id,platform:c.platform,workspace_id:c.workspace_id}).from(c).where(eq(c.id,t)).limit(1).get();if(o){r&&!o.workspace_id&&s.db.update(c).set({workspace_id:r}).where(eq(c.id,t)).run();return}let l=new Date().toISOString();s.db.insert(c).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to ensure thread",r)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let s=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:s.db.transaction(l=>{let p=l.select({message_count:c.message_count}).from(c).where(eq(c.id,t)).limit(1).get()?.message_count===0;return l.run(sql`
98
129
  UPDATE threads
99
130
  SET first_message = COALESCE(first_message, ${e}),
100
131
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -102,4 +133,4 @@ ${n.join(`
102
133
  message_count = message_count + 1,
103
134
  updated_at = ${r}
104
135
  WHERE id = ${t}
105
- `),p},{behavior:"immediate"})}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save user message",r)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.update(c).set({last_message:e,updated_at:r}).where(eq(c.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save assistant message",r)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(c).set(s).where(eq(c.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread",s)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let s=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),r=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(s).get();if(!r)return null;let o=r.pinned?0:1,l=r.metadata?JSON.parse(r.metadata):{};if(o){let u=e?and(eq(c.pinned,1),eq(c.workspace_id,e)):eq(c.pinned,1),p=n.db.select({metadata:c.metadata}).from(c).where(u).all(),h=0;for(let m of p){let y=m.metadata?JSON.parse(m.metadata):{};typeof y.pinOrder=="number"&&y.pinOrder>h&&(h=y.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(s).run(),{pinned:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle pin",s)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let s=0;s<t.length;s++){let r=e?and(eq(c.id,t[s]),eq(c.workspace_id,e)):eq(c.id,t[s]),o=n.db.select({metadata:c.metadata}).from(c).where(r).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=s+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(r).run();}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to reorder pins",s)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let s=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),r=n.db.select({starred:c.starred}).from(c).where(s).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(c).set({starred:o}).where(s).run(),{starred:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}};var Rt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(H).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(H).where(eq(H.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(H).where(eq(H.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var Et=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(z).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(z).where(eq(z.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:z.tool_name,count:sql`count(*)`}).from(z).where(eq(z.task_id,t)).groupBy(z.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var xt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:c.id}).from(c).where(eq(c.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(N).where(eq(N.thread_id,t)).orderBy(asc(N.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(N).where(and(eq(N.id,e),eq(N.thread_id,t))).limit(1).get()??void 0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(N).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(N).where(eq(N.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Dt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let r of t)s.insert(K).values({id:randomUUID(),path:r.path,method:r.method,status_code:r.statusCode,duration_ms:r.durationMs,ip:r.ip??null,request_headers:r.requestHeaders??null,response_headers:r.responseHeaders??null,request_body:r.requestBody??null,response_body:r.responseBody??null,query:r.query??null,user_id:r.userId??null,project_id:r.projectId??null,partition_key:r.partitionKey??"default",timestamp:n,metadata:r.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(K).orderBy(desc(K.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};export{E as BaseSqliteRepository,d as RepositoryError,Dt as RequestLogRepository,Rt as SpanRepository,wt as TaskRepository,xt as ThreadBoxRepository,yt as ThreadRepository,Et as ToolCallRepository,_t as WorkspaceRepository,w as openDrizzleDb,Pe as pushSchema,Y as runMigrations,O as runMigrationsOnce};
136
+ `),p},{behavior:"immediate"})}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to save user message",r)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.update(c).set({last_message:e,updated_at:r}).where(eq(c.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to save assistant message",r)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(c).set(s).where(eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread",s)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let s=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),r=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(s).get();if(!r)return null;let o=r.pinned?0:1,l=r.metadata?JSON.parse(r.metadata):{};if(o){let u=e?and(eq(c.pinned,1),eq(c.workspace_id,e)):eq(c.pinned,1),p=n.db.select({metadata:c.metadata}).from(c).where(u).all(),f=0;for(let m of p){let w=m.metadata?JSON.parse(m.metadata):{};typeof w.pinOrder=="number"&&w.pinOrder>f&&(f=w.pinOrder);}l.pinOrder=f+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(s).run(),{pinned:!!o}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to toggle pin",s)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let s=0;s<t.length;s++){let r=e?and(eq(c.id,t[s]),eq(c.workspace_id,e)):eq(c.id,t[s]),o=n.db.select({metadata:c.metadata}).from(c).where(r).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=s+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(r).run();}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to reorder pins",s)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let s=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),r=n.db.select({starred:c.starred}).from(c).where(s).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(c).set({starred:o}).where(s).run(),{starred:!!o}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}};var kt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(q).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(q).where(eq(q.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(q).where(eq(q.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var bt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(B).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(B).where(eq(B.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:B.tool_name,count:sql`count(*)`}).from(B).where(eq(B.task_id,t)).groupBy(B.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new a("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var Rt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:c.id}).from(c).where(eq(c.id,e)).limit(1).get())throw new a("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(P).where(eq(P.thread_id,t)).orderBy(asc(P.seq)).all()}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(P).where(and(eq(P.id,e),eq(P.thread_id,t))).limit(1).get()??void 0}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(P).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new a("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(P).where(eq(P.id,t.id)).limit(1).get();if(!n)throw new a("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var yt=class extends E{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let r of t)s.insert(G).values({id:randomUUID(),path:r.path,method:r.method,status_code:r.statusCode,duration_ms:r.durationMs,ip:r.ip??null,request_headers:r.requestHeaders??null,response_headers:r.responseHeaders??null,request_body:r.requestBody??null,response_body:r.responseBody??null,query:r.query??null,user_id:r.userId??null,project_id:r.projectId??null,partition_key:r.partitionKey??"default",timestamp:n,metadata:r.metadata??null}).run();});}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(G).orderBy(desc(G.timestamp)).limit(t).all()}catch(n){throw new a("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};export{E as BaseSqliteRepository,a as RepositoryError,yt as RequestLogRepository,kt as SpanRepository,gt as TaskRepository,Rt as ThreadBoxRepository,wt as ThreadRepository,bt as ToolCallRepository,ft as WorkspaceRepository,k as openDrizzleDb,Ae as pushSchema,Y as runMigrations,O as runMigrationsOnce};