@crewx/sdk 0.8.6-rc.7 → 0.8.6-rc.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import*as et from'path';import et__default,{join,basename,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync}from'fs';import It,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,or,isNull,like,asc,inArray,gte,lt}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique}from'drizzle-orm/sqlite-core';var W=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var Rt=()=>fileURLToPath(import.meta.url),Tt=()=>et__default.dirname(Rt()),g=Tt();var O=class{detach(t){}};function dt(d){let t=e=>String(e).padStart(2,"0");return `${d.getFullYear()}${t(d.getMonth()+1)}${t(d.getDate())}T${t(d.getHours())}${t(d.getMinutes())}${t(d.getSeconds())}`}var tt=class extends O{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let s=dt(e.timestamp),n=join(this.logsDir,`${s}_${e.traceId}.log`);this.logFiles.set(e.traceId,n);let r=`=== TASK LOG: ${e.traceId} ===
1
+ import*as j from'path';import j__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync}from'fs';import It,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,or,isNull,like,asc,inArray,gte,lt}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique}from'drizzle-orm/sqlite-core';var W=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var Rt=()=>fileURLToPath(import.meta.url),Tt=()=>j__default.dirname(Rt()),g=Tt();var O=class{detach(t){}};function dt(d){let t=e=>String(e).padStart(2,"0");return `${d.getFullYear()}${t(d.getMonth()+1)}${t(d.getDate())}T${t(d.getHours())}${t(d.getMinutes())}${t(d.getSeconds())}`}var et=class extends O{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let s=dt(e.timestamp),n=join(this.logsDir,`${s}_${e.traceId}.log`);this.logFiles.set(e.traceId,n);let r=`=== TASK LOG: ${e.traceId} ===
2
2
  CrewX Version: ${this.version}
3
3
  Mode: ${e.mode}
4
4
  Agent: ${e.agentRef}
@@ -6,40 +6,37 @@ Started: ${e.timestamp.toLocaleString()}
6
6
  Message: ${e.message}
7
7
 
8
8
  `;writeFileSync(n,r,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toISOString();appendFileSync(s,`[${n}] STDOUT: ${e.output}
9
- `,"utf8");}catch{}}),t.on("task:end",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toLocaleString(),r=e.error?`failed: ${e.error.message}`:"completed successfully",i=`[${n}] INFO: Task ${r} in ${e.durationMs}ms
9
+ `,"utf8");}catch{}}),t.on("task:end",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toLocaleString(),r=e.error?`failed: ${e.error.message}`:"completed successfully",a=`[${n}] INFO: Task ${r} in ${e.durationMs}ms
10
10
  [${n}] INFO: Process closed with exit code: ${e.error?1:0}
11
- `;appendFileSync(s,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function vt(d){let t=et.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function pt(d){let t=vt(d);return createHash("sha256").update(t).digest("hex")}var B=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(It.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};function b(d){let t=W("better-sqlite3"),{drizzle:e}=W("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),{db:e(s),runRaw:(n,r=[])=>s.prepare(n).run(...r),close:()=>s.close()}}var _t=new Set;function Ut(d){let{migrate:t}=W("drizzle-orm/better-sqlite3/migrator"),{sql:e}=W("drizzle-orm"),s=[et__default.join(g,"../migrations"),et__default.join(g,"migrations")],n=s.find(p=>existsSync(et__default.join(p,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
11
+ `;appendFileSync(s,a,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function vt(d){let t=j.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function pt(d){let t=vt(d);return createHash("sha256").update(t).digest("hex")}var B=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(It.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};function b(d){let t=W("better-sqlite3"),{drizzle:e}=W("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),{db:e(s),runRaw:(n,r=[])=>s.prepare(n).run(...r),close:()=>s.close()}}var _t=new Set;function Ut(d){let{migrate:t}=W("drizzle-orm/better-sqlite3/migrator"),{sql:e}=W("drizzle-orm"),s=[j__default.join(g,"../migrations"),j__default.join(g,"migrations"),j__default.join(g,"../../../../drizzle/migrations"),j__default.join(process.cwd(),"drizzle/migrations")],n=s.find(p=>existsSync(j__default.join(p,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
12
12
  ${s.join(`
13
- `)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),t(d,{migrationsFolder:n});let a=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(a>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${a} migration${a>1?"s":""} applied).`);}}function j(d,t){_t.has(t)||(Ut(d),_t.add(t));}var c=class extends Error{code;cause;constructor(t,e,s){super(e),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var q=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),workspace_name:text("workspace_name"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_name:text("project_name"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var u=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>q.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var Wt=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Wt.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>u.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));var J=class extends B{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new c("NOT_FOUND","Database not found");let s=b(e);if(t)try{j(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(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,workspace_name:t.workspaceName??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
13
+ `)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;r?.cnt&&(a=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(l>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${l} migration${l>1?"s":""} applied).`);}}function G(d,t){_t.has(t)||(Ut(d),_t.add(t));}var c=class extends Error{code;cause;constructor(t,e,s){super(e),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var q=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var u=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>q.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var jt=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>jt.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>u.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));var V=class extends B{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new c("NOT_FOUND","Database not found");let s=b(e);if(t)try{G(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
14
14
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
15
- model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),n.update(o).set({logs:JSON.stringify(i)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof c?n:new c("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new c("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 c("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new c("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to kill task",s)}finally{e.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let i=e?eq(o.workspace_id,e):void 0,l=i?and(eq(o.id,t),i):eq(o.id,t),a=r.db.select().from(o).where(l).limit(1).get()??void 0;if(!a){let p=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),_=i?and(p,i):p;a=r.db.select().from(o).where(_).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(a)return a}catch(i){throw new c("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let l=b(i);try{let a=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),p=l.db.select().from(o).where(a).orderBy(asc(o.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(a){throw new c("DB_ERROR","Failed to find child tasks",a)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
15
+ model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),a=r?.logs?JSON.parse(r.logs):[];a.push(e),n.update(o).set({logs:JSON.stringify(a)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof c?n:new c("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new c("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 c("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new c("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to kill task",s)}finally{e.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let a=e?eq(o.workspace_id,e):void 0,i=a?and(eq(o.id,t),a):eq(o.id,t),l=r.db.select().from(o).where(i).limit(1).get()??void 0;if(!l){let p=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),_=a?and(p,a):p;l=r.db.select().from(o).where(_).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(l)return l}catch(a){throw new c("DB_ERROR","Failed to find task status",a)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let a of s){if(!existsSync(a))continue;let i=b(a);try{let l=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),p=i.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(l){throw new c("DB_ERROR","Failed to find child tasks",l)}finally{i.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
16
16
  SELECT
17
17
  COALESCE(workspace_id, 'unknown') AS workspace_id,
18
- COALESCE(workspace_name, 'Unknown Workspace') AS workspace_name,
19
18
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
20
19
  COALESCE(SUM(output_tokens), 0) AS output_tokens,
21
20
  COALESCE(SUM(cost_usd), 0) AS cost_usd,
22
21
  COUNT(*) AS task_count
23
22
  FROM tasks
24
23
  WHERE workspace_id = ${t}
25
- GROUP BY workspace_id, workspace_name
24
+ GROUP BY workspace_id
26
25
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
27
26
  `:sql`
28
27
  SELECT
29
28
  COALESCE(workspace_id, 'unknown') AS workspace_id,
30
- COALESCE(workspace_name, 'Unknown Workspace') AS workspace_name,
31
29
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
32
30
  COALESCE(SUM(output_tokens), 0) AS output_tokens,
33
31
  COALESCE(SUM(cost_usd), 0) AS cost_usd,
34
32
  COUNT(*) AS task_count
35
33
  FROM tasks
36
- GROUP BY workspace_id, workspace_name
34
+ GROUP BY workspace_id
37
35
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
38
- `)}catch(s){throw new c("DB_ERROR","Failed to get workspace usage summary",s)}finally{e.close();}}getThreadTokenUsage(t,e){let s=this.resolveDbPaths(),n=new Set,r=0,i=0,l=0;for(let a of s){if(!existsSync(a))continue;let p=b(a);try{let _=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),k=e?and(_,eq(o.workspace_id,e)):_,A=p.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(k).all();for(let P of A)n.has(P.id)||(n.add(P.id),r+=P.input_tokens??0,i+=P.output_tokens??0,l+=P.cost_usd??0);}catch(_){throw new c("DB_ERROR","Failed to get thread token usage",_)}finally{p.close();}}return {inputTokens:r,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let l=b(i);try{let a=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),p=e?and(a,eq(o.workspace_id,e)):a,_=l.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(a){throw new c("DB_ERROR","Failed to find tasks by thread",a)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(o.workspace_id,t.workspaceId));let n=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;n&&s.push(inArray(o.agent_id,n));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&s.push(inArray(o.status,r));let i=t.q??t.search;i&&s.push(like(o.prompt,`%${i}%`)),t.from&&s.push(gte(o.started_at,t.from)),t.to&&s.push(lt(o.started_at,t.to));let l=s.length>0?and(...s):void 0,a=e.db.select({count:sql`count(*)`}).from(o).where(l).get(),p=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(l).orderBy(p).limit(t.limit).offset(t.offset).all(),total:a?.count??0}}catch(s){throw new c("DB_ERROR","Failed to find all tasks",s)}finally{e.close();}}getAgentUsage(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
36
+ `)}catch(s){throw new c("DB_ERROR","Failed to get workspace usage summary",s)}finally{e.close();}}getThreadTokenUsage(t,e){let s=this.resolveDbPaths(),n=new Set,r=0,a=0,i=0;for(let l of s){if(!existsSync(l))continue;let p=b(l);try{let _=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),k=e?and(_,eq(o.workspace_id,e)):_,$=p.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(k).all();for(let v of $)n.has(v.id)||(n.add(v.id),r+=v.input_tokens??0,a+=v.output_tokens??0,i+=v.cost_usd??0);}catch(_){throw new c("DB_ERROR","Failed to get thread token usage",_)}finally{p.close();}}return {inputTokens:r,outputTokens:a,costUsd:i}}findTasksByThread(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let a of s){if(!existsSync(a))continue;let i=b(a);try{let l=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),p=e?and(l,eq(o.workspace_id,e)):l,_=i.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(l){throw new c("DB_ERROR","Failed to find tasks by thread",l)}finally{i.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(o.workspace_id,t.workspaceId));let n=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;n&&s.push(inArray(o.agent_id,n));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&s.push(inArray(o.status,r));let a=t.q??t.search;a&&s.push(like(o.prompt,`%${a}%`)),t.from&&s.push(gte(o.started_at,t.from)),t.to&&s.push(lt(o.started_at,t.to));let i=s.length>0?and(...s):void 0,l=e.db.select({count:sql`count(*)`}).from(o).where(i).get(),p=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(i).orderBy(p).limit(t.limit).offset(t.offset).all(),total:l?.count??0}}catch(s){throw new c("DB_ERROR","Failed to find all tasks",s)}finally{e.close();}}getAgentUsage(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
39
37
  SELECT
40
38
  t.agent_id,
41
39
  t.workspace_id,
42
- t.workspace_name,
43
40
  COUNT(*) AS total_tasks,
44
41
  COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
45
42
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
@@ -49,14 +46,13 @@ ${s.join(`
49
46
  WHERE t.status IN ('completed', 'success')
50
47
  AND t.started_at >= ${t}
51
48
  AND t.started_at < ${e}
52
- AND t.workspace_name = ${s}
53
- GROUP BY t.agent_id, t.workspace_id, t.workspace_name
49
+ AND t.workspace_id = ${s}
50
+ GROUP BY t.agent_id, t.workspace_id
54
51
  ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
55
52
  `:sql`
56
53
  SELECT
57
54
  t.agent_id,
58
55
  t.workspace_id,
59
- t.workspace_name,
60
56
  COUNT(*) AS total_tasks,
61
57
  COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
62
58
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
@@ -66,9 +62,9 @@ ${s.join(`
66
62
  WHERE t.status IN ('completed', 'success')
67
63
  AND t.started_at >= ${t}
68
64
  AND t.started_at < ${e}
69
- GROUP BY t.agent_id, t.workspace_id, t.workspace_name
65
+ GROUP BY t.agent_id, t.workspace_id
70
66
  ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
71
- `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,workspaceName:i.workspace_name??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new c("DB_ERROR","Failed to get agent usage",r)}finally{n.close();}}getAgentUsageTrendRaw(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
67
+ `).map(a=>({agentId:a.agent_id,workspaceId:a.workspace_id??null,totalTasks:a.total_tasks,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd}))}catch(r){throw new c("DB_ERROR","Failed to get agent usage",r)}finally{n.close();}}getAgentUsageTrendRaw(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
72
68
  SELECT
73
69
  date(t.started_at) AS date,
74
70
  t.agent_id,
@@ -80,7 +76,7 @@ ${s.join(`
80
76
  WHERE t.status IN ('completed', 'success')
81
77
  AND t.started_at >= ${t}
82
78
  AND t.started_at < ${e}
83
- AND t.workspace_name = ${s}
79
+ AND t.workspace_id = ${s}
84
80
  GROUP BY date(t.started_at), t.agent_id
85
81
  ORDER BY date(t.started_at) ASC
86
82
  `:sql`
@@ -97,13 +93,13 @@ ${s.join(`
97
93
  AND t.started_at < ${e}
98
94
  GROUP BY date(t.started_at), t.agent_id
99
95
  ORDER BY date(t.started_at) ASC
100
- `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new c("DB_ERROR","Failed to get agent usage trend",r)}finally{n.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(o).where(and(eq(o.id,t),eq(o.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new c("DB_ERROR","Failed to find task for stop",n)}finally{s.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString(),i=s?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,s)):and(eq(o.id,t),eq(o.status,"running"));n.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let l=b(i);try{let a=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),p=l.db.select().from(o).where(a).orderBy(asc(o.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(a){throw new c("DB_ERROR","Failed to find tasks by prompt hint",a)}finally{l.close();}}return r}};var it=class extends O{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new J({dbPath:this.dbPath}),s=process.cwd(),n=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml")),r=n?pt(s):null,i=n?basename(s):null,l=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let p=process.env.CREWX_CALLER_AGENT_ID||null,_=process.env.CREWX_PARENT_TASK_ID||null,k=process.env.CREWX_TRACE_ID||a.traceId,A=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});e.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:l,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??r,workspaceName:a.workspaceName??i,callerAgentId:p,parentTaskId:_,traceId:k,metadata:A,threadId:a.threadId??null});}catch{}}),t.on("task:output",a=>{try{e.appendLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch{}}),t.on("task:end",a=>{try{e.finishTask({id:a.traceId,status:a.error?"failed":"success",result:a.result??null,error:a.error?JSON.stringify(a.error):null,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var Q=class extends B{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new c("NOT_FOUND","Database not found");let s=b(e);if(t)try{j(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:q.id}).from(q).where(eq(q.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!existsSync(r))continue;let i=b(r);try{let l=t?or(eq(u.workspace_id,t),isNull(u.workspace_id)):void 0,a=i.db.select().from(u).where(l).orderBy(desc(u.updated_at)).all();for(let p of a)s.has(p.id)||(s.add(p.id),n.push(p));}catch(l){throw new c("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let i=eq(u.id,t),l=e?and(i,or(eq(u.workspace_id,e),isNull(u.workspace_id))):i,a=r.db.select().from(u).where(l).limit(1).get()??void 0;if(a)return a}catch(i){throw new c("DB_ERROR","Failed to find thread by id",i)}finally{r.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let i=eq(u.id,t),l=e?and(i,or(eq(u.workspace_id,e),isNull(u.workspace_id))):i;if(r.db.select({id:u.id}).from(u).where(l).limit(1).get())return !0}catch(i){throw new c("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),n=0,r=0,i=0,l=0,a=0,p=new Set;for(let _ of s){if(!existsSync(_))continue;let k=b(_);try{let A=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),P=e?and(A,eq(o.workspace_id,e)):A,F=k.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(P).get();F&&(n+=F.cnt,r+=F.total_input,i+=F.total_output,l+=F.total_cached,a+=F.total_cost);let yt=k.db.all(sql`
96
+ `).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd}))}catch(r){throw new c("DB_ERROR","Failed to get agent usage trend",r)}finally{n.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(o).where(and(eq(o.id,t),eq(o.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new c("DB_ERROR","Failed to find task for stop",n)}finally{s.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString(),a=s?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,s)):and(eq(o.id,t),eq(o.status,"running"));n.db.update(o).set({status:"failed",error:e,completed_at:r}).where(a).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let a of s){if(!existsSync(a))continue;let i=b(a);try{let l=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),p=i.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(l){throw new c("DB_ERROR","Failed to find tasks by prompt hint",l)}finally{i.close();}}return r}};var it=class extends O{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new V({dbPath:this.dbPath}),s=process.cwd(),r=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?pt(s):null,a=process.argv.join(" ");this.unsubs.push(t.on("task:start",i=>{try{let l=process.env.CREWX_CALLER_AGENT_ID||null,p=process.env.CREWX_PARENT_TASK_ID||null,_=process.env.CREWX_TRACE_ID||i.traceId,k=i.metadata?JSON.stringify(i.metadata):JSON.stringify({provider:i.provider??"cli/claude"});e.startTask({id:i.traceId,agentId:i.agentRef.replace(/^@/,""),prompt:i.message,mode:i.mode,status:"running",pid:i.pid??null,startedAt:i.timestamp.toISOString(),crewxVersion:this.version,platform:i.platform??"cli",model:i.model??null,renderedPrompt:i.renderedPrompt??null,command:a,codingAgentCommand:i.codingAgentCommand??null,workspaceId:i.workspaceId??r,callerAgentId:l,parentTaskId:p,traceId:_,metadata:k,threadId:i.threadId??null});}catch{}}),t.on("task:output",i=>{try{e.appendLog(i.traceId,{timestamp:i.timestamp.toISOString(),level:i.level??"stdout",message:i.output});}catch{}}),t.on("task:end",i=>{try{e.finishTask({id:i.traceId,status:i.error?"failed":"success",result:i.result??null,error:i.error?JSON.stringify(i.error):null,completedAt:i.timestamp.toISOString(),durationMs:i.durationMs,exitCode:i.exitCode??null,inputTokens:i.inputTokens??0,outputTokens:i.outputTokens??0,cachedInputTokens:i.cachedInputTokens??0,costUsd:i.costUsd??0,model:i.model??null});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var Z=class extends B{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new c("NOT_FOUND","Database not found");let s=b(e);if(t)try{G(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:q.id}).from(q).where(eq(q.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!existsSync(r))continue;let a=b(r);try{let i=t?or(eq(u.workspace_id,t),isNull(u.workspace_id)):void 0,l=a.db.select().from(u).where(i).orderBy(desc(u.updated_at)).all();for(let p of l)s.has(p.id)||(s.add(p.id),n.push(p));}catch(i){throw new c("DB_ERROR","Failed to find all threads",i)}finally{a.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let a=eq(u.id,t),i=e?and(a,or(eq(u.workspace_id,e),isNull(u.workspace_id))):a,l=r.db.select().from(u).where(i).limit(1).get()??void 0;if(l)return l}catch(a){throw new c("DB_ERROR","Failed to find thread by id",a)}finally{r.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let a=eq(u.id,t),i=e?and(a,or(eq(u.workspace_id,e),isNull(u.workspace_id))):a;if(r.db.select({id:u.id}).from(u).where(i).limit(1).get())return !0}catch(a){throw new c("DB_ERROR","Failed to check thread existence",a)}finally{r.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),n=0,r=0,a=0,i=0,l=0,p=new Set;for(let _ of s){if(!existsSync(_))continue;let k=b(_);try{let $=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),v=e?and($,eq(o.workspace_id,e)):$,F=k.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(v).get();F&&(n+=F.cnt,r+=F.total_input,a+=F.total_output,i+=F.total_cached,l+=F.total_cost);let yt=k.db.all(sql`
101
97
  SELECT DISTINCT agent_id FROM tasks
102
98
  WHERE thread_id = ${t}
103
99
  AND agent_id IS NOT NULL AND agent_id != ''
104
100
  AND (parent_task_id IS NULL OR parent_task_id = '')
105
101
  ${e?sql`AND workspace_id = ${e}`:sql``}
106
- `);for(let Et of yt)p.add(Et.agent_id);}catch(A){throw new c("DB_ERROR","Failed to aggregate task stats",A)}finally{k.close();}}return {taskCount:n,inputTokens:r,outputTokens:i,cachedInputTokens:l,costUsd:a,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let l=b(i);try{let a=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),p=e?and(a,eq(o.workspace_id,e)):a,_=l.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(a){throw new c("DB_ERROR","Failed to find top-level tasks",a)}finally{l.close();}}return r}findAllTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let l=b(i);try{let a=eq(o.thread_id,t),p=e?and(a,eq(o.workspace_id,e)):a,_=l.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(a){throw new c("DB_ERROR","Failed to find all tasks for thread",a)}finally{l.close();}}return r}findTaskById(t,e,s){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let i=b(r);try{let l=and(eq(o.id,e),eq(o.thread_id,t)),a=s?and(l,eq(o.workspace_id,s)):l,p=i.db.select().from(o).where(a).limit(1).get();if(!p)continue;let _=i.db.select().from(o).where(eq(o.parent_task_id,p.id)).orderBy(asc(o.started_at)).all();return {task:p,children:_}}catch(l){throw new c("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasks(t,e){let s=new Map;if(t.length===0)return s;let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let i=b(r);try{let l=and(inArray(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),a=e?and(l,eq(o.workspace_id,e)):l,p=i.db.select().from(o).where(a).orderBy(asc(o.started_at)).all();for(let _ of p){let k=_.thread_id;s.has(k)||s.set(k,[]),s.get(k).push(_);}}catch(l){throw new c("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return s}updateThreadTitle(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=eq(u.id,t),i=s?and(r,or(eq(u.workspace_id,s),isNull(u.workspace_id))):r;if(!n.db.select({id:u.id}).from(u).where(i).limit(1).get())return;n.db.update(u).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(u.id,t)).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to update thread title",r)}finally{n.close();}}upsertThread(t,e){let s=this.openHandle(true);try{let n=e.workspaceId?this.validateWorkspaceId(s,e.workspaceId):null,r=new Date().toISOString();if(s.db.select({id:u.id,message_count:u.message_count}).from(u).where(eq(u.id,t)).limit(1).get()){let l={updated_at:r};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),s.db.update(u).set(l).where(eq(u.id,t)).run();}else s.db.insert(u).values({id:t,platform:e.platform,workspace_id:n,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(n){throw n instanceof c?n:new c("DB_ERROR","Failed to upsert thread",n)}finally{s.close();}}ensureThread(t,e,s){let n=this.openHandle(true);try{let r=s?this.validateWorkspaceId(n,s):null,i=n.db.select({id:u.id,platform:u.platform,workspace_id:u.workspace_id}).from(u).where(eq(u.id,t)).limit(1).get();if(i){r&&!i.workspace_id&&n.db.update(u).set({workspace_id:r}).where(eq(u.id,t)).run();return}let l=new Date().toISOString();n.db.insert(u).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to ensure thread",r)}finally{n.close();}}saveUserMessage(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString();n.db.run(sql`
102
+ `);for(let Et of yt)p.add(Et.agent_id);}catch($){throw new c("DB_ERROR","Failed to aggregate task stats",$)}finally{k.close();}}return {taskCount:n,inputTokens:r,outputTokens:a,cachedInputTokens:i,costUsd:l,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let a of s){if(!existsSync(a))continue;let i=b(a);try{let l=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),p=e?and(l,eq(o.workspace_id,e)):l,_=i.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(l){throw new c("DB_ERROR","Failed to find top-level tasks",l)}finally{i.close();}}return r}findAllTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let a of s){if(!existsSync(a))continue;let i=b(a);try{let l=eq(o.thread_id,t),p=e?and(l,eq(o.workspace_id,e)):l,_=i.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(l){throw new c("DB_ERROR","Failed to find all tasks for thread",l)}finally{i.close();}}return r}findTaskById(t,e,s){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let a=b(r);try{let i=and(eq(o.id,e),eq(o.thread_id,t)),l=s?and(i,eq(o.workspace_id,s)):i,p=a.db.select().from(o).where(l).limit(1).get();if(!p)continue;let _=a.db.select().from(o).where(eq(o.parent_task_id,p.id)).orderBy(asc(o.started_at)).all();return {task:p,children:_}}catch(i){throw new c("DB_ERROR","Failed to find task by id",i)}finally{a.close();}}}batchFetchTasks(t,e){let s=new Map;if(t.length===0)return s;let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let a=b(r);try{let i=and(inArray(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),l=e?and(i,eq(o.workspace_id,e)):i,p=a.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let _ of p){let k=_.thread_id;s.has(k)||s.set(k,[]),s.get(k).push(_);}}catch(i){throw new c("DB_ERROR","Failed to batch fetch tasks",i)}finally{a.close();}}return s}updateThreadTitle(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=eq(u.id,t),a=s?and(r,or(eq(u.workspace_id,s),isNull(u.workspace_id))):r;if(!n.db.select({id:u.id}).from(u).where(a).limit(1).get())return;n.db.update(u).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(u.id,t)).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to update thread title",r)}finally{n.close();}}upsertThread(t,e){let s=this.openHandle(true);try{let n=e.workspaceId?this.validateWorkspaceId(s,e.workspaceId):null,r=new Date().toISOString();if(s.db.select({id:u.id,message_count:u.message_count}).from(u).where(eq(u.id,t)).limit(1).get()){let i={updated_at:r};e.title!==void 0&&(i.title=e.title),e.titleLocked!==void 0&&(i.title_locked=e.titleLocked?1:0),s.db.update(u).set(i).where(eq(u.id,t)).run();}else s.db.insert(u).values({id:t,platform:e.platform,workspace_id:n,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(n){throw n instanceof c?n:new c("DB_ERROR","Failed to upsert thread",n)}finally{s.close();}}ensureThread(t,e,s){let n=this.openHandle(true);try{let r=s?this.validateWorkspaceId(n,s):null,a=n.db.select({id:u.id,platform:u.platform,workspace_id:u.workspace_id}).from(u).where(eq(u.id,t)).limit(1).get();if(a){r&&!a.workspace_id&&n.db.update(u).set({workspace_id:r}).where(eq(u.id,t)).run();return}let i=new Date().toISOString();n.db.insert(u).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:i,updated_at:i}).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to ensure thread",r)}finally{n.close();}}saveUserMessage(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString();n.db.run(sql`
107
103
  UPDATE threads
108
104
  SET first_message = COALESCE(first_message, ${e}),
109
105
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -111,7 +107,7 @@ ${s.join(`
111
107
  message_count = message_count + 1,
112
108
  updated_at = ${r}
113
109
  WHERE id = ${t}
114
- `);}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to save user message",r)}finally{n.close();}}saveAssistantMessage(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString();n.db.update(u).set({last_message:e,updated_at:r}).where(eq(u.id,t)).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to save assistant message",r)}finally{n.close();}}updateThread(t,e){if(!this.dbExists())return;let s=this.openHandle(true);try{let n={updated_at:new Date().toISOString()};e.title!==void 0&&(n.title=e.title,n.title_locked=1),e.titleLocked!==void 0&&(n.title_locked=e.titleLocked?1:0),s.db.update(u).set(n).where(eq(u.id,t)).run();}catch(n){throw n instanceof c?n:new c("DB_ERROR","Failed to update thread",n)}finally{s.close();}}};function ue(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
110
+ `);}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to save user message",r)}finally{n.close();}}saveAssistantMessage(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString();n.db.update(u).set({last_message:e,updated_at:r}).where(eq(u.id,t)).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to save assistant message",r)}finally{n.close();}}updateThread(t,e){if(!this.dbExists())return;let s=this.openHandle(true);try{let n={updated_at:new Date().toISOString()};e.title!==void 0&&(n.title=e.title,n.title_locked=1),e.titleLocked!==void 0&&(n.title_locked=e.titleLocked?1:0),s.db.update(u).set(n).where(eq(u.id,t)).run();}catch(n){throw n instanceof c?n:new c("DB_ERROR","Failed to update thread",n)}finally{s.close();}}};function ce(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
115
111
  `).filter(n=>!(n.startsWith("Loaded ")&&n.includes("layouts from")||n.includes("[dotenv@")||n.includes("[Nest]")&&n.includes("DEBUG")||n.startsWith("Registered custom layout:")||n.startsWith("Updated custom layout:"))).join(`
116
- `).trim()}function pe(d){if(!d)return "";let t=d;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
117
- `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=ue(t);}return t}var Z=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Q({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let n=this.getThreadRepo(),r=n.findThreadById(t);if(r){if(r.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${r.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return}n.ensureThread(t,e,s);}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),i=n.findTopLevelTasks(t),l=new Set(["done","completed","success"]);i=i.filter(_=>(!_.status||l.has(_.status))&&(!e?.currentTraceId||_.trace_id!==e.currentTraceId)),i=i.slice(0,s);let a=r?.platform??"cli",p=this.rowsToMessages(i);return {threadId:t,platform:a,messages:p,metadata:{title:r?.title??void 0,firstMessage:r?.first_message??void 0,lastMessage:r?.last_message??void 0,messageCount:r?.message_count??0,updatedAt:r?.updated_at?new Date(r.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,n){this.getThreadRepo().saveUserMessage(t,e);}async saveAssistantMessage(t,e,s,n){this.getThreadRepo().saveAssistantMessage(t,e);}close(){}rowsToMessages(t){let e=[];for(let s of t){s.prompt&&e.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime()});let n=pe(s.result);n&&e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime()});}return e}};var at=class extends O{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new Z(t?.dbPath);}get conversationProvider(){return this._provider}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{await this._provider.ensureThread(e.threadId,s,e.workspaceId),await this._provider.saveUserMessage(e.threadId,e.message??"");}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let n=e.agentRef?.replace(/^@/,"")??"";try{await this._provider.saveAssistantMessage(s,e.result,n);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{at as ConversationPlugin,tt as FileLoggerPlugin,it as SqliteTracingPlugin};
112
+ `).trim()}function ue(d){if(!d)return "";let t=d;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
113
+ `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=ce(t);}return t}var tt=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Z({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let n=this.getThreadRepo(),r=n.findThreadById(t);if(r){if(r.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${r.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return}n.ensureThread(t,e,s);}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),a=n.findTopLevelTasks(t),i=new Set(["done","completed","success"]);a=a.filter(_=>(!_.status||i.has(_.status))&&(!e?.currentTraceId||_.trace_id!==e.currentTraceId)),a=a.slice(0,s);let l=r?.platform??"cli",p=this.rowsToMessages(a);return {threadId:t,platform:l,messages:p,metadata:{title:r?.title??void 0,firstMessage:r?.first_message??void 0,lastMessage:r?.last_message??void 0,messageCount:r?.message_count??0,updatedAt:r?.updated_at?new Date(r.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,n){this.getThreadRepo().saveUserMessage(t,e);}async saveAssistantMessage(t,e,s,n){this.getThreadRepo().saveAssistantMessage(t,e);}close(){}rowsToMessages(t){let e=[];for(let s of t){s.prompt&&e.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime()});let n=ue(s.result);n&&e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime()});}return e}};var at=class extends O{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new tt(t?.dbPath);}get conversationProvider(){return this._provider}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{await this._provider.ensureThread(e.threadId,s,e.workspaceId),await this._provider.saveUserMessage(e.threadId,e.message??"");}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let n=e.agentRef?.replace(/^@/,"")??"";try{await this._provider.saveAssistantMessage(s,e.result,n);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{at as ConversationPlugin,et as FileLoggerPlugin,it as SqliteTracingPlugin};
@@ -1,40 +1,37 @@
1
- import*as ct from'path';import ct__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import vt,{existsSync,mkdirSync}from'fs';import Jt from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique,getTableConfig}from'drizzle-orm/sqlite-core';import {randomUUID,createHash}from'crypto';var Z=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var Kt=()=>fileURLToPath(import.meta.url),Qt=()=>ct__default.dirname(Kt()),b=Qt();var R=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Jt.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var a=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function m(d){let t=Z("better-sqlite3"),{drizzle:e}=Z("drizzle-orm/better-sqlite3"),n=new t(d);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(s,r=[])=>n.prepare(s).run(...r),close:()=>n.close()}}var xt=new Set;function G(d){let{migrate:t}=Z("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Z("drizzle-orm"),n=[ct__default.join(b,"../migrations"),ct__default.join(b,"migrations")],s=n.find(_=>existsSync(ct__default.join(_,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
1
+ import*as X from'path';import X__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import vt,{existsSync,mkdirSync}from'fs';import Jt from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique,getTableConfig}from'drizzle-orm/sqlite-core';import {randomUUID,createHash}from'crypto';var tt=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var Kt=()=>fileURLToPath(import.meta.url),Qt=()=>X__default.dirname(Kt()),b=Qt();var R=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Jt.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var a=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function m(d){let t=tt("better-sqlite3"),{drizzle:e}=tt("drizzle-orm/better-sqlite3"),n=new t(d);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(s,o=[])=>n.prepare(s).run(...o),close:()=>n.close()}}var xt=new Set;function G(d){let{migrate:t}=tt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=tt("drizzle-orm"),n=[X__default.join(b,"../migrations"),X__default.join(b,"migrations"),X__default.join(b,"../../../../drizzle/migrations"),X__default.join(process.cwd(),"drizzle/migrations")],s=n.find(h=>existsSync(X__default.join(h,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
3
- `)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),t(d,{migrationsFolder:s});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let _=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${_} (${c} migration${c>1?"s":""} applied).`);}}function T(d,t){xt.has(t)||(G(d),xt.add(t));}var u=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),workspace_name:text("workspace_name"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_name:text("project_name"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>u.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var F=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>F.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));var v=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));var A=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));var Q=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));function pt(d){let t=ct.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function At(d){let t=pt(d);return createHash("sha256").update(t).digest("hex")}function nt(d){return d.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var ft=class extends R{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{G(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=nt(basename(n)),i=`${nt(basename(dirname(n)))}-${s}`,l=[s,i];try{let c=_=>t.select({id:u.id}).from(u).where(and(eq(u.slug,_),ne(u.id,e))).limit(1).all().length>0;for(let _ of l)if(!c(_))return _;for(let _=2;_<1e3;_+=1){let h=`${i}-${_}`;if(!c(h))return h}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:u.id,slug:u.slug}).from(u).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=nt(s.slug.replace(/\//g,"-"));t.db.update(u).set({slug:r,updated_at:new Date().toISOString()}).where(eq(u.id,s.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:s,name:r,workspacePath:i}=e,l=new Date().toISOString();t.insert(u).values({id:n,slug:s,name:r,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(u).set({workspace_path:i,updated_at:l}).where(and(eq(u.id,n),isNull(u.workspace_path))).run();}registerWorkspace(t){let e=pt(t),n=this.openHandle(true);try{let s=At(e),r=basename(e),i=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:i,name:r,workspacePath:e}),{id:s,slug:i}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to register workspace",s)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(u.is_active,t.isActive?1:0):void 0,s=e.db.select({count:sql`count(*)`}).from(u).where(n).get();return {rows:e.db.select().from(u).where(n).orderBy(desc(u.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new a("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(u).where(eq(u.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(s=>s.agent_id)}catch(n){throw new a("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let s=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
3
+ `)}`);let o=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),t(d,{migrationsFolder:s});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let h=o?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${h} (${c} migration${c>1?"s":""} applied).`);}}function T(d,t){xt.has(t)||(G(d),xt.add(t));}var u=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var r=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>u.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var F=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>r.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>F.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));var v=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>r.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));var A=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));var Q=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));function pt(d){let t=X.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function At(d){let t=pt(d);return createHash("sha256").update(t).digest("hex")}function st(d){return d.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var ft=class extends R{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{G(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=st(basename(n)),i=`${st(basename(dirname(n)))}-${s}`,l=[s,i];try{let c=h=>t.select({id:u.id}).from(u).where(and(eq(u.slug,h),ne(u.id,e))).limit(1).all().length>0;for(let h of l)if(!c(h))return h;for(let h=2;h<1e3;h+=1){let _=`${i}-${h}`;if(!c(_))return _}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:u.id,slug:u.slug}).from(u).all(),n=0;for(let s of e)if(s.slug.includes("/")){let o=st(s.slug.replace(/\//g,"-"));t.db.update(u).set({slug:o,updated_at:new Date().toISOString()}).where(eq(u.id,s.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:s,name:o,workspacePath:i}=e,l=new Date().toISOString();t.insert(u).values({id:n,slug:s,name:o,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(u).set({workspace_path:i,updated_at:l}).where(and(eq(u.id,n),isNull(u.workspace_path))).run();}registerWorkspace(t){let e=pt(t),n=this.openHandle(true);try{let s=At(e),o=basename(e),i=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:i,name:o,workspacePath:e}),{id:s,slug:i}}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to register workspace",s)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(u.is_active,t.isActive?1:0):void 0,s=e.db.select({count:sql`count(*)`}).from(u).where(n).get();return {rows:e.db.select().from(u).where(n).orderBy(desc(u.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new a("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(u).where(eq(u.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(s=>s.agent_id)}catch(n){throw new a("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let s=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
4
4
  (SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
5
5
  FROM threads t
6
6
  WHERE t.workspace_id = ${t}
7
7
  ORDER BY t.updated_at DESC
8
- LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new a("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(u).where(eq(u.slug,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?and(eq(u.slug,t),ne(u.id,e)):eq(u.slug,t);return !!n.db.select({id:u.id}).from(u).where(s).limit(1).get()}catch(s){throw new a("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let i=new Date().toISOString();r.db.insert(u).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:i,updated_at:i}).run();let l=r.db.select().from(u).where(eq(u.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{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(u).where(eq(u.id,t)).limit(1).get();if(!r)throw new a("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:u.id,workspace_path:u.workspace_path}).from(u).where(and(eq(u.is_active,1),isNotNull(u.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))||(t.db.update(u).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(u.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(u).where(eq(u.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var zt=[u,o,p,F,v,A,Q];function ye(){return ct__default.join(Jt.homedir(),".crewx","crewx.db")}function Re(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 Ee(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 xe(d){let t=d.getSQLType(),e=`"${d.name}" ${t}`,n=Ee(d.default);return n!==null&&(e+=` DEFAULT ${n}`),d.notNull&&(e+=" NOT NULL"),e}function Se(d,t){let e=t?.dbPath??ye(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Re(e);if(n&&!s)try{d.run("DELETE FROM __drizzle_migrations");}catch{}let i=qt(d);s||G(d);let l,c;s?(l=zt.map(E=>getTableConfig(E).name).filter(E=>!i.has(E)),c=i):(c=qt(d),l=[...c].filter(k=>!i.has(k)));let _=[],h=[];for(let k of zt){let E=getTableConfig(k),D=E.name;if(!c.has(D))continue;let z=d.all(`PRAGMA table_info("${D}")`),dt=new Set(z.map(B=>B.name)),lt=new Set(E.columns.map(B=>B.name));for(let B of E.columns)if(!dt.has(B.name)){if(!s){let Wt=xe(B);d.run(`ALTER TABLE "${D}" ADD COLUMN ${Wt}`);}_.push({table:D,column:B.name});}for(let B of z)lt.has(B.name)||h.push(`${D}.${B.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:_,warnings:h,backupPath:r}}var gt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,workspace_name:t.workspaceName??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new a("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(u).where(eq(u.slug,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?and(eq(u.slug,t),ne(u.id,e)):eq(u.slug,t);return !!n.db.select({id:u.id}).from(u).where(s).limit(1).get()}catch(s){throw new a("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let o=this.openHandle(true);try{let i=new Date().toISOString();o.db.insert(u).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:i,updated_at:i}).run();let l=o.db.select().from(u).where(eq(u.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{o.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let o=s.db.select().from(u).where(eq(u.id,t)).limit(1).get();if(!o)throw new a("NOT_FOUND",`Workspace ${t} not found`);return o}catch(o){throw o instanceof a?o:new a("DB_ERROR","Failed to update workspace",o)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:u.id,workspace_path:u.workspace_path}).from(u).where(and(eq(u.is_active,1),isNotNull(u.workspace_path))).all(),n=0;for(let s of e){let o=s.workspace_path;existsSync(join(o,"crewx.yaml"))||existsSync(join(o,"crewx.yml"))||(t.db.update(u).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(u.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(u).where(eq(u.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Lt=[u,r,p,F,v,A,Q];function ye(){return X__default.join(Jt.homedir(),".crewx","crewx.db")}function Re(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 Ee(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 xe(d){let t=d.getSQLType(),e=`"${d.name}" ${t}`,n=Ee(d.default);return n!==null&&(e+=` DEFAULT ${n}`),d.notNull&&(e+=" NOT NULL"),e}function De(d,t){let e=t?.dbPath??ye(),n=t?.force??false,s=t?.dryRun??false,o=s?null:Re(e);if(n&&!s)try{d.run("DELETE FROM __drizzle_migrations");}catch{}let i=qt(d);s||G(d);let l,c;s?(l=Lt.map(E=>getTableConfig(E).name).filter(E=>!i.has(E)),c=i):(c=qt(d),l=[...c].filter(g=>!i.has(g)));let h=[],_=[];for(let g of Lt){let E=getTableConfig(g),S=E.name;if(!c.has(S))continue;let L=d.all(`PRAGMA table_info("${S}")`),lt=new Set(L.map(B=>B.name)),ct=new Set(E.columns.map(B=>B.name));for(let B of E.columns)if(!lt.has(B.name)){if(!s){let Wt=xe(B);d.run(`ALTER TABLE "${S}" ADD COLUMN ${Wt}`);}h.push({table:S,column:B.name});}for(let B of L)ct.has(B.name)||_.push(`${S}.${B.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:h,warnings:_,backupPath:o}}var gt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(r).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
9
9
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
10
- model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),s.update(o).set({logs:JSON.stringify(i)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(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();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=m(s);try{let i=e?eq(o.workspace_id,e):void 0,l=i?and(eq(o.id,t),i):eq(o.id,t),c=r.db.select().from(o).where(l).limit(1).get()??void 0;if(!c){let _=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),h=i?and(_,i):_;c=r.db.select().from(o).where(h).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new a("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),_=l.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of _)s.has(h.id)||(s.add(h.id),r.push(h));}catch(c){throw new a("DB_ERROR","Failed to find child tasks",c)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
10
+ model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let o=s.select({logs:r.logs}).from(r).where(eq(r.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(e),s.update(r).set({logs:JSON.stringify(i)}).where(eq(r.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(r).where(eq(r.status,"running")).orderBy(desc(r.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(r).orderBy(desc(r.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(r).where(eq(r.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:r.id,status:r.status,pid:r.pid}).from(r).where(eq(r.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(r).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(r.id,t),eq(r.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();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let o=m(s);try{let i=e?eq(r.workspace_id,e):void 0,l=i?and(eq(r.id,t),i):eq(r.id,t),c=o.db.select().from(r).where(l).limit(1).get()??void 0;if(!c){let h=or(eq(r.thread_id,t),and(isNull(r.thread_id),like(r.command,`%--thread=${t}%`))),_=i?and(h,i):h;c=o.db.select().from(r).where(_).orderBy(desc(r.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new a("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=e?and(eq(r.parent_task_id,t),eq(r.workspace_id,e)):eq(r.parent_task_id,t),h=l.db.select().from(r).where(c).orderBy(asc(r.started_at)).all();for(let _ of h)s.has(_.id)||(s.add(_.id),o.push(_));}catch(c){throw new a("DB_ERROR","Failed to find child tasks",c)}finally{l.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
11
11
  SELECT
12
12
  COALESCE(workspace_id, 'unknown') AS workspace_id,
13
- COALESCE(workspace_name, 'Unknown Workspace') AS workspace_name,
14
13
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
15
14
  COALESCE(SUM(output_tokens), 0) AS output_tokens,
16
15
  COALESCE(SUM(cost_usd), 0) AS cost_usd,
17
16
  COUNT(*) AS task_count
18
17
  FROM tasks
19
18
  WHERE workspace_id = ${t}
20
- GROUP BY workspace_id, workspace_name
19
+ GROUP BY workspace_id
21
20
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
22
21
  `:sql`
23
22
  SELECT
24
23
  COALESCE(workspace_id, 'unknown') AS workspace_id,
25
- COALESCE(workspace_name, 'Unknown Workspace') AS workspace_name,
26
24
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
27
25
  COALESCE(SUM(output_tokens), 0) AS output_tokens,
28
26
  COALESCE(SUM(cost_usd), 0) AS cost_usd,
29
27
  COUNT(*) AS task_count
30
28
  FROM tasks
31
- GROUP BY workspace_id, workspace_name
29
+ GROUP BY workspace_id
32
30
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
33
- `)}catch(n){throw new a("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),s=new Set,r=0,i=0,l=0;for(let c of n){if(!existsSync(c))continue;let _=m(c);try{let h=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),k=e?and(h,eq(o.workspace_id,e)):h,E=_.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(k).all();for(let D of E)s.has(D.id)||(s.add(D.id),r+=D.input_tokens??0,i+=D.output_tokens??0,l+=D.cost_usd??0);}catch(h){throw new a("DB_ERROR","Failed to get thread token usage",h)}finally{_.close();}}return {inputTokens:r,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),_=e?and(c,eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(asc(o.started_at)).all();for(let k of h)s.has(k.id)||(s.add(k.id),r.push(k));}catch(c){throw new a("DB_ERROR","Failed to find tasks by thread",c)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(o.workspace_id,t.workspaceId));let s=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;s&&n.push(inArray(o.agent_id,s));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&n.push(inArray(o.status,r));let i=t.q??t.search;i&&n.push(like(o.prompt,`%${i}%`)),t.from&&n.push(gte(o.started_at,t.from)),t.to&&n.push(lt(o.started_at,t.to));let l=n.length>0?and(...n):void 0,c=e.db.select({count:sql`count(*)`}).from(o).where(l).get(),_=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(l).orderBy(_).limit(t.limit).offset(t.offset).all(),total:c?.count??0}}catch(n){throw new a("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
31
+ `)}catch(n){throw new a("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),s=new Set,o=0,i=0,l=0;for(let c of n){if(!existsSync(c))continue;let h=m(c);try{let _=or(eq(r.thread_id,t),and(isNull(r.thread_id),like(r.command,`%--thread=${t}%`))),g=e?and(_,eq(r.workspace_id,e)):_,E=h.db.select({id:r.id,input_tokens:r.input_tokens,output_tokens:r.output_tokens,cost_usd:r.cost_usd}).from(r).where(g).all();for(let S of E)s.has(S.id)||(s.add(S.id),o+=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{h.close();}}return {inputTokens:o,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),s=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=or(eq(r.thread_id,t),and(isNull(r.thread_id),like(r.command,`%--thread=${t}%`))),h=e?and(c,eq(r.workspace_id,e)):c,_=l.db.select().from(r).where(h).orderBy(asc(r.started_at)).all();for(let g of _)s.has(g.id)||(s.add(g.id),o.push(g));}catch(c){throw new a("DB_ERROR","Failed to find tasks by thread",c)}finally{l.close();}}return o}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(r.workspace_id,t.workspaceId));let s=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;s&&n.push(inArray(r.agent_id,s));let o=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;o&&n.push(inArray(r.status,o));let i=t.q??t.search;i&&n.push(like(r.prompt,`%${i}%`)),t.from&&n.push(gte(r.started_at,t.from)),t.to&&n.push(lt(r.started_at,t.to));let l=n.length>0?and(...n):void 0,c=e.db.select({count:sql`count(*)`}).from(r).where(l).get(),h=(t.sortDir??"DESC")==="ASC"?asc(r.started_at):desc(r.started_at);return {rows:e.db.select().from(r).where(l).orderBy(h).limit(t.limit).offset(t.offset).all(),total:c?.count??0}}catch(n){throw new a("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
34
32
  SELECT
35
33
  t.agent_id,
36
34
  t.workspace_id,
37
- t.workspace_name,
38
35
  COUNT(*) AS total_tasks,
39
36
  COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
40
37
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
@@ -44,14 +41,13 @@ ${n.join(`
44
41
  WHERE t.status IN ('completed', 'success')
45
42
  AND t.started_at >= ${t}
46
43
  AND t.started_at < ${e}
47
- AND t.workspace_name = ${n}
48
- GROUP BY t.agent_id, t.workspace_id, t.workspace_name
44
+ AND t.workspace_id = ${n}
45
+ GROUP BY t.agent_id, t.workspace_id
49
46
  ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
50
47
  `:sql`
51
48
  SELECT
52
49
  t.agent_id,
53
50
  t.workspace_id,
54
- t.workspace_name,
55
51
  COUNT(*) AS total_tasks,
56
52
  COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
57
53
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
@@ -61,9 +57,9 @@ ${n.join(`
61
57
  WHERE t.status IN ('completed', 'success')
62
58
  AND t.started_at >= ${t}
63
59
  AND t.started_at < ${e}
64
- GROUP BY t.agent_id, t.workspace_id, t.workspace_name
60
+ GROUP BY t.agent_id, t.workspace_id
65
61
  ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
66
- `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,workspaceName:i.workspace_name??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new a("DB_ERROR","Failed to get agent usage",r)}finally{s.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
62
+ `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(o){throw new a("DB_ERROR","Failed to get agent usage",o)}finally{s.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
67
63
  SELECT
68
64
  date(t.started_at) AS date,
69
65
  t.agent_id,
@@ -75,7 +71,7 @@ ${n.join(`
75
71
  WHERE t.status IN ('completed', 'success')
76
72
  AND t.started_at >= ${t}
77
73
  AND t.started_at < ${e}
78
- AND t.workspace_name = ${n}
74
+ AND t.workspace_id = ${n}
79
75
  GROUP BY date(t.started_at), t.agent_id
80
76
  ORDER BY date(t.started_at) ASC
81
77
  `:sql`
@@ -92,18 +88,18 @@ ${n.join(`
92
88
  AND t.started_at < ${e}
93
89
  GROUP BY date(t.started_at), t.agent_id
94
90
  ORDER BY date(t.started_at) ASC
95
- `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new a("DB_ERROR","Failed to get agent usage trend",r)}finally{s.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(and(eq(o.id,t),eq(o.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new a("DB_ERROR","Failed to find task for stop",s)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString(),i=n?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,n)):and(eq(o.id,t),eq(o.status,"running"));s.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to mark task failed",r)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),_=l.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of _)s.has(h.id)||(s.add(h.id),r.push(h));}catch(c){throw new a("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{l.close();}}return r}};var kt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:u.id}).from(u).where(eq(u.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!existsSync(r))continue;let i=m(r);try{let l=t?or(eq(p.workspace_id,t),isNull(p.workspace_id)):void 0,c=i.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let _ of c)n.has(_.id)||(n.add(_.id),s.push(_));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=m(s);try{let i=eq(p.id,t),l=e?and(i,or(eq(p.workspace_id,e),isNull(p.workspace_id))):i,c=r.db.select().from(p).where(l).limit(1).get()??void 0;if(c)return c}catch(i){throw new a("DB_ERROR","Failed to find thread by id",i)}finally{r.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=m(s);try{let i=eq(p.id,t),l=e?and(i,or(eq(p.workspace_id,e),isNull(p.workspace_id))):i;if(r.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(i){throw new a("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,i=0,l=0,c=0,_=new Set;for(let h of n){if(!existsSync(h))continue;let k=m(h);try{let E=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),D=e?and(E,eq(o.workspace_id,e)):E,z=k.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(D).get();z&&(s+=z.cnt,r+=z.total_input,i+=z.total_output,l+=z.total_cached,c+=z.total_cost);let dt=k.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(o){throw new a("DB_ERROR","Failed to get agent usage trend",o)}finally{s.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(r).where(and(eq(r.id,t),eq(r.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new a("DB_ERROR","Failed to find task for stop",s)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString(),i=n?and(eq(r.id,t),eq(r.status,"running"),eq(r.workspace_id,n)):and(eq(r.id,t),eq(r.status,"running"));s.db.update(r).set({status:"failed",error:e,completed_at:o}).where(i).run();}catch(o){throw o instanceof a?o:new a("DB_ERROR","Failed to mark task failed",o)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=e?and(like(r.prompt,`%${t}%`),eq(r.workspace_id,e)):like(r.prompt,`%${t}%`),h=l.db.select().from(r).where(c).orderBy(asc(r.started_at)).all();for(let _ of h)s.has(_.id)||(s.add(_.id),o.push(_));}catch(c){throw new a("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{l.close();}}return o}};var kt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:u.id}).from(u).where(eq(u.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let o of e){if(!existsSync(o))continue;let i=m(o);try{let l=t?or(eq(p.workspace_id,t),isNull(p.workspace_id)):void 0,c=i.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let h of c)n.has(h.id)||(n.add(h.id),s.push(h));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let o=m(s);try{let i=eq(p.id,t),l=e?and(i,or(eq(p.workspace_id,e),isNull(p.workspace_id))):i,c=o.db.select().from(p).where(l).limit(1).get()??void 0;if(c)return c}catch(i){throw new a("DB_ERROR","Failed to find thread by id",i)}finally{o.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let o=m(s);try{let i=eq(p.id,t),l=e?and(i,or(eq(p.workspace_id,e),isNull(p.workspace_id))):i;if(o.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(i){throw new a("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,o=0,i=0,l=0,c=0,h=new Set;for(let _ of n){if(!existsSync(_))continue;let g=m(_);try{let E=and(eq(r.thread_id,t),or(isNull(r.parent_task_id),eq(r.parent_task_id,""))),S=e?and(E,eq(r.workspace_id,e)):E,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(r).where(S).get();L&&(s+=L.cnt,o+=L.total_input,i+=L.total_output,l+=L.total_cached,c+=L.total_cost);let lt=g.db.all(sql`
96
92
  SELECT DISTINCT agent_id FROM tasks
97
93
  WHERE thread_id = ${t}
98
94
  AND agent_id IS NOT NULL AND agent_id != ''
99
95
  AND (parent_task_id IS NULL OR parent_task_id = '')
100
96
  ${e?sql`AND workspace_id = ${e}`:sql``}
101
- `);for(let lt of dt)_.add(lt.agent_id);}catch(E){throw new a("DB_ERROR","Failed to aggregate task stats",E)}finally{k.close();}}return {taskCount:s,inputTokens:r,outputTokens:i,cachedInputTokens:l,costUsd:c,agentIds:Array.from(_)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),_=e?and(c,eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(asc(o.started_at)).all();for(let k of h)s.has(k.id)||(s.add(k.id),r.push(k));}catch(c){throw new a("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}return r}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=eq(o.thread_id,t),_=e?and(c,eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(asc(o.started_at)).all();for(let k of h)s.has(k.id)||(s.add(k.id),r.push(k));}catch(c){throw new a("DB_ERROR","Failed to find all tasks for thread",c)}finally{l.close();}}return r}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=m(r);try{let l=and(eq(o.id,e),eq(o.thread_id,t)),c=n?and(l,eq(o.workspace_id,n)):l,_=i.db.select().from(o).where(c).limit(1).get();if(!_)continue;let h=i.db.select().from(o).where(eq(o.parent_task_id,_.id)).orderBy(asc(o.started_at)).all();return {task:_,children:h}}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 s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=m(r);try{let l=and(inArray(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),c=e?and(l,eq(o.workspace_id,e)):l,_=i.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of _){let k=h.thread_id;n.has(k)||n.set(k,[]),n.get(k).push(h);}}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 s=this.openHandle(true);try{let r=eq(p.id,t),i=n?and(r,or(eq(p.workspace_id,n),isNull(p.workspace_id))):r;if(!s.db.select({id:p.id}).from(p).where(i).limit(1).get())return;s.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to update thread title",r)}finally{s.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let s=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,r=new Date().toISOString();if(n.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let l={updated_at:r};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(p).set(l).where(eq(p.id,t)).run();}else n.db.insert(p).values({id:t,platform:e.platform,workspace_id:s,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to upsert thread",s)}finally{n.close();}}ensureThread(t,e,n){let s=this.openHandle(true);try{let r=n?this.validateWorkspaceId(s,n):null,i=s.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get();if(i){r&&!i.workspace_id&&s.db.update(p).set({workspace_id:r}).where(eq(p.id,t)).run();return}let l=new Date().toISOString();s.db.insert(p).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to ensure thread",r)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.run(sql`
97
+ `);for(let ct of lt)h.add(ct.agent_id);}catch(E){throw new a("DB_ERROR","Failed to aggregate task stats",E)}finally{g.close();}}return {taskCount:s,inputTokens:o,outputTokens:i,cachedInputTokens:l,costUsd:c,agentIds:Array.from(h)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=and(eq(r.thread_id,t),or(isNull(r.parent_task_id),eq(r.parent_task_id,""))),h=e?and(c,eq(r.workspace_id,e)):c,_=l.db.select().from(r).where(h).orderBy(asc(r.started_at)).all();for(let g of _)s.has(g.id)||(s.add(g.id),o.push(g));}catch(c){throw new a("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}return o}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=eq(r.thread_id,t),h=e?and(c,eq(r.workspace_id,e)):c,_=l.db.select().from(r).where(h).orderBy(asc(r.started_at)).all();for(let g of _)s.has(g.id)||(s.add(g.id),o.push(g));}catch(c){throw new a("DB_ERROR","Failed to find all tasks for thread",c)}finally{l.close();}}return o}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=m(o);try{let l=and(eq(r.id,e),eq(r.thread_id,t)),c=n?and(l,eq(r.workspace_id,n)):l,h=i.db.select().from(r).where(c).limit(1).get();if(!h)continue;let _=i.db.select().from(r).where(eq(r.parent_task_id,h.id)).orderBy(asc(r.started_at)).all();return {task:h,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 s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=m(o);try{let l=and(inArray(r.thread_id,t),or(isNull(r.parent_task_id),eq(r.parent_task_id,""))),c=e?and(l,eq(r.workspace_id,e)):l,h=i.db.select().from(r).where(c).orderBy(asc(r.started_at)).all();for(let _ of h){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 s=this.openHandle(true);try{let o=eq(p.id,t),i=n?and(o,or(eq(p.workspace_id,n),isNull(p.workspace_id))):o;if(!s.db.select({id:p.id}).from(p).where(i).limit(1).get())return;s.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(o){throw o instanceof a?o:new a("DB_ERROR","Failed to update thread title",o)}finally{s.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let s=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,o=new Date().toISOString();if(n.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let l={updated_at:o};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(p).set(l).where(eq(p.id,t)).run();}else n.db.insert(p).values({id:t,platform:e.platform,workspace_id:s,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:o,updated_at:o}).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to upsert thread",s)}finally{n.close();}}ensureThread(t,e,n){let s=this.openHandle(true);try{let o=n?this.validateWorkspaceId(s,n):null,i=s.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get();if(i){o&&!i.workspace_id&&s.db.update(p).set({workspace_id:o}).where(eq(p.id,t)).run();return}let l=new Date().toISOString();s.db.insert(p).values({id:t,platform:e,workspace_id:o,message_count:0,created_at:l,updated_at:l}).run();}catch(o){throw o instanceof a?o:new a("DB_ERROR","Failed to ensure thread",o)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.run(sql`
102
98
  UPDATE threads
103
99
  SET first_message = COALESCE(first_message, ${e}),
104
100
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
105
101
  last_message = ${e},
106
102
  message_count = message_count + 1,
107
- updated_at = ${r}
103
+ updated_at = ${o}
108
104
  WHERE id = ${t}
109
- `);}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to save user message",r)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.update(p).set({last_message:e,updated_at:r}).where(eq(p.id,t)).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to save assistant message",r)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(p).set(s).where(eq(p.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread",s)}finally{n.close();}}};var bt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}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 yt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(v).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(v).where(eq(v.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:v.tool_name,count:sql`count(*)`}).from(v).where(eq(v.task_id,t)).groupBy(v.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new a("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var Rt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.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(s){throw s instanceof a?s:new a("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(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(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new a("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(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 Et=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let r of t)s.insert(Q).values({id:randomUUID(),path:r.path,method:r.method,status_code:r.statusCode,duration_ms:r.durationMs,ip:r.ip??null,request_headers:r.requestHeaders??null,response_headers:r.responseHeaders??null,request_body:r.requestBody??null,response_body:r.responseBody??null,query:r.query??null,user_id:r.userId??null,project_id:r.projectId??null,partition_key:r.partitionKey??"default",timestamp:n,metadata:r.metadata??null}).run();});}catch(n){throw n instanceof 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(Q).orderBy(desc(Q.timestamp)).limit(t).all()}catch(n){throw new a("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};export{R as BaseSqliteRepository,a as RepositoryError,Et as RequestLogRepository,bt as SpanRepository,gt as TaskRepository,Rt as ThreadBoxRepository,kt as ThreadRepository,yt as ToolCallRepository,ft as WorkspaceRepository,m as openDrizzleDb,Se as pushSchema,G as runMigrations,T as runMigrationsOnce};
105
+ `);}catch(o){throw o instanceof a?o:new a("DB_ERROR","Failed to save user message",o)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.update(p).set({last_message:e,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof a?o:new a("DB_ERROR","Failed to save assistant message",o)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(p).set(s).where(eq(p.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread",s)}finally{n.close();}}};var bt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}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 yt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(v).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(v).where(eq(v.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:v.tool_name,count:sql`count(*)`}).from(v).where(eq(v.task_id,t)).groupBy(v.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new a("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var Rt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.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(s){throw s instanceof a?s:new a("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(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(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new a("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(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 Et=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let o of t)s.insert(Q).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:n,metadata:o.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(Q).orderBy(desc(Q.timestamp)).limit(t).all()}catch(n){throw new a("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};export{R as BaseSqliteRepository,a as RepositoryError,Et as RequestLogRepository,bt as SpanRepository,gt as TaskRepository,Rt as ThreadBoxRepository,kt as ThreadRepository,yt as ToolCallRepository,ft as WorkspaceRepository,m as openDrizzleDb,De as pushSchema,G as runMigrations,T as runMigrationsOnce};