@crewx/sdk 0.8.7-rc.26 → 0.8.7-rc.27

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.
@@ -5,7 +5,7 @@ ${n.join(`
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:r?.count??0}}catch(r){throw new a("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(p).where(eq(p.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 r=e?and(eq(p.slug,t),ne$1(p.id,e)):eq(p.slug,t);return !!n.db.select({id:p.id}).from(p).where(r).limit(1).get()}catch(r){throw new a("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(p).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(p).where(eq(p.id,t)).limit(1).get();if(!l)throw new a("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof a?i:new a("DB_ERROR","Failed to insert workspace",i)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(p).where(eq(p.id,t)).limit(1).get();if(!s)throw new a("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:p.id,workspace_path:p.workspace_path}).from(p).where(and(eq(p.is_active,1),isNotNull(p.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(p).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(p.id,r.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(p).where(eq(p.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Lt=[p,o,c,F,v,A,Y];function xe(){return K__default.join(Qt.homedir(),".crewx","crewx.db")}function De(d){if(!vt.existsSync(d))return null;let t=Math.floor(Date.now()/1e3),e=`${d}.bak-${t}`;return vt.copyFileSync(d,e),e}function qt(d){let t=d.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Se(d){return d==null||typeof d=="object"&&"queryChunks"in d?null:typeof d=="number"?String(d):typeof d=="boolean"?d?"1":"0":typeof d=="string"?`'${d.replace(/'/g,"''")}'`:String(d)}function Te(d){let t=d.getSQLType(),e=`"${d.name}" ${t}`,n=Se(d.default);return n!==null&&(e+=` DEFAULT ${n}`),d.notNull&&(e+=" NOT NULL"),e}function Oe(d,t){let e=t?.dbPath??xe(),n=t?.force??false,r=t?.dryRun??false,s=r?null:De(e);if(n&&!r)try{d.run("DELETE FROM __drizzle_migrations");}catch{}let i=qt(d);r||W(d);let l,u;r?(l=Lt.map(R=>getTableConfig(R).name).filter(R=>!i.has(R)),u=i):(u=qt(d),l=[...u].filter(g=>!i.has(g)));let f=[],_=[];for(let g of Lt){let R=getTableConfig(g),T=R.name;if(!u.has(T))continue;let L=d.all(`PRAGMA table_info("${T}")`),dt=new Set(L.map(B=>B.name)),lt=new Set(R.columns.map(B=>B.name));for(let B of R.columns)if(!dt.has(B.name)){if(!r){let Wt=Te(B);d.run(`ALTER TABLE "${T}" ADD COLUMN ${Wt}`);}f.push({table:T,column:B.name});}for(let B of L)lt.has(B.name)||_.push(`${T}.${B.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:f,warnings:_,backupPath:s}}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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}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 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:r?.count??0}}catch(r){throw new a("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(p).where(eq(p.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 r=e?and(eq(p.slug,t),ne$1(p.id,e)):eq(p.slug,t);return !!n.db.select({id:p.id}).from(p).where(r).limit(1).get()}catch(r){throw new a("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(p).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(p).where(eq(p.id,t)).limit(1).get();if(!l)throw new a("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof a?i:new a("DB_ERROR","Failed to insert workspace",i)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(p).where(eq(p.id,t)).limit(1).get();if(!s)throw new a("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:p.id,workspace_path:p.workspace_path}).from(p).where(and(eq(p.is_active,1),isNotNull(p.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(p).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(p.id,r.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(p).where(eq(p.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Lt=[p,o,c,F,v,A,Y];function xe(){return K__default.join(Qt.homedir(),".crewx","crewx.db")}function De(d){if(!vt.existsSync(d))return null;let t=Math.floor(Date.now()/1e3),e=`${d}.bak-${t}`;return vt.copyFileSync(d,e),e}function qt(d){let t=d.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Se(d){return d==null||typeof d=="object"&&"queryChunks"in d?null:typeof d=="number"?String(d):typeof d=="boolean"?d?"1":"0":typeof d=="string"?`'${d.replace(/'/g,"''")}'`:String(d)}function Te(d){let t=d.getSQLType(),e=`"${d.name}" ${t}`,n=Se(d.default);return n!==null&&(e+=` DEFAULT ${n}`),d.notNull&&(e+=" NOT NULL"),e}function Oe(d,t){let e=t?.dbPath??xe(),n=t?.force??false,r=t?.dryRun??false,s=r?null:De(e);if(n&&!r)try{d.run("DELETE FROM __drizzle_migrations");}catch{}let i=qt(d);if(!r)try{W(d);}catch(m){let R=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!R.includes("duplicate column"))throw m}let l,u;r?(l=Lt.map(R=>getTableConfig(R).name).filter(R=>!i.has(R)),u=i):(u=qt(d),l=[...u].filter(m=>!i.has(m)));let f=[],_=[];for(let m of Lt){let R=getTableConfig(m),T=R.name;if(!u.has(T))continue;let L=d.all(`PRAGMA table_info("${T}")`),dt=new Set(L.map(B=>B.name)),lt=new Set(R.columns.map(B=>B.name));for(let B of R.columns)if(!dt.has(B.name)){if(!r){let Wt=Te(B);d.run(`ALTER TABLE "${T}" ADD COLUMN ${Wt}`);}f.push({table:T,column:B.name});}for(let B of L)lt.has(B.name)||_.push(`${T}.${B.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:f,warnings:_,backupPath:s}}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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}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 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
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(r=>{let s=r.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(e),r.update(o).set({logs:JSON.stringify(i)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to append log",r)}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 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(o).orderBy(desc(o.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(o).where(eq(o.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: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 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:o.id,pid:o.pid}).from(o).where(eq(o.status,"running")).all(),n=0;for(let r of e){let s=!1;if(r.pid)try{process.kill(r.pid,0),s=!0;}catch{}s||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,r.id),eq(o.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let i=e?eq(o.workspace_id,e):void 0,l=i?and(eq(o.id,t),i):eq(o.id,t),u=s.db.select().from(o).where(l).limit(1).get()??void 0;if(!u){let f=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),_=i?and(f,i):f;u=s.db.select().from(o).where(_).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(u)return u}catch(i){throw new a("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=w(i);try{let u=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),f=l.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let _ of f)r.has(_.id)||(r.add(_.id),s.push(_));}catch(u){throw new a("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
11
11
  SELECT
@@ -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(),r=new Set,s=0,i=0,l=0;for(let u of n){if(!existsSync(u))continue;let f=w(u);try{let _=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),g=e?and(_,eq(o.workspace_id,e)):_,R=f.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(g).all();for(let T of R)r.has(T.id)||(r.add(T.id),s+=T.input_tokens??0,i+=T.output_tokens??0,l+=T.cost_usd??0);}catch(_){throw new a("DB_ERROR","Failed to get thread token usage",_)}finally{f.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=w(i);try{let u=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),f=e?and(u,eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(asc(o.started_at)).all();for(let g of _)r.has(g.id)||(r.add(g.id),s.push(g));}catch(u){throw new a("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}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 r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(inArray(o.status,s));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(),f=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(l).orderBy(f).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 r=this.openHandle(false);try{return r.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(),r=new Set,s=0,i=0,l=0;for(let u of n){if(!existsSync(u))continue;let f=w(u);try{let _=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),m=e?and(_,eq(o.workspace_id,e)):_,R=f.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 T of R)r.has(T.id)||(r.add(T.id),s+=T.input_tokens??0,i+=T.output_tokens??0,l+=T.cost_usd??0);}catch(_){throw new a("DB_ERROR","Failed to get thread token usage",_)}finally{f.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=w(i);try{let u=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),f=e?and(u,eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(asc(o.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new a("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}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 r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(inArray(o.status,s));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(),f=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(l).orderBy(f).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 r=this.openHandle(false);try{return r.db.all(n?sql`
32
32
  SELECT
33
33
  t.agent_id,
34
34
  t.workspace_id,
@@ -88,13 +88,13 @@ ${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(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(s){throw new a("DB_ERROR","Failed to get agent usage trend",s)}finally{r.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(r){throw new a("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=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"));r.db.update(o).set({status:"failed",error:e,completed_at:s}).where(i).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=w(i);try{let u=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),f=l.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let _ of f)r.has(_.id)||(r.add(_.id),s.push(_));}catch(u){throw new a("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}};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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!existsSync(s))continue;let i=w(s);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 f of u)n.has(f.id)||(n.add(f.id),r.push(f));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let i=eq(c.id,t),l=e?and(i,eq(c.workspace_id,e)):i,u=s.db.select().from(c).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new a("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let i=eq(c.id,t),l=e?and(i,eq(c.workspace_id,e)):i;if(s.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(i){throw new a("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,i=0,l=0,u=0,f=new Set;for(let _ of n){if(!existsSync(_))continue;let g=w(_);try{let R=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),T=e?and(R,eq(o.workspace_id,e)):R,L=g.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(T).get();L&&(r+=L.cnt,s+=L.total_input,i+=L.total_output,l+=L.total_cached,u+=L.total_cost);let dt=g.db.all(sql`
91
+ `).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(s){throw new a("DB_ERROR","Failed to get agent usage trend",s)}finally{r.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(r){throw new a("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=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"));r.db.update(o).set({status:"failed",error:e,completed_at:s}).where(i).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=w(i);try{let u=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),f=l.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let _ of f)r.has(_.id)||(r.add(_.id),s.push(_));}catch(u){throw new a("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}};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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!existsSync(s))continue;let i=w(s);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 f of u)n.has(f.id)||(n.add(f.id),r.push(f));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let i=eq(c.id,t),l=e?and(i,eq(c.workspace_id,e)):i,u=s.db.select().from(c).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new a("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let i=eq(c.id,t),l=e?and(i,eq(c.workspace_id,e)):i;if(s.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(i){throw new a("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,i=0,l=0,u=0,f=new Set;for(let _ of n){if(!existsSync(_))continue;let m=w(_);try{let R=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),T=e?and(R,eq(o.workspace_id,e)):R,L=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(o).where(T).get();L&&(r+=L.cnt,s+=L.total_input,i+=L.total_output,l+=L.total_cached,u+=L.total_cost);let dt=m.db.all(sql`
92
92
  SELECT DISTINCT agent_id FROM tasks
93
93
  WHERE thread_id = ${t}
94
94
  AND agent_id IS NOT NULL AND agent_id != ''
95
95
  AND (parent_task_id IS NULL OR parent_task_id = '')
96
96
  ${e?sql`AND workspace_id = ${e}`:sql``}
97
- `);for(let lt of dt)f.add(lt.agent_id);}catch(R){throw new a("DB_ERROR","Failed to aggregate task stats",R)}finally{g.close();}}return {taskCount:r,inputTokens:s,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(f)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=w(i);try{let u=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),f=e?and(u,eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(asc(o.started_at)).all();for(let g of _)r.has(g.id)||(r.add(g.id),s.push(g));}catch(u){throw new a("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return s}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=w(i);try{let u=eq(o.thread_id,t),f=e?and(u,eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(asc(o.started_at)).all();for(let g of _)r.has(g.id)||(r.add(g.id),s.push(g));}catch(u){throw new a("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=w(s);try{let l=and(eq(o.id,e),eq(o.thread_id,t)),u=n?and(l,eq(o.workspace_id,n)):l,f=i.db.select().from(o).where(u).limit(1).get();if(!f)continue;let _=i.db.select().from(o).where(eq(o.parent_task_id,f.id)).orderBy(asc(o.started_at)).all();return {task:f,children:_}}catch(l){throw new a("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 r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=w(s);try{let l=and(inArray(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),u=e?and(l,eq(o.workspace_id,e)):l,f=i.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let _ of f){let g=_.thread_id;n.has(g)||n.set(g,[]),n.get(g).push(_);}}catch(l){throw new a("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=eq(c.id,t),i=n?and(s,eq(c.workspace_id,n)):s;if(!r.db.select({id:c.id}).from(c).where(i).limit(1).get())return;r.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,s=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:s};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:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let s=n?this.validateWorkspaceId(r,n):null,i=r.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){s&&!i.workspace_id&&r.db.update(c).set({workspace_id:s}).where(eq(c.id,t)).run();return}let l=new Date().toISOString();r.db.insert(c).values({id:t,platform:e,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.run(sql`
97
+ `);for(let lt of dt)f.add(lt.agent_id);}catch(R){throw new a("DB_ERROR","Failed to aggregate task stats",R)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(f)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=w(i);try{let u=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),f=e?and(u,eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(asc(o.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new a("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return s}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=w(i);try{let u=eq(o.thread_id,t),f=e?and(u,eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(asc(o.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new a("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=w(s);try{let l=and(eq(o.id,e),eq(o.thread_id,t)),u=n?and(l,eq(o.workspace_id,n)):l,f=i.db.select().from(o).where(u).limit(1).get();if(!f)continue;let _=i.db.select().from(o).where(eq(o.parent_task_id,f.id)).orderBy(asc(o.started_at)).all();return {task:f,children:_}}catch(l){throw new a("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 r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=w(s);try{let l=and(inArray(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),u=e?and(l,eq(o.workspace_id,e)):l,f=i.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let _ of f){let m=_.thread_id;n.has(m)||n.set(m,[]),n.get(m).push(_);}}catch(l){throw new a("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=eq(c.id,t),i=n?and(s,eq(c.workspace_id,n)):s;if(!r.db.select({id:c.id}).from(c).where(i).limit(1).get())return;r.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,s=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:s};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:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let s=n?this.validateWorkspaceId(r,n):null,i=r.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){s&&!i.workspace_id&&r.db.update(c).set({workspace_id:s}).where(eq(c.id,t)).run();return}let l=new Date().toISOString();r.db.insert(c).values({id:t,platform:e,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.run(sql`
98
98
  UPDATE threads
99
99
  SET first_message = COALESCE(first_message, ${e}),
100
100
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -102,4 +102,4 @@ ${n.join(`
102
102
  message_count = message_count + 1,
103
103
  updated_at = ${s}
104
104
  WHERE id = ${t}
105
- `);}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(c).set({last_message:e,updated_at:s}).where(eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(c).set(r).where(eq(c.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),s=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=e?and(eq(c.pinned,1),eq(c.workspace_id,e)):eq(c.pinned,1),f=n.db.select({metadata:c.metadata}).from(c).where(u).all(),_=0;for(let g of f){let R=g.metadata?JSON.parse(g.metadata):{};typeof R.pinOrder=="number"&&R.pinOrder>_&&(_=R.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?and(eq(c.id,t[r]),eq(c.workspace_id,e)):eq(c.id,t[r]),i=n.db.select({metadata:c.metadata}).from(c).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),s=n.db.select({starred:c.starred}).from(c).where(r).get();if(!s)return null;let i=s.starred?0:1;return n.db.update(c).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to toggle star",r)}finally{n.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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(F).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(F).where(eq(F.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(F).where(eq(F.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 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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}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 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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}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(A).where(eq(A.thread_id,t)).orderBy(asc(A.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(A).where(and(eq(A.id,e),eq(A.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(A).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new a("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(A).where(eq(A.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 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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(Y).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.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{E as BaseSqliteRepository,a as RepositoryError,xt as RequestLogRepository,yt as SpanRepository,gt as TaskRepository,Et as ThreadBoxRepository,bt as ThreadRepository,Rt as ToolCallRepository,ht as WorkspaceRepository,w as openDrizzleDb,Oe as pushSchema,W as runMigrations,O as runMigrationsOnce};
105
+ `);}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(c).set({last_message:e,updated_at:s}).where(eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(c).set(r).where(eq(c.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),s=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=e?and(eq(c.pinned,1),eq(c.workspace_id,e)):eq(c.pinned,1),f=n.db.select({metadata:c.metadata}).from(c).where(u).all(),_=0;for(let m of f){let R=m.metadata?JSON.parse(m.metadata):{};typeof R.pinOrder=="number"&&R.pinOrder>_&&(_=R.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?and(eq(c.id,t[r]),eq(c.workspace_id,e)):eq(c.id,t[r]),i=n.db.select({metadata:c.metadata}).from(c).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),s=n.db.select({starred:c.starred}).from(c).where(r).get();if(!s)return null;let i=s.starred?0:1;return n.db.update(c).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to toggle star",r)}finally{n.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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(F).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(F).where(eq(F.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(F).where(eq(F.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 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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}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 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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}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(A).where(eq(A.thread_id,t)).orderBy(asc(A.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(A).where(and(eq(A.id,e),eq(A.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(A).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new a("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(A).where(eq(A.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 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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(Y).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.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{E as BaseSqliteRepository,a as RepositoryError,xt as RequestLogRepository,yt as SpanRepository,gt as TaskRepository,Et as ThreadBoxRepository,bt as ThreadRepository,Rt as ToolCallRepository,ht as WorkspaceRepository,w as openDrizzleDb,Oe as pushSchema,W as runMigrations,O as runMigrationsOnce};
@@ -5,7 +5,7 @@ ${n.join(`
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:r?.count??0}}catch(r){throw new a("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(p).where(drizzleOrm.eq(p.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 r=e?drizzleOrm.and(drizzleOrm.eq(p.slug,t),drizzleOrm.ne(p.id,e)):drizzleOrm.eq(p.slug,t);return !!n.db.select({id:p.id}).from(p).where(r).limit(1).get()}catch(r){throw new a("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(p).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get();if(!l)throw new a("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof a?i:new a("DB_ERROR","Failed to insert workspace",i)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get();if(!s)throw new a("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:p.id,workspace_path:p.workspace_path}).from(p).where(drizzleOrm.and(drizzleOrm.eq(p.is_active,1),drizzleOrm.isNotNull(p.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;Bt.existsSync(G.join(s,"crewx.yaml"))||Bt.existsSync(G.join(s,"crewx.yml"))||(t.db.update(p).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(p.id,r.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(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(p).where(drizzleOrm.eq(p.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var zt=[p,o,c,q,B,N,X];function ke(){return G__namespace.default.join(Yt__default.default.homedir(),".crewx","crewx.db")}function be(d){if(!Bt__default.default.existsSync(d))return null;let t=Math.floor(Date.now()/1e3),e=`${d}.bak-${t}`;return Bt__default.default.copyFileSync(d,e),e}function Lt(d){let t=d.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function ye(d){return d==null||typeof d=="object"&&"queryChunks"in d?null:typeof d=="number"?String(d):typeof d=="boolean"?d?"1":"0":typeof d=="string"?`'${d.replace(/'/g,"''")}'`:String(d)}function Re(d){let t=d.getSQLType(),e=`"${d.name}" ${t}`,n=ye(d.default);return n!==null&&(e+=` DEFAULT ${n}`),d.notNull&&(e+=" NOT NULL"),e}function Ee(d,t){let e=t?.dbPath??ke(),n=t?.force??false,r=t?.dryRun??false,s=r?null:be(e);if(n&&!r)try{d.run("DELETE FROM __drizzle_migrations");}catch{}let i=Lt(d);r||j(d);let l,u;r?(l=zt.map(y=>sqliteCore.getTableConfig(y).name).filter(y=>!i.has(y)),u=i):(u=Lt(d),l=[...u].filter(w=>!i.has(w)));let f=[],_=[];for(let w of zt){let y=sqliteCore.getTableConfig(w),S=y.name;if(!u.has(S))continue;let z=d.all(`PRAGMA table_info("${S}")`),at=new Set(z.map(A=>A.name)),dt=new Set(y.columns.map(A=>A.name));for(let A of y.columns)if(!at.has(A.name)){if(!r){let jt=Re(A);d.run(`ALTER TABLE "${S}" ADD COLUMN ${jt}`);}f.push({table:S,column:A.name});}for(let A of z)dt.has(A.name)||_.push(`${S}.${A.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:f,warnings:_,backupPath:s}}var mt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}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 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:r?.count??0}}catch(r){throw new a("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(p).where(drizzleOrm.eq(p.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 r=e?drizzleOrm.and(drizzleOrm.eq(p.slug,t),drizzleOrm.ne(p.id,e)):drizzleOrm.eq(p.slug,t);return !!n.db.select({id:p.id}).from(p).where(r).limit(1).get()}catch(r){throw new a("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(p).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get();if(!l)throw new a("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof a?i:new a("DB_ERROR","Failed to insert workspace",i)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get();if(!s)throw new a("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:p.id,workspace_path:p.workspace_path}).from(p).where(drizzleOrm.and(drizzleOrm.eq(p.is_active,1),drizzleOrm.isNotNull(p.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;Bt.existsSync(G.join(s,"crewx.yaml"))||Bt.existsSync(G.join(s,"crewx.yml"))||(t.db.update(p).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(p.id,r.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(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(p).where(drizzleOrm.eq(p.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var zt=[p,o,c,q,B,N,X];function ke(){return G__namespace.default.join(Yt__default.default.homedir(),".crewx","crewx.db")}function be(d){if(!Bt__default.default.existsSync(d))return null;let t=Math.floor(Date.now()/1e3),e=`${d}.bak-${t}`;return Bt__default.default.copyFileSync(d,e),e}function Lt(d){let t=d.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function ye(d){return d==null||typeof d=="object"&&"queryChunks"in d?null:typeof d=="number"?String(d):typeof d=="boolean"?d?"1":"0":typeof d=="string"?`'${d.replace(/'/g,"''")}'`:String(d)}function Re(d){let t=d.getSQLType(),e=`"${d.name}" ${t}`,n=ye(d.default);return n!==null&&(e+=` DEFAULT ${n}`),d.notNull&&(e+=" NOT NULL"),e}function Ee(d,t){let e=t?.dbPath??ke(),n=t?.force??false,r=t?.dryRun??false,s=r?null:be(e);if(n&&!r)try{d.run("DELETE FROM __drizzle_migrations");}catch{}let i=Lt(d);if(!r)try{j(d);}catch(m){let y=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!y.includes("duplicate column"))throw m}let l,u;r?(l=zt.map(y=>sqliteCore.getTableConfig(y).name).filter(y=>!i.has(y)),u=i):(u=Lt(d),l=[...u].filter(m=>!i.has(m)));let f=[],_=[];for(let m of zt){let y=sqliteCore.getTableConfig(m),S=y.name;if(!u.has(S))continue;let z=d.all(`PRAGMA table_info("${S}")`),at=new Set(z.map(A=>A.name)),dt=new Set(y.columns.map(A=>A.name));for(let A of y.columns)if(!at.has(A.name)){if(!r){let jt=Re(A);d.run(`ALTER TABLE "${S}" ADD COLUMN ${jt}`);}f.push({table:S,column:A.name});}for(let A of z)dt.has(A.name)||_.push(`${S}.${A.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:f,warnings:_,backupPath:s}}var mt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}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 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
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(r=>{let s=r.select({logs:o.logs}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(e),r.update(o).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.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(o).orderBy(drizzleOrm.desc(o.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(o).where(drizzleOrm.eq(o.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:o.id,status:o.status,pid:o.pid}).from(o).where(drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.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:o.id,pid:o.pid}).from(o).where(drizzleOrm.eq(o.status,"running")).all(),n=0;for(let r of e){let s=!1;if(r.pid)try{process.kill(r.pid,0),s=!0;}catch{}s||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,r.id),drizzleOrm.eq(o.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Bt.existsSync(r))continue;let s=g(r);try{let i=e?drizzleOrm.eq(o.workspace_id,e):void 0,l=i?drizzleOrm.and(drizzleOrm.eq(o.id,t),i):drizzleOrm.eq(o.id,t),u=s.db.select().from(o).where(l).limit(1).get()??void 0;if(!u){let f=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),_=i?drizzleOrm.and(f,i):f;u=s.db.select().from(o).where(_).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??void 0;}if(u)return u}catch(i){throw new a("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=g(i);try{let u=e?drizzleOrm.and(drizzleOrm.eq(o.parent_task_id,t),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.eq(o.parent_task_id,t),f=l.db.select().from(o).where(u).orderBy(drizzleOrm.asc(o.started_at)).all();for(let _ of f)r.has(_.id)||(r.add(_.id),s.push(_));}catch(u){throw new a("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
11
11
  SELECT
@@ -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(),r=new Set,s=0,i=0,l=0;for(let u of n){if(!Bt.existsSync(u))continue;let f=g(u);try{let _=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),w=e?drizzleOrm.and(_,drizzleOrm.eq(o.workspace_id,e)):_,y=f.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(w).all();for(let S of y)r.has(S.id)||(r.add(S.id),s+=S.input_tokens??0,i+=S.output_tokens??0,l+=S.cost_usd??0);}catch(_){throw new a("DB_ERROR","Failed to get thread token usage",_)}finally{f.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=g(i);try{let u=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),f=e?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(drizzleOrm.asc(o.started_at)).all();for(let w of _)r.has(w.id)||(r.add(w.id),s.push(w));}catch(u){throw new a("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(drizzleOrm.eq(o.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(drizzleOrm.inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(drizzleOrm.inArray(o.status,s));let i=t.q??t.search;i&&n.push(drizzleOrm.like(o.prompt,`%${i}%`)),t.from&&n.push(drizzleOrm.gte(o.started_at,t.from)),t.to&&n.push(drizzleOrm.lt(o.started_at,t.to));let l=n.length>0?drizzleOrm.and(...n):void 0,u=e.db.select({count:drizzleOrm.sql`count(*)`}).from(o).where(l).get(),f=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(o.started_at):drizzleOrm.desc(o.started_at);return {rows:e.db.select().from(o).where(l).orderBy(f).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 r=this.openHandle(false);try{return r.db.all(n?drizzleOrm.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(),r=new Set,s=0,i=0,l=0;for(let u of n){if(!Bt.existsSync(u))continue;let f=g(u);try{let _=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),m=e?drizzleOrm.and(_,drizzleOrm.eq(o.workspace_id,e)):_,y=f.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 S of y)r.has(S.id)||(r.add(S.id),s+=S.input_tokens??0,i+=S.output_tokens??0,l+=S.cost_usd??0);}catch(_){throw new a("DB_ERROR","Failed to get thread token usage",_)}finally{f.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=g(i);try{let u=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),f=e?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(drizzleOrm.asc(o.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new a("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(drizzleOrm.eq(o.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(drizzleOrm.inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(drizzleOrm.inArray(o.status,s));let i=t.q??t.search;i&&n.push(drizzleOrm.like(o.prompt,`%${i}%`)),t.from&&n.push(drizzleOrm.gte(o.started_at,t.from)),t.to&&n.push(drizzleOrm.lt(o.started_at,t.to));let l=n.length>0?drizzleOrm.and(...n):void 0,u=e.db.select({count:drizzleOrm.sql`count(*)`}).from(o).where(l).get(),f=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(o.started_at):drizzleOrm.desc(o.started_at);return {rows:e.db.select().from(o).where(l).orderBy(f).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 r=this.openHandle(false);try{return r.db.all(n?drizzleOrm.sql`
32
32
  SELECT
33
33
  t.agent_id,
34
34
  t.workspace_id,
@@ -88,13 +88,13 @@ ${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(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(s){throw new a("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new a("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),i=n?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));r.db.update(o).set({status:"failed",error:e,completed_at:s}).where(i).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=g(i);try{let u=e?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.like(o.prompt,`%${t}%`),f=l.db.select().from(o).where(u).orderBy(drizzleOrm.asc(o.started_at)).all();for(let _ of f)r.has(_.id)||(r.add(_.id),s.push(_));}catch(u){throw new a("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}};var kt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!Bt.existsSync(s))continue;let i=g(s);try{let l=t?drizzleOrm.eq(c.workspace_id,t):void 0,u=i.db.select().from(c).where(l).orderBy(drizzleOrm.desc(c.updated_at)).all();for(let f of u)n.has(f.id)||(n.add(f.id),r.push(f));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Bt.existsSync(r))continue;let s=g(r);try{let i=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(i,drizzleOrm.eq(c.workspace_id,e)):i,u=s.db.select().from(c).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new a("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Bt.existsSync(r))continue;let s=g(r);try{let i=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(i,drizzleOrm.eq(c.workspace_id,e)):i;if(s.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(i){throw new a("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,i=0,l=0,u=0,f=new Set;for(let _ of n){if(!Bt.existsSync(_))continue;let w=g(_);try{let y=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),S=e?drizzleOrm.and(y,drizzleOrm.eq(o.workspace_id,e)):y,z=w.db.select({cnt:drizzleOrm.sql`count(*)`,total_input:drizzleOrm.sql`COALESCE(SUM(input_tokens), 0)`,total_output:drizzleOrm.sql`COALESCE(SUM(output_tokens), 0)`,total_cached:drizzleOrm.sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:drizzleOrm.sql`COALESCE(SUM(cost_usd), 0)`}).from(o).where(S).get();z&&(r+=z.cnt,s+=z.total_input,i+=z.total_output,l+=z.total_cached,u+=z.total_cost);let at=w.db.all(drizzleOrm.sql`
91
+ `).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(s){throw new a("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new a("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),i=n?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));r.db.update(o).set({status:"failed",error:e,completed_at:s}).where(i).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=g(i);try{let u=e?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.like(o.prompt,`%${t}%`),f=l.db.select().from(o).where(u).orderBy(drizzleOrm.asc(o.started_at)).all();for(let _ of f)r.has(_.id)||(r.add(_.id),s.push(_));}catch(u){throw new a("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}};var kt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!Bt.existsSync(s))continue;let i=g(s);try{let l=t?drizzleOrm.eq(c.workspace_id,t):void 0,u=i.db.select().from(c).where(l).orderBy(drizzleOrm.desc(c.updated_at)).all();for(let f of u)n.has(f.id)||(n.add(f.id),r.push(f));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Bt.existsSync(r))continue;let s=g(r);try{let i=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(i,drizzleOrm.eq(c.workspace_id,e)):i,u=s.db.select().from(c).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new a("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Bt.existsSync(r))continue;let s=g(r);try{let i=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(i,drizzleOrm.eq(c.workspace_id,e)):i;if(s.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(i){throw new a("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,i=0,l=0,u=0,f=new Set;for(let _ of n){if(!Bt.existsSync(_))continue;let m=g(_);try{let y=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),S=e?drizzleOrm.and(y,drizzleOrm.eq(o.workspace_id,e)):y,z=m.db.select({cnt:drizzleOrm.sql`count(*)`,total_input:drizzleOrm.sql`COALESCE(SUM(input_tokens), 0)`,total_output:drizzleOrm.sql`COALESCE(SUM(output_tokens), 0)`,total_cached:drizzleOrm.sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:drizzleOrm.sql`COALESCE(SUM(cost_usd), 0)`}).from(o).where(S).get();z&&(r+=z.cnt,s+=z.total_input,i+=z.total_output,l+=z.total_cached,u+=z.total_cost);let at=m.db.all(drizzleOrm.sql`
92
92
  SELECT DISTINCT agent_id FROM tasks
93
93
  WHERE thread_id = ${t}
94
94
  AND agent_id IS NOT NULL AND agent_id != ''
95
95
  AND (parent_task_id IS NULL OR parent_task_id = '')
96
96
  ${e?drizzleOrm.sql`AND workspace_id = ${e}`:drizzleOrm.sql``}
97
- `);for(let dt of at)f.add(dt.agent_id);}catch(y){throw new a("DB_ERROR","Failed to aggregate task stats",y)}finally{w.close();}}return {taskCount:r,inputTokens:s,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(f)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=g(i);try{let u=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),f=e?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(drizzleOrm.asc(o.started_at)).all();for(let w of _)r.has(w.id)||(r.add(w.id),s.push(w));}catch(u){throw new a("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return s}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=g(i);try{let u=drizzleOrm.eq(o.thread_id,t),f=e?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(drizzleOrm.asc(o.started_at)).all();for(let w of _)r.has(w.id)||(r.add(w.id),s.push(w));}catch(u){throw new a("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!Bt.existsSync(s))continue;let i=g(s);try{let l=drizzleOrm.and(drizzleOrm.eq(o.id,e),drizzleOrm.eq(o.thread_id,t)),u=n?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,n)):l,f=i.db.select().from(o).where(u).limit(1).get();if(!f)continue;let _=i.db.select().from(o).where(drizzleOrm.eq(o.parent_task_id,f.id)).orderBy(drizzleOrm.asc(o.started_at)).all();return {task:f,children:_}}catch(l){throw new a("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 r=this.resolveDbPaths();for(let s of r){if(!Bt.existsSync(s))continue;let i=g(s);try{let l=drizzleOrm.and(drizzleOrm.inArray(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),u=e?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,e)):l,f=i.db.select().from(o).where(u).orderBy(drizzleOrm.asc(o.started_at)).all();for(let _ of f){let w=_.thread_id;n.has(w)||n.set(w,[]),n.get(w).push(_);}}catch(l){throw new a("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=drizzleOrm.eq(c.id,t),i=n?drizzleOrm.and(s,drizzleOrm.eq(c.workspace_id,n)):s;if(!r.db.select({id:c.id}).from(c).where(i).limit(1).get())return;r.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,s=new Date().toISOString();if(n.db.select({id:c.id,message_count:c.message_count}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get()){let l={updated_at:s};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(drizzleOrm.eq(c.id,t)).run();}else n.db.insert(c).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let s=n?this.validateWorkspaceId(r,n):null,i=r.db.select({id:c.id,platform:c.platform,workspace_id:c.workspace_id}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get();if(i){s&&!i.workspace_id&&r.db.update(c).set({workspace_id:s}).where(drizzleOrm.eq(c.id,t)).run();return}let l=new Date().toISOString();r.db.insert(c).values({id:t,platform:e,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.run(drizzleOrm.sql`
97
+ `);for(let dt of at)f.add(dt.agent_id);}catch(y){throw new a("DB_ERROR","Failed to aggregate task stats",y)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(f)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=g(i);try{let u=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),f=e?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(drizzleOrm.asc(o.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new a("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return s}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=g(i);try{let u=drizzleOrm.eq(o.thread_id,t),f=e?drizzleOrm.and(u,drizzleOrm.eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(f).orderBy(drizzleOrm.asc(o.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new a("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!Bt.existsSync(s))continue;let i=g(s);try{let l=drizzleOrm.and(drizzleOrm.eq(o.id,e),drizzleOrm.eq(o.thread_id,t)),u=n?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,n)):l,f=i.db.select().from(o).where(u).limit(1).get();if(!f)continue;let _=i.db.select().from(o).where(drizzleOrm.eq(o.parent_task_id,f.id)).orderBy(drizzleOrm.asc(o.started_at)).all();return {task:f,children:_}}catch(l){throw new a("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 r=this.resolveDbPaths();for(let s of r){if(!Bt.existsSync(s))continue;let i=g(s);try{let l=drizzleOrm.and(drizzleOrm.inArray(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),u=e?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,e)):l,f=i.db.select().from(o).where(u).orderBy(drizzleOrm.asc(o.started_at)).all();for(let _ of f){let m=_.thread_id;n.has(m)||n.set(m,[]),n.get(m).push(_);}}catch(l){throw new a("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=drizzleOrm.eq(c.id,t),i=n?drizzleOrm.and(s,drizzleOrm.eq(c.workspace_id,n)):s;if(!r.db.select({id:c.id}).from(c).where(i).limit(1).get())return;r.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,s=new Date().toISOString();if(n.db.select({id:c.id,message_count:c.message_count}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get()){let l={updated_at:s};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(drizzleOrm.eq(c.id,t)).run();}else n.db.insert(c).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let s=n?this.validateWorkspaceId(r,n):null,i=r.db.select({id:c.id,platform:c.platform,workspace_id:c.workspace_id}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get();if(i){s&&!i.workspace_id&&r.db.update(c).set({workspace_id:s}).where(drizzleOrm.eq(c.id,t)).run();return}let l=new Date().toISOString();r.db.insert(c).values({id:t,platform:e,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.run(drizzleOrm.sql`
98
98
  UPDATE threads
99
99
  SET first_message = COALESCE(first_message, ${e}),
100
100
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -102,4 +102,4 @@ ${n.join(`
102
102
  message_count = message_count + 1,
103
103
  updated_at = ${s}
104
104
  WHERE id = ${t}
105
- `);}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(c).set({last_message:e,updated_at:s}).where(drizzleOrm.eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(c).set(r).where(drizzleOrm.eq(c.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),s=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=e?drizzleOrm.and(drizzleOrm.eq(c.pinned,1),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.pinned,1),f=n.db.select({metadata:c.metadata}).from(c).where(u).all(),_=0;for(let w of f){let y=w.metadata?JSON.parse(w.metadata):{};typeof y.pinOrder=="number"&&y.pinOrder>_&&(_=y.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?drizzleOrm.and(drizzleOrm.eq(c.id,t[r]),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t[r]),i=n.db.select({metadata:c.metadata}).from(c).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),s=n.db.select({starred:c.starred}).from(c).where(r).get();if(!s)return null;let i=s.starred?0:1;return n.db.update(c).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}};var bt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}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(drizzleOrm.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(drizzleOrm.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 yt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}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(drizzleOrm.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:drizzleOrm.sql`count(*)`}).from(B).where(drizzleOrm.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 R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:c.id}).from(c).where(drizzleOrm.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(N).where(drizzleOrm.eq(N.thread_id,t)).orderBy(drizzleOrm.asc(N.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(N).where(drizzleOrm.and(drizzleOrm.eq(N.id,e),drizzleOrm.eq(N.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(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(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new a("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(N).where(drizzleOrm.eq(N.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 Et=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(X).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.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(X).orderBy(drizzleOrm.desc(X.timestamp)).limit(t).all()}catch(n){throw new a("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};exports.BaseSqliteRepository=R;exports.RepositoryError=a;exports.RequestLogRepository=Et;exports.SpanRepository=bt;exports.TaskRepository=mt;exports.ThreadBoxRepository=Rt;exports.ThreadRepository=kt;exports.ToolCallRepository=yt;exports.WorkspaceRepository=ft;exports.openDrizzleDb=g;exports.pushSchema=Ee;exports.runMigrations=j;exports.runMigrationsOnce=T;
105
+ `);}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(c).set({last_message:e,updated_at:s}).where(drizzleOrm.eq(c.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(c).set(r).where(drizzleOrm.eq(c.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),s=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=e?drizzleOrm.and(drizzleOrm.eq(c.pinned,1),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.pinned,1),f=n.db.select({metadata:c.metadata}).from(c).where(u).all(),_=0;for(let m of f){let y=m.metadata?JSON.parse(m.metadata):{};typeof y.pinOrder=="number"&&y.pinOrder>_&&(_=y.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?drizzleOrm.and(drizzleOrm.eq(c.id,t[r]),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t[r]),i=n.db.select({metadata:c.metadata}).from(c).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),s=n.db.select({starred:c.starred}).from(c).where(r).get();if(!s)return null;let i=s.starred?0:1;return n.db.update(c).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}};var bt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}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(drizzleOrm.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(drizzleOrm.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 yt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}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(drizzleOrm.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:drizzleOrm.sql`count(*)`}).from(B).where(drizzleOrm.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 R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:c.id}).from(c).where(drizzleOrm.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(N).where(drizzleOrm.eq(N.thread_id,t)).orderBy(drizzleOrm.asc(N.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(N).where(drizzleOrm.and(drizzleOrm.eq(N.id,e),drizzleOrm.eq(N.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(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(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new a("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(N).where(drizzleOrm.eq(N.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 Et=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=G.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=G.dirname(e);Bt.existsSync(r)||Bt.mkdirSync(r,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=g(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(X).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.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(X).orderBy(drizzleOrm.desc(X.timestamp)).limit(t).all()}catch(n){throw new a("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};exports.BaseSqliteRepository=R;exports.RepositoryError=a;exports.RequestLogRepository=Et;exports.SpanRepository=bt;exports.TaskRepository=mt;exports.ThreadBoxRepository=Rt;exports.ThreadRepository=kt;exports.ToolCallRepository=yt;exports.WorkspaceRepository=ft;exports.openDrizzleDb=g;exports.pushSchema=Ee;exports.runMigrations=j;exports.runMigrationsOnce=T;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewx/sdk",
3
- "version": "0.8.7-rc.26",
3
+ "version": "0.8.7-rc.27",
4
4
  "license": "UNLICENSED",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"