@crewx/sdk 0.8.9-rc.15 → 0.8.9-rc.17

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,13 +1,13 @@
1
- import*as z from'path';import z__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Ht,{existsSync,mkdirSync,readFileSync}from'fs';import se from'os';import {sql,and,eq,ne,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 nt=(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 Zt=()=>fileURLToPath(import.meta.url),te=()=>z__default.dirname(Zt()),E=te();var S=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(se.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=nt("better-sqlite3"),{drizzle:e}=nt("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 At=new Set,re={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 _t(i,t){return (i.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function oe(i,t){if(t>0||!_t(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(re))n.has(s)||i.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}var ie={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ae(i,t,e){if(!_t(i,"__drizzle_migrations")||!_t(i,"tasks"))return;let n=i.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(readFileSync(z__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=ie[o.tag];if(!l)continue;let u=z__default.join(t,`${o.tag}.sql`);if(!existsSync(u))continue;let p=readFileSync(u,"utf-8"),_=createHash("sha256").update(p).digest("hex");if(s.has(_))continue;let m=i.all("PRAGMA table_info(tasks)"),w=new Set(m.map(y=>y.name));for(let[y,U]of Object.entries(l))w.has(y)||(i.run(`ALTER TABLE tasks ADD COLUMN ${y} ${U}`),w.add(y));}}function de(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(z__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=z__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 _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],w;for(;(w=_.exec(u))!==null;)m.push({table:w[1],column:w[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(F=>F.trim()).filter(Boolean).every(F=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(F)))continue;m.every(({table:F,column:pt})=>i.all(`PRAGMA table_info("${F}")`).some(ht=>ht.name===pt))&&i.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${o.when})`);}}function G(i){let{migrate:t}=nt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=nt("drizzle-orm"),n=[z__default.join(E,"../migrations"),z__default.join(E,"migrations"),z__default.join(E,"../../../../drizzle/migrations"),z__default.join(process.cwd(),"drizzle/migrations")],s=n.find(p=>existsSync(z__default.join(p,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
1
+ import*as z from'path';import z__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Ht,{existsSync,mkdirSync,readFileSync}from'fs';import se from'os';import {sql,and,eq,ne,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 nt=(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 Zt=()=>fileURLToPath(import.meta.url),te=()=>z__default.dirname(Zt()),b=te();var S=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(se.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 k(a){let t=nt("better-sqlite3"),{drizzle:e}=nt("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 At=new Set,re={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 ht(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function oe(a,t){if(t>0||!ht(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(re))n.has(s)||a.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}var ie={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ae(a,t,e){if(!ht(a,"__drizzle_migrations")||!ht(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(i=>i.hash)),r=JSON.parse(readFileSync(z__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let l=ie[i.tag];if(!l)continue;let u=z__default.join(t,`${i.tag}.sql`);if(!existsSync(u))continue;let p=readFileSync(u,"utf-8"),h=createHash("sha256").update(p).digest("hex");if(s.has(h))continue;let m=a.all("PRAGMA table_info(tasks)"),w=new Set(m.map(y=>y.name));for(let[y,q]of Object.entries(l))w.has(y)||(a.run(`ALTER TABLE tasks ADD COLUMN ${y} ${q}`),w.add(y));}}function de(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(i=>i.hash)),r=JSON.parse(readFileSync(z__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let l=z__default.join(t,`${i.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=[],w;for(;(w=h.exec(u))!==null;)m.push({table:w[1],column:w[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(F=>F.trim()).filter(Boolean).every(F=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(F)))continue;m.every(({table:F,column:pt})=>a.all(`PRAGMA table_info("${F}")`).some(_t=>_t.name===pt))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${i.when})`);}}function J(a){let{migrate:t}=nt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=nt("drizzle-orm"),n=[z__default.join(b,"../migrations"),z__default.join(b,"migrations"),z__default.join(b,"../../../../drizzle/migrations"),z__default.join(process.cwd(),"drizzle/migrations")],s=n.find(p=>existsSync(z__default.join(p,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
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),oe(i,o),r?.cnt&&(de(i,s,e),ae(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){At.has(t)||(G(i),At.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 H=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(()=>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")},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 v=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 L=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 Y=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 wt(i){let t=z.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 $t(i){let t=wt(i);return createHash("sha256").update(t).digest("hex")}function at(i){return i.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var bt=class extends S{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{G(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=at(basename(n)),o=`${at(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(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 _=`${o}-${p}`;if(!u(_))return _}}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=at(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=wt(t),n=this.openHandle(true);try{let s=$t(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.*,
3
+ `)}`);let r=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),oe(a,i),r?.cnt&&(de(a,s,e),ae(a,s,e)),t(a,{migrationsFolder:s});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;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){At.has(t)||(J(a),At.add(t));}var _=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)},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(()=>_.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 U=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(()=>U.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 $=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()},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 L=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 Q=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 wt(a){let t=z.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 Bt(a){let t=wt(a);return createHash("sha256").update(t).digest("hex")}function at(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Et=class extends S{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=k(e);if(t)try{J(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=at(basename(n)),i=`${at(basename(dirname(n)))}-${s}`,l=[s,i];try{let u=p=>t.select({id:_.id}).from(_).where(and(eq(_.slug,p),ne(_.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=`${i}-${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:_.id,slug:_.slug}).from(_).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=at(s.slug.replace(/\//g,"-"));t.db.update(_).set({slug:r,updated_at:new Date().toISOString()}).where(eq(_.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:i}=e,l=new Date().toISOString();t.insert(_).values({id:n,slug:s,name:r,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(_).set({workspace_path:i,updated_at:l}).where(and(eq(_.id,n),isNull(_.workspace_path))).run();}registerWorkspace(t){let e=wt(t),n=this.openHandle(true);try{let s=Bt(e),r=basename(e),i=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:i,name:r,workspacePath:e}),{id:s,slug:i}}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(_.is_active,t.isActive?1:0):void 0,s=e.db.select({count:sql`count(*)`}).from(_).where(n).get();return {rows:e.db.select().from(_).where(n).orderBy(desc(_.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(_).where(eq(_.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.*,
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 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(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 Ut=[h,d,c,H,v,L,Y];function Ne(){return z__default.join(se.homedir(),".crewx","crewx.db")}function Ce(i){if(!Ht.existsSync(i))return null;let t=Math.floor(Date.now()/1e3),e=`${i}.bak-${t}`;return Ht.copyFileSync(i,e),e}function Ft(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 Le(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 Pe(i){let t=i.getSQLType(),e=`"${i.name}" ${t}`,n=Le(i.default);return n!==null&&(e+=` DEFAULT ${n}`),i.notNull&&(e+=" NOT NULL"),e}function ve(i,t){let e=t?.dbPath??Ne(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Ce(e);if(n&&!s)try{i.run("DELETE FROM __drizzle_migrations");}catch{}let o=Ft(i);if(!s)try{G(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=Ut.map(w=>getTableConfig(w).name).filter(w=>!o.has(w)),u=o):(u=Ft(i),l=[...u].filter(m=>!o.has(m)));let p=[],_=[];for(let m of Ut){let w=getTableConfig(m),y=w.name;if(!u.has(y))continue;let U=i.all(`PRAGMA table_info("${y}")`),F=new Set(U.map(P=>P.name)),pt=new Set(w.columns.map(P=>P.name));for(let P of w.columns)if(!F.has(P.name)){if(!s){let ht=Pe(P);i.run(`ALTER TABLE "${y}" ADD COLUMN ${ht}`);}p.push({table:y,column:P.name});}for(let P of U)pt.has(P.name)||_.push(`${y}.${P.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:_,backupPath:r}}var V="2026-05-09",qe="0.8.9-rc.13",Q=10,Z=parseInt(qe.split("rc.")[1]),yt=class extends S{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=?,
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(_).where(eq(_.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(_.slug,t),ne(_.id,e)):eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).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 i=new Date().toISOString();r.db.insert(_).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:i,updated_at:i}).run();let l=r.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof d?i:new d("DB_ERROR","Failed to insert workspace",i)}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(_).where(eq(_.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:_.id,workspace_path:_.workspace_path}).from(_).where(and(eq(_.is_active,1),isNotNull(_.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(_).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(_.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(_).where(eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Mt=[_,o,c,U,$,L,Q];function Ne(){return z__default.join(se.homedir(),".crewx","crewx.db")}function Ce(a){if(!Ht.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Ht.copyFileSync(a,e),e}function qt(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 Le(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 ve(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Le(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Pe(a,t){let e=t?.dbPath??Ne(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Ce(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=qt(a);if(!s)try{J(a);}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=Mt.map(w=>getTableConfig(w).name).filter(w=>!i.has(w)),u=i):(u=qt(a),l=[...u].filter(m=>!i.has(m)));let p=[],h=[];for(let m of Mt){let w=getTableConfig(m),y=w.name;if(!u.has(y))continue;let q=a.all(`PRAGMA table_info("${y}")`),F=new Set(q.map(P=>P.name)),pt=new Set(w.columns.map(P=>P.name));for(let P of w.columns)if(!F.has(P.name)){if(!s){let _t=ve(P);a.run(`ALTER TABLE "${y}" ADD COLUMN ${_t}`);}p.push({table:y,column:P.name});}for(let P of q)pt.has(P.name)||h.push(`${y}.${P.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:h,backupPath:r}}var G="2026-05-09",Ue="0.8.9-rc.13",X=10,Y=parseInt(Ue.split("rc.")[1]),yt=class extends S{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=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(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(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=?,
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 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}%`))),_=o?and(p,o):p;u=r.db.select().from(d).where(_).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 _ of p)s.has(_.id)||(s.add(_.id),r.push(_));}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`
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:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),s.update(o).set({logs:JSON.stringify(i)}).where(eq(o.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(o).where(eq(o.status,"running")).orderBy(desc(o.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(o).orderBy(desc(o.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(o).where(eq(o.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:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.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(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: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:o.id,pid:o.pid}).from(o).where(eq(o.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(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,s.id),eq(o.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 i=e?eq(o.workspace_id,e):void 0,l=i?and(eq(o.id,t),i):eq(o.id,t),u=r.db.select().from(o).where(l).limit(1).get()??void 0;if(!u){let p=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),h=i?and(p,i):p;u=r.db.select().from(o).where(h).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),p=l.db.select().from(o).where(u).orderBy(asc(o.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`
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 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 _=or(eq(d.thread_id,t),and(isNull(d.thread_id),like(d.command,`%--thread=${t}%`))),m=e?and(_,eq(d.workspace_id,e)):_,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 y of w)s.has(y.id)||(s.add(y.id),r+=y.input_tokens??0,o+=y.output_tokens??0,l+=y.cost_usd??0);}catch(_){throw new a("DB_ERROR","Failed to get thread token usage",_)}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,_=l.db.select().from(d).where(p).orderBy(asc(d.started_at)).all();for(let m of _)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`
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,i=0,l=0;for(let u of n){if(!existsSync(u))continue;let p=k(u);try{let h=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),m=e?and(h,eq(o.workspace_id,e)):h,w=p.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(m).all();for(let y of w)s.has(y.id)||(s.add(y.id),r+=y.input_tokens??0,i+=y.output_tokens??0,l+=y.cost_usd??0);}catch(h){throw new d("DB_ERROR","Failed to get thread token usage",h)}finally{p.close();}}return {inputTokens:r,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),p=e?and(u,eq(o.workspace_id,e)):u,h=l.db.select().from(o).where(p).orderBy(asc(o.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(o.workspace_id,t.workspaceId));let s=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;s&&n.push(inArray(o.agent_id,s));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&n.push(inArray(o.status,r));let i=t.q??t.search;i&&n.push(like(o.prompt,`%${i}%`)),t.from&&n.push(gte(o.started_at,t.from)),t.to&&n.push(lt(o.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(o).where(l).get(),p=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).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`
32
32
  SELECT
33
33
  t.agent_id,
34
34
  t.workspace_id,
@@ -36,11 +36,11 @@ ${n.join(`
36
36
  COALESCE(SUM(
37
37
  COALESCE(t.input_tokens, 0)
38
38
  + CASE
39
- WHEN t.started_at >= ${V}
39
+ WHEN t.started_at >= ${G}
40
40
  AND (
41
41
  t.crewx_version IS NULL
42
42
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
43
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Q}) AS INTEGER) < ${Z})
43
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${Y})
44
44
  )
45
45
  THEN COALESCE(t.cached_input_tokens, 0)
46
46
  ELSE 0
@@ -59,11 +59,11 @@ ${n.join(`
59
59
  COALESCE(SUM(
60
60
  COALESCE(t.input_tokens, 0)
61
61
  + CASE
62
- WHEN t.started_at >= ${V}
62
+ WHEN t.started_at >= ${G}
63
63
  AND (
64
64
  t.crewx_version IS NULL
65
65
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
66
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Q}) AS INTEGER) < ${Z})
66
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${Y})
67
67
  )
68
68
  THEN COALESCE(t.cached_input_tokens, 0)
69
69
  ELSE 0
@@ -79,11 +79,11 @@ ${n.join(`
79
79
  COALESCE(SUM(
80
80
  COALESCE(t.input_tokens, 0)
81
81
  + CASE
82
- WHEN t.started_at >= ${V}
82
+ WHEN t.started_at >= ${G}
83
83
  AND (
84
84
  t.crewx_version IS NULL
85
85
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
86
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Q}) AS INTEGER) < ${Z})
86
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${Y})
87
87
  )
88
88
  THEN COALESCE(t.cached_input_tokens, 0)
89
89
  ELSE 0
@@ -101,11 +101,11 @@ ${n.join(`
101
101
  COALESCE(SUM(
102
102
  COALESCE(t.input_tokens, 0)
103
103
  + CASE
104
- WHEN t.started_at >= ${V}
104
+ WHEN t.started_at >= ${G}
105
105
  AND (
106
106
  t.crewx_version IS NULL
107
107
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
108
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Q}) AS INTEGER) < ${Z})
108
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${Y})
109
109
  )
110
110
  THEN COALESCE(t.cached_input_tokens, 0)
111
111
  ELSE 0
@@ -113,18 +113,18 @@ ${n.join(`
113
113
  ), 0)
114
114
  + COALESCE(SUM(t.output_tokens), 0)
115
115
  ) DESC
116
- `).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,totalTokens:o.input_tokens+o.output_tokens}))}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`
116
+ `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(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`
117
117
  SELECT
118
118
  date(t.started_at) AS date,
119
119
  t.agent_id,
120
120
  COALESCE(SUM(
121
121
  COALESCE(t.input_tokens, 0)
122
122
  + CASE
123
- WHEN t.started_at >= ${V}
123
+ WHEN t.started_at >= ${G}
124
124
  AND (
125
125
  t.crewx_version IS NULL
126
126
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
127
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Q}) AS INTEGER) < ${Z})
127
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${Y})
128
128
  )
129
129
  THEN COALESCE(t.cached_input_tokens, 0)
130
130
  ELSE 0
@@ -147,11 +147,11 @@ ${n.join(`
147
147
  COALESCE(SUM(
148
148
  COALESCE(t.input_tokens, 0)
149
149
  + CASE
150
- WHEN t.started_at >= ${V}
150
+ WHEN t.started_at >= ${G}
151
151
  AND (
152
152
  t.crewx_version IS NULL
153
153
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
154
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Q}) AS INTEGER) < ${Z})
154
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${Y})
155
155
  )
156
156
  THEN COALESCE(t.cached_input_tokens, 0)
157
157
  ELSE 0
@@ -166,7 +166,43 @@ ${n.join(`
166
166
  AND t.started_at < ${e}
167
167
  GROUP BY date(t.started_at), t.agent_id
168
168
  ORDER BY date(t.started_at) ASC
169
- `).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,totalTokens:o.input_tokens+o.output_tokens}))}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 _ of p)s.has(_.id)||(s.add(_.id),r.push(_));}catch(u){throw new a("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return r}};var St=class extends S{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(`(
169
+ `).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,totalTokens:i.input_tokens+i.output_tokens}))}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(o).where(and(eq(o.id,t),eq(o.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(),i=n?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,n)):and(eq(o.id,t),eq(o.status,"running"));s.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).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 i of n){if(!existsSync(i))continue;let l=k(i);try{let u=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),p=l.db.select().from(o).where(u).orderBy(asc(o.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}getProviderUsage(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{let r=sql`
170
+ CASE
171
+ WHEN ${o.model} LIKE 'claude-%' OR ${o.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
172
+ WHEN ${o.model} LIKE 'gpt-%' OR ${o.model} LIKE 'codex-%' THEN 'codex'
173
+ WHEN ${o.model} LIKE 'gemini-%' THEN 'gemini'
174
+ WHEN ${o.model} LIKE 'zai-%' OR ${o.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
175
+ WHEN ${o.model} LIKE 'minimax/%' THEN 'minimax'
176
+ WHEN ${o.model} LIKE 'qwen%' THEN 'qwen'
177
+ ELSE 'unknown'
178
+ END
179
+ `,i=sql`
180
+ COALESCE(${o.input_tokens}, 0)
181
+ + CASE
182
+ WHEN ${o.started_at} >= ${G}
183
+ AND (
184
+ ${o.crewx_version} IS NULL
185
+ OR (${o.crewx_version} LIKE '0.8.%' AND ${o.crewx_version} NOT LIKE '0.8.9%')
186
+ OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${X}) AS INTEGER) < ${Y})
187
+ )
188
+ THEN COALESCE(${o.cached_input_tokens}, 0)
189
+ ELSE 0
190
+ END
191
+ `,l=n?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e} AND ${o.workspace_id} = ${n}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e}`;return s.db.all(sql`
192
+ SELECT
193
+ ${r} AS provider,
194
+ COUNT(*) AS total_tasks,
195
+ COALESCE(SUM(${i}), 0) AS input_tokens,
196
+ COALESCE(SUM(${o.output_tokens}), 0) AS output_tokens,
197
+ COALESCE(SUM(${o.cached_input_tokens}), 0) AS cached_input_tokens,
198
+ COALESCE(SUM(${o.cost_usd}), 0) AS cost_usd,
199
+ COALESCE(SUM(${o.duration_ms}), 0) AS active_duration_ms,
200
+ MAX(${o.completed_at}) AS last_active_at
201
+ FROM ${o}
202
+ ${l}
203
+ GROUP BY provider
204
+ ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${o.output_tokens}), 0)) DESC
205
+ `).map(p=>({provider:p.provider,totalTasks:p.total_tasks,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(r){throw new d("DB_ERROR","Failed to get provider usage",r)}finally{s.close();}}};var St=class extends S{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=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:_.id}).from(_).where(eq(_.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
170
206
  ${t}.parent_task_id IS NULL
171
207
  OR ${t}.parent_task_id = ''
172
208
  OR NOT EXISTS (
@@ -174,7 +210,7 @@ ${n.join(`
174
210
  WHERE parent.id = ${t}.parent_task_id
175
211
  AND parent.thread_id = ${t}.thread_id
176
212
  )
177
- )`)}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 _ of n){if(!existsSync(_))continue;let m=k(_);try{let w=m.db.get(sql`
213
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!existsSync(r))continue;let i=k(r);try{let l=t?eq(c.workspace_id,t):void 0,u=i.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{i.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 i=eq(c.id,t),l=e?and(i,eq(c.workspace_id,e)):i,u=r.db.select().from(c).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find thread by id",i)}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 i=eq(c.id,t),l=e?and(i,eq(c.workspace_id,e)):i;if(r.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(i){throw new d("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,i=0,l=0,u=0,p=new Set;for(let h of n){if(!existsSync(h))continue;let m=k(h);try{let w=m.db.get(sql`
178
214
  SELECT
179
215
  count(*) AS cnt,
180
216
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -185,25 +221,25 @@ ${n.join(`
185
221
  WHERE child.thread_id = ${t}
186
222
  AND ${this.topLevelTaskPredicateSql()}
187
223
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
188
- `);w&&(s+=w.cnt,r+=w.total_input,o+=w.total_output,l+=w.total_cached,u+=w.total_cost);let y=m.db.all(sql`
224
+ `);w&&(s+=w.cnt,r+=w.total_input,i+=w.total_output,l+=w.total_cached,u+=w.total_cost);let y=m.db.all(sql`
189
225
  SELECT DISTINCT child.agent_id FROM tasks child
190
226
  WHERE child.thread_id = ${t}
191
227
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
192
228
  AND ${this.topLevelTaskPredicateSql()}
193
229
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
194
- `);for(let U of y)p.add(U.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`
230
+ `);for(let q of y)p.add(q.agent_id);}catch(w){throw new d("DB_ERROR","Failed to aggregate task stats",w)}finally{m.close();}}return {taskCount:s,inputTokens:r,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=l.db.all(sql`
195
231
  SELECT child.* FROM tasks child
196
232
  WHERE child.thread_id = ${t}
197
233
  AND ${this.topLevelTaskPredicateSql()}
198
234
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
199
235
  ORDER BY child.started_at ASC
200
- `);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,_=l.db.select().from(d).where(p).orderBy(asc(d.started_at)).all();for(let m of _)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 _=o.db.select().from(d).where(eq(d.parent_task_id,p.id)).orderBy(asc(d.started_at)).all();return {task:p,children:_}}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`
236
+ `);for(let p of u)s.has(p.id)||(s.add(p.id),r.push(p));}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 i of n){if(!existsSync(i))continue;let l=k(i);try{let u=eq(o.thread_id,t),p=e?and(u,eq(o.workspace_id,e)):u,h=l.db.select().from(o).where(p).orderBy(asc(o.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 i=k(r);try{let l=and(eq(o.id,e),eq(o.thread_id,t)),u=n?and(l,eq(o.workspace_id,n)):l,p=i.db.select().from(o).where(u).limit(1).get();if(!p)continue;let h=i.db.select().from(o).where(eq(o.parent_task_id,p.id)).orderBy(asc(o.started_at)).all();return {task:p,children:h}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{i.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 i=k(r);try{let l=i.db.all(sql`
201
237
  SELECT child.* FROM tasks child
202
238
  WHERE child.thread_id IN (${sql.join(t.map(u=>sql`${u}`),sql`, `)})
203
239
  AND ${this.topLevelTaskPredicateSql()}
204
240
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
205
241
  ORDER BY child.started_at ASC
206
- `);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`
242
+ `);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 d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=eq(c.id,t),i=n?and(r,eq(c.workspace_id,n)):r;if(!s.db.select({id:c.id}).from(c).where(i).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,i=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(i){r&&!i.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`
207
243
  UPDATE threads
208
244
  SET first_message = COALESCE(first_message, ${e}),
209
245
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -211,4 +247,4 @@ ${n.join(`
211
247
  message_count = message_count + 1,
212
248
  updated_at = ${r}
213
249
  WHERE id = ${t}
214
- `),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(),_=0;for(let m of p){let w=m.metadata?JSON.parse(m.metadata):{};typeof w.pinOrder=="number"&&w.pinOrder>_&&(_=w.pinOrder);}l.pinOrder=_+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 Tt=class extends S{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(H).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(H).where(eq(H.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(H).where(eq(H.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 xt=class extends S{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(v).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(v).where(eq(v.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:v.tool_name,count:sql`count(*)`}).from(v).where(eq(v.task_id,t)).groupBy(v.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 Dt=class extends S{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(L).where(eq(L.thread_id,t)).orderBy(asc(L.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(L).where(and(eq(L.id,e),eq(L.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(L).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(L).where(eq(L.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 Ot=class extends S{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(Y).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(Y).orderBy(desc(Y.timestamp)).limit(t).all()}catch(n){throw new a("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};export{S as BaseSqliteRepository,a as RepositoryError,Ot as RequestLogRepository,Tt as SpanRepository,yt as TaskRepository,Dt as ThreadBoxRepository,St as ThreadRepository,xt as ToolCallRepository,bt as WorkspaceRepository,k as openDrizzleDb,ve as pushSchema,G as runMigrations,O as runMigrationsOnce};
250
+ `),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 i=r.pinned?0:1,l=r.metadata?JSON.parse(r.metadata):{};if(i){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 w=m.metadata?JSON.parse(m.metadata):{};typeof w.pinOrder=="number"&&w.pinOrder>h&&(h=w.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(s).run(),{pinned:!!i}}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]),i=n.db.select({metadata:c.metadata}).from(c).where(r).get();if(!i)continue;let l=i.metadata?JSON.parse(i.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 i=r.starred?0:1;return n.db.update(c).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}};var Tt=class extends S{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=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(U).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(U).where(eq(U.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(U).where(eq(U.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 Dt=class extends S{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=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($).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($).where(eq($.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:$.tool_name,count:sql`count(*)`}).from($).where(eq($.task_id,t)).groupBy($.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 S{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=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 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(L).where(eq(L.thread_id,t)).orderBy(asc(L.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(L).where(and(eq(L.id,e),eq(L.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(L).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(L).where(eq(L.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 Ot=class extends S{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=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(Q).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(Q).orderBy(desc(Q.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};export{S as BaseSqliteRepository,d as RepositoryError,Ot as RequestLogRepository,Tt as SpanRepository,yt as TaskRepository,xt as ThreadBoxRepository,St as ThreadRepository,Dt as ToolCallRepository,Et as WorkspaceRepository,k as openDrizzleDb,Pe as pushSchema,J as runMigrations,O as runMigrationsOnce};