@crewx/sdk 0.9.0-rc.2 → 0.9.0-rc.4

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.
package/dist/esm/index.js CHANGED
@@ -55,7 +55,7 @@ ${n??""}
55
55
  ---
56
56
  `)}c();function Ei(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return `${e}-${t}-${r}`}async function Xn(n,e=Me){let t=e.resolvePath(n,`${Ei()}.md`);return await e.exists(t)?e.readFile(t):""}Ce();c();var ht=new AsyncLocalStorage;function Or(n){if(n)return {parentTaskId:n.parentTaskId??null,rootTraceId:n.rootTraceId,callerAgentId:n.callerAgentId??null}}c();function Ti(n){return typeof n!="string"?"":n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Mr(n){return n.messages.map(e=>({text:Ti(e.text),isAssistant:e.isAssistant,timestamp:e.timestamp,metadata:e.metadata,files:void 0}))}c();Ce();Te();c();c();var Ze=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ii.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};c();function _e(n){let e=Y("better-sqlite3"),{drizzle:t}=Y("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),{db:t(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}c();var Jn=new Set,Oi={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function Dr(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Mi(n,e){if(e>0||!Dr(n,"tasks"))return;let t=n.all("PRAGMA table_info(tasks)"),r=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(Oi))r.has(o)||n.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var Ni={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Di(n,e,t){if(!Dr(n,"__drizzle_migrations")||!Dr(n,"tasks"))return;let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(X__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=Ni[i.tag];if(!a)continue;let d=X__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let l=readFileSync(d,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(o.has(u))continue;let p=n.all("PRAGMA table_info(tasks)"),y=new Set(p.map(g=>g.name));for(let[g,w]of Object.entries(a))y.has(g)||(n.run(`ALTER TABLE tasks ADD COLUMN ${g} ${w}`),y.add(g));}}function Li(n,e,t){let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(X__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=X__default.join(e,`${i.tag}.sql`);if(!existsSync(a))continue;let d=readFileSync(a,"utf-8"),l=createHash("sha256").update(d).digest("hex");if(o.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,p=[],y;for(;(y=u.exec(d))!==null;)p.push({table:y[1],column:y[2]});if(p.length===0||!d.split(/-->\s*statement-breakpoint/).map(k=>k.trim()).filter(Boolean).every(k=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(k)))continue;p.every(({table:k,column:A})=>n.all(`PRAGMA table_info("${k}")`).some(v=>v.name===A))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function $i(n){let{migrate:e}=Y("drizzle-orm/better-sqlite3/migrator"),{sql:t}=Y("drizzle-orm"),r=[X__default.join(f,"../migrations"),X__default.join(f,"migrations"),X__default.join(f,"../../../../drizzle/migrations"),X__default.join(process.cwd(),"drizzle/migrations")],o=r.find(l=>existsSync(X__default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
57
57
  ${r.join(`
58
- `)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Mi(n,i),s?.cnt&&(Li(n,o,t),Di(n,o,t)),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let l=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${l} (${d} migration${d>1?"s":""} applied).`);}}function Wt(n,e){Jn.has(e)||($i(n),Jn.add(e));}c();var N=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};c();c();var Qn=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()});c();var m=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),run_epoch:integer("run_epoch").default(0)},n=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));c();var eo=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Qn.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id)}));c();var je=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>m.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>je.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));c();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>m.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));c();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>eo.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));c();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));c();sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));var qe="2026-05-09",oa="0.8.9-rc.13",Be=10,We=parseInt(oa.split("rc.")[1]),wt=class extends Ze{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new N("NOT_FOUND","Database not found");let r=_e(t);if(e)try{Wt(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(m).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoNothing().run();}catch(r){throw r instanceof N?r:new N("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{let r=e.runEpoch??null;t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
58
+ `)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Mi(n,i),s?.cnt&&(Li(n,o,t),Di(n,o,t)),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${d} migration${d>1?"s":""} applied).`);}}function Wt(n,e){Jn.has(e)||($i(n),Jn.add(e));}c();var N=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};c();c();var Qn=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()});c();var m=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),run_epoch:integer("run_epoch").default(0)},n=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));c();var eo=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Qn.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id)}));c();var je=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>m.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>je.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));c();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>m.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));c();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>eo.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));c();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));c();sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));var qe="2026-05-09",oa="0.8.9-rc.13",Be=10,We=parseInt(oa.split("rc.")[1]),wt=class extends Ze{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new N("NOT_FOUND","Database not found");let r=_e(t);if(e)try{Wt(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(m).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoUpdate({target:m.id,set:{pid:sql`COALESCE(excluded.pid, ${m.pid})`},setWhere:eq(m.status,"running")}).run();}catch(r){throw r instanceof N?r:new N("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{let r=e.runEpoch??null;t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
59
59
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
60
60
  model=COALESCE(?, model)
61
61
  WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id,r]);}catch(r){throw r instanceof N?r:new N("DB_ERROR","Failed to finish task",r)}finally{t.close();}}appendLog(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{let s=o.select({logs:m.logs}).from(m).where(eq(m.id,e)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(t),o.update(m).set({logs:JSON.stringify(i)}).where(eq(m.id,e)).run();},{behavior:"immediate"});}catch(o){throw o instanceof N?o:new N("DB_ERROR","Failed to append log",o)}finally{r.close();}}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(m).where(eq(m.status,"running")).orderBy(desc(m.started_at)).all()}catch(t){throw new N("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(m).orderBy(desc(m.started_at)).limit(100).all()}catch(t){throw new N("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(m).where(eq(m.id,e)).limit(1).get()??void 0}catch(r){throw new N("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:m.id,status:m.status,pid:m.pid}).from(m).where(eq(m.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(m).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(m.id,e),eq(m.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof N?r:new N("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:m.id,pid:m.pid}).from(m).where(eq(m.status,"running")).all(),r=0;for(let o of t){if(!o.pid)continue;let s=!1;try{process.kill(o.pid,0),s=!0;}catch{}s||(e.db.update(m).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(m.id,o.id),eq(m.status,"running"))).run(),r++);}return r}finally{e.close();}}findTaskStatus(e,t){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=_e(o);try{let i=t?eq(m.workspace_id,t):void 0,a=i?and(eq(m.id,e),i):eq(m.id,e),d=s.db.select().from(m).where(a).limit(1).get()??void 0;if(!d){let l=or$1(eq(m.thread_id,e),and(isNull(m.thread_id),like(m.command,`%--thread=${e}%`))),u=i?and(l,i):l;d=s.db.select().from(m).where(u).orderBy(desc(m.started_at)).limit(1).get()??void 0;}if(d)return d}catch(i){throw new N("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let a=_e(i);try{let d=t?and(eq(m.parent_task_id,e),eq(m.workspace_id,t)):eq(m.parent_task_id,e),l=a.db.select().from(m).where(d).orderBy(asc(m.started_at)).all();for(let u of l)o.has(u.id)||(o.add(u.id),s.push(u));}catch(d){throw new N("DB_ERROR","Failed to find child tasks",d)}finally{a.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?sql`
@@ -10,7 +10,7 @@ Message: ${e.message}
10
10
  [${n}] INFO: Process closed with exit code: ${e.error?1:0}
11
11
  `;appendFileSync(s,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Ft(d){let t=N.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function kt(d){let t=Ft(d);return createHash("sha256").update(t).digest("hex")}var q=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(qt.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};function T(d){let t=X("better-sqlite3"),{drizzle:e}=X("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 wt=new Set,Wt={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function it(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function jt(d,t){if(t>0||!it(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),s=new Set(e.map(n=>n.name));for(let[n,r]of Object.entries(Wt))s.has(n)||d.run(`ALTER TABLE tasks ADD COLUMN ${n} ${r}`);}var Kt={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Gt(d,t,e){if(!it(d,"__drizzle_migrations")||!it(d,"tasks"))return;let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(i=>i.hash)),r=JSON.parse(readFileSync(N__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let a=Kt[i.tag];if(!a)continue;let l=N__default.join(t,`${i.tag}.sql`);if(!existsSync(l))continue;let c=readFileSync(l,"utf-8"),p=createHash("sha256").update(c).digest("hex");if(n.has(p))continue;let k=d.all("PRAGMA table_info(tasks)"),E=new Set(k.map(R=>R.name));for(let[R,G]of Object.entries(a))E.has(R)||(d.run(`ALTER TABLE tasks ADD COLUMN ${R} ${G}`),E.add(R));}}function Xt(d,t,e){let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(i=>i.hash)),r=JSON.parse(readFileSync(N__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let a=N__default.join(t,`${i.tag}.sql`);if(!existsSync(a))continue;let l=readFileSync(a,"utf-8"),c=createHash("sha256").update(l).digest("hex");if(n.has(c))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,k=[],E;for(;(E=p.exec(l))!==null;)k.push({table:E[1],column:E[2]});if(k.length===0||!l.split(/-->\s*statement-breakpoint/).map(K=>K.trim()).filter(Boolean).every(K=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(K)))continue;k.every(({table:K,column:Dt})=>d.all(`PRAGMA table_info("${K}")`).some(Nt=>Nt.name===Dt))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function Yt(d){let{migrate:t}=X("drizzle-orm/better-sqlite3/migrator"),{sql:e}=X("drizzle-orm"),s=[N__default.join(f,"../migrations"),N__default.join(f,"migrations"),N__default.join(f,"../../../../drizzle/migrations"),N__default.join(process.cwd(),"drizzle/migrations")],n=s.find(c=>existsSync(N__default.join(c,"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),jt(d,i),r?.cnt&&(Xt(d,n,e),Gt(d,n,e)),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function J(d,t){wt.has(t)||(Yt(d),wt.add(t));}var _=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 W=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),run_epoch:integer("run_epoch").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(()=>W.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var ne=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(()=>ne.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)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));var F="2026-05-09",ge="0.8.9-rc.13",H=10,z=parseInt(ge.split("rc.")[1]),st=class extends q{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 _("NOT_FOUND","Database not found");let s=T(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,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 _?s:new _("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let s=t.runEpoch??null;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'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),jt(d,i),r?.cnt&&(Xt(d,n,e),Gt(d,n,e)),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=r?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function J(d,t){wt.has(t)||(Yt(d),wt.add(t));}var _=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 W=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),run_epoch:integer("run_epoch").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(()=>W.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var ne=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(()=>ne.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)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));var F="2026-05-09",ge="0.8.9-rc.13",H=10,z=parseInt(ge.split("rc.")[1]),st=class extends q{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 _("NOT_FOUND","Database not found");let s=T(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,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}).onConflictDoUpdate({target:o.id,set:{pid:sql`COALESCE(excluded.pid, ${o.pid})`},setWhere:eq(o.status,"running")}).run();}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let s=t.runEpoch??null;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
15
  model=COALESCE(?, model)
16
16
  WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,s]);}catch(s){throw s instanceof _?s:new _("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 _?n:new _("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 _("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 _("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 _("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 _?s:new _("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(eq(o.status,"running")).all(),s=0;for(let n of e){if(!n.pid)continue;let r=!1;try{process.kill(n.pid,0),r=!0;}catch{}r||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,n.id),eq(o.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=T(n);try{let i=e?eq(o.workspace_id,e):void 0,a=i?and(eq(o.id,t),i):eq(o.id,t),l=r.db.select().from(o).where(a).limit(1).get()??void 0;if(!l){let c=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),p=i?and(c,i):c;l=r.db.select().from(o).where(p).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(l)return l}catch(i){throw new _("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let a=T(i);try{let l=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),c=a.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let p of c)n.has(p.id)||(n.add(p.id),r.push(p));}catch(l){throw new _("DB_ERROR","Failed to find child tasks",l)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
@@ -1,14 +1,14 @@
1
- import*as H from'path';import H__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import jt,{existsSync,mkdirSync,readFileSync}from'fs';import ce from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt as lt$1,lte}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,getTableConfig}from'drizzle-orm/sqlite-core';var st=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var ie=()=>fileURLToPath(import.meta.url),ae=()=>H__default.dirname(ie()),b=ae();var T=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(ce.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=st("better-sqlite3"),{drizzle:e}=st("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(r,s=[])=>n.prepare(r).run(...s),close:()=>n.close()}}var vt=new Set,ue={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function mt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function pe(a,t){if(t>0||!mt(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,s]of Object.entries(ue))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var _e={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function he(a,t,e){if(!mt(a,"__drizzle_migrations")||!mt(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=_e[o.tag];if(!l)continue;let u=H__default.join(t,`${o.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),h=createHash("sha256").update(c).digest("hex");if(r.has(h))continue;let m=a.all("PRAGMA table_info(tasks)"),g=new Set(m.map(y=>y.name));for(let[y,j]of Object.entries(l))g.has(y)||(a.run(`ALTER TABLE tasks ADD COLUMN ${y} ${j}`),g.add(y));}}function fe(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=H__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],g;for(;(g=h.exec(u))!==null;)m.push({table:g[1],column:g[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(W=>W.trim()).filter(Boolean).every(W=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(W)))continue;m.every(({table:W,column:ht})=>a.all(`PRAGMA table_info("${W}")`).some(ft=>ft.name===ht))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function Z(a){let{migrate:t}=st("drizzle-orm/better-sqlite3/migrator"),{sql:e}=st("drizzle-orm"),n=[H__default.join(b,"../migrations"),H__default.join(b,"migrations"),H__default.join(b,"../../../../drizzle/migrations"),H__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(H__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
1
+ import*as H from'path';import H__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import jt,{existsSync,mkdirSync,readFileSync}from'fs';import ce from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt as lt$1,lte}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,getTableConfig}from'drizzle-orm/sqlite-core';var st=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var ie=()=>fileURLToPath(import.meta.url),ae=()=>H__default.dirname(ie()),b=ae();var T=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(ce.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function k(a){let t=st("better-sqlite3"),{drizzle:e}=st("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(r,s=[])=>n.prepare(r).run(...s),close:()=>n.close()}}var Lt=new Set,ue={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function mt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function pe(a,t){if(t>0||!mt(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,s]of Object.entries(ue))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var _e={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function he(a,t,e){if(!mt(a,"__drizzle_migrations")||!mt(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=_e[o.tag];if(!l)continue;let u=H__default.join(t,`${o.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),h=createHash("sha256").update(c).digest("hex");if(r.has(h))continue;let m=a.all("PRAGMA table_info(tasks)"),g=new Set(m.map(y=>y.name));for(let[y,j]of Object.entries(l))g.has(y)||(a.run(`ALTER TABLE tasks ADD COLUMN ${y} ${j}`),g.add(y));}}function fe(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=H__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],g;for(;(g=h.exec(u))!==null;)m.push({table:g[1],column:g[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(W=>W.trim()).filter(Boolean).every(W=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(W)))continue;m.every(({table:W,column:ht})=>a.all(`PRAGMA table_info("${W}")`).some(ft=>ft.name===ht))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function Z(a){let{migrate:t}=st("drizzle-orm/better-sqlite3/migrator"),{sql:e}=st("drizzle-orm"),n=[H__default.join(b,"../migrations"),H__default.join(b,"migrations"),H__default.join(b,"../../../../drizzle/migrations"),H__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(H__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
3
- `)}`);let s=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;s?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),pe(a,o),s?.cnt&&(fe(a,r,e),he(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function D(a,t){vt.has(t)||(Z(a),vt.add(t));}var _=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var i=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>_.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id)}));var M=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>M.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var B=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var L=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()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var tt=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var x=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));function kt(a){let t=H.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Mt(a){let t=kt(a);return createHash("sha256").update(t).digest("hex")}function lt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Rt=class extends T{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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{Z(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=lt(basename(n)),o=`${lt(basename(dirname(n)))}-${r}`,l=[r,o];try{let u=c=>t.select({id:_.id}).from(_).where(and(eq(_.slug,c),ne(_.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let h=`${o}-${c}`;if(!u(h))return h}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,slug:_.slug}).from(_).all(),n=0;for(let r of e)if(r.slug.includes("/")){let s=lt(r.slug.replace(/\//g,"-"));t.db.update(_).set({slug:s,updated_at:new Date().toISOString()}).where(eq(_.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:o}=e,l=new Date().toISOString();t.insert(_).values({id:n,slug:r,name:s,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(_).set({workspace_path:o,updated_at:l}).where(and(eq(_.id,n),isNull(_.workspace_path))).run();}registerWorkspace(t){let e=kt(t),n=this.openHandle(true);try{let r=Mt(e),s=basename(e),o=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:o,name:s,workspacePath:e}),{id:r,slug:o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(_.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(_).where(n).get();return {rows:e.db.select().from(_).where(n).orderBy(desc(_.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(eq(_.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
3
+ `)}`);let s=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;s?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),pe(a,o),s?.cnt&&(fe(a,r,e),he(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function D(a,t){Lt.has(t)||(Z(a),Lt.add(t));}var _=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var i=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>_.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id)}));var M=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>M.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var B=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var P=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()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var tt=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var x=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));function kt(a){let t=H.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Mt(a){let t=kt(a);return createHash("sha256").update(t).digest("hex")}function lt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Rt=class extends T{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 r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{Z(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=lt(basename(n)),o=`${lt(basename(dirname(n)))}-${r}`,l=[r,o];try{let u=c=>t.select({id:_.id}).from(_).where(and(eq(_.slug,c),ne(_.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let h=`${o}-${c}`;if(!u(h))return h}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,slug:_.slug}).from(_).all(),n=0;for(let r of e)if(r.slug.includes("/")){let s=lt(r.slug.replace(/\//g,"-"));t.db.update(_).set({slug:s,updated_at:new Date().toISOString()}).where(eq(_.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:o}=e,l=new Date().toISOString();t.insert(_).values({id:n,slug:r,name:s,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(_).set({workspace_path:o,updated_at:l}).where(and(eq(_.id,n),isNull(_.workspace_path))).run();}registerWorkspace(t){let e=kt(t),n=this.openHandle(true);try{let r=Mt(e),s=basename(e),o=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:o,name:s,workspacePath:e}),{id:r,slug:o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(_.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(_).where(n).get();return {rows:e.db.select().from(_).where(n).orderBy(desc(_.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(eq(_.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=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:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?and(eq(_.slug,t),ne(_.id,e)):eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.insert(_).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:o,updated_at:o}).run();let l=s.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(and(eq(_.is_active,1),isNotNull(_.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(_.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Kt=[_,i,p,M,B,L,tt];function He(){return H__default.join(ce.homedir(),".crewx","crewx.db")}function Ue(a){if(!jt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return jt.copyFileSync(a,e),e}function Gt(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Me(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function qe(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Me(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Fe(a,t){let e=t?.dbPath??He(),n=t?.force??false,r=t?.dryRun??false,s=r?null:Ue(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Gt(a);if(!r)try{Z(a);}catch(m){let g=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw m}let l,u;r?(l=Kt.map(g=>getTableConfig(g).name).filter(g=>!o.has(g)),u=o):(u=Gt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Kt){let g=getTableConfig(m),y=g.name;if(!u.has(y))continue;let j=a.all(`PRAGMA table_info("${y}")`),W=new Set(j.map($=>$.name)),ht=new Set(g.columns.map($=>$.name));for(let $ of g.columns)if(!W.has($.name)){if(!r){let ft=qe($);a.run(`ALTER TABLE "${y}" ADD COLUMN ${ft}`);}c.push({table:y,column:$.name});}for(let $ of j)ht.has($.name)||h.push(`${y}.${$.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:s}}var J="2026-05-09",Xe="0.8.9-rc.13",V=10,Q=parseInt(Xe.split("rc.")[1]),Tt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?and(eq(_.slug,t),ne(_.id,e)):eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.insert(_).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:o,updated_at:o}).run();let l=s.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(and(eq(_.is_active,1),isNotNull(_.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(_.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Kt=[_,i,p,M,B,P,tt];function He(){return H__default.join(ce.homedir(),".crewx","crewx.db")}function Ue(a){if(!jt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return jt.copyFileSync(a,e),e}function Gt(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Me(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function qe(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Me(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Fe(a,t){let e=t?.dbPath??He(),n=t?.force??false,r=t?.dryRun??false,s=r?null:Ue(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Gt(a);if(!r)try{Z(a);}catch(m){let g=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw m}let l,u;r?(l=Kt.map(g=>getTableConfig(g).name).filter(g=>!o.has(g)),u=o):(u=Gt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Kt){let g=getTableConfig(m),y=g.name;if(!u.has(y))continue;let j=a.all(`PRAGMA table_info("${y}")`),W=new Set(j.map($=>$.name)),ht=new Set(g.columns.map($=>$.name));for(let $ of g.columns)if(!W.has($.name)){if(!r){let ft=qe($);a.run(`ALTER TABLE "${y}" ADD COLUMN ${ft}`);}c.push({table:y,column:$.name});}for(let $ of j)ht.has($.name)||h.push(`${y}.${$.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:s}}var J="2026-05-09",Xe="0.8.9-rc.13",V=10,Q=parseInt(Xe.split("rc.")[1]),Tt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:i.id,set:{pid:sql`COALESCE(excluded.pid, ${i.pid})`},setWhere:eq(i.status,"running")}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
9
9
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
10
10
  model=COALESCE(?, model)
11
- WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let s=r.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=s?.logs?JSON.parse(s.logs):[];o.push(e),r.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,t),eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(eq(i.status,"running")).all(),n=0;for(let r of e){if(!r.pid)continue;let s=!1;try{process.kill(r.pid,0),s=!0;}catch{}s||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,r.id),eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let o=e?eq(i.workspace_id,e):void 0,l=o?and(eq(i.id,t),o):eq(i.id,t),u=s.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),h=o?and(c,o):c;u=s.db.select().from(i).where(h).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=e?and(eq(i.parent_task_id,t),eq(i.workspace_id,e)):eq(i.parent_task_id,t),c=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
11
+ WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let s=r.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=s?.logs?JSON.parse(s.logs):[];o.push(e),r.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,t),eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(eq(i.status,"running")).all(),n=0;for(let r of e){if(!r.pid)continue;let s=!1;try{process.kill(r.pid,0),s=!0;}catch{}s||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,r.id),eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=k(r);try{let o=e?eq(i.workspace_id,e):void 0,l=o?and(eq(i.id,t),o):eq(i.id,t),u=s.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),h=o?and(c,o):c;u=s.db.select().from(i).where(h).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=e?and(eq(i.parent_task_id,t),eq(i.workspace_id,e)):eq(i.parent_task_id,t),c=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
12
12
  SELECT
13
13
  COALESCE(workspace_id, 'unknown') AS workspace_id,
14
14
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -29,7 +29,7 @@ ${n.join(`
29
29
  FROM tasks
30
30
  GROUP BY workspace_id
31
31
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
32
- `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,s=0,o=0,l=0;for(let u of n){if(!existsSync(u))continue;let c=w(u);try{let h=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),m=e?and(h,eq(i.workspace_id,e)):h,g=c.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(m).all();for(let y of g)r.has(y.id)||(r.add(y.id),s+=y.input_tokens??0,o+=y.output_tokens??0,l+=y.cost_usd??0);}catch(h){throw new d("DB_ERROR","Failed to get thread token usage",h)}finally{c.close();}}return {inputTokens:s,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),c=e?and(u,eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(i.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(i.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(inArray(i.status,s));let o=t.q??t.search;o&&n.push(like(i.prompt,`%${o}%`)),t.from&&n.push(gte(i.started_at,t.from)),t.to&&n.push(lt$1(i.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(i).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?asc(i.started_at):desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
32
+ `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,s=0,o=0,l=0;for(let u of n){if(!existsSync(u))continue;let c=k(u);try{let h=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),m=e?and(h,eq(i.workspace_id,e)):h,g=c.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(m).all();for(let y of g)r.has(y.id)||(r.add(y.id),s+=y.input_tokens??0,o+=y.output_tokens??0,l+=y.cost_usd??0);}catch(h){throw new d("DB_ERROR","Failed to get thread token usage",h)}finally{c.close();}}return {inputTokens:s,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),c=e?and(u,eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(i.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(i.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(inArray(i.status,s));let o=t.q??t.search;o&&n.push(like(i.prompt,`%${o}%`)),t.from&&n.push(gte(i.started_at,t.from)),t.to&&n.push(lt$1(i.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(i).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?asc(i.started_at):desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
33
33
  SELECT
34
34
  t.agent_id,
35
35
  t.workspace_id,
@@ -167,7 +167,7 @@ ${n.join(`
167
167
  AND t.started_at < ${e}
168
168
  GROUP BY date(t.started_at), t.agent_id
169
169
  ORDER BY date(t.started_at) ASC
170
- `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(and(eq(i.id,t),eq(i.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),o=n?and(eq(i.id,t),eq(i.status,"running"),eq(i.workspace_id,n)):and(eq(i.id,t),eq(i.status,"running"));r.db.update(i).set({status:"failed",error:e,completed_at:s}).where(o).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=e?and(like(i.prompt,`%${t}%`),eq(i.workspace_id,e)):like(i.prompt,`%${t}%`),c=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=sql`
170
+ `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(and(eq(i.id,t),eq(i.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),o=n?and(eq(i.id,t),eq(i.status,"running"),eq(i.workspace_id,n)):and(eq(i.id,t),eq(i.status,"running"));r.db.update(i).set({status:"failed",error:e,completed_at:s}).where(o).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=e?and(like(i.prompt,`%${t}%`),eq(i.workspace_id,e)):like(i.prompt,`%${t}%`),c=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=sql`
171
171
  CASE
172
172
  WHEN ${i.model} LIKE 'claude-%' OR ${i.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
173
173
  WHEN ${i.model} LIKE 'gpt-%' OR ${i.model} LIKE 'codex-%' THEN 'codex'
@@ -203,7 +203,7 @@ ${n.join(`
203
203
  ${l}
204
204
  GROUP BY provider
205
205
  ORDER BY (COALESCE(SUM(${o}), 0) + COALESCE(SUM(${i.output_tokens}), 0)) DESC
206
- `).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}};var xt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:_.id}).from(_).where(eq(_.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
206
+ `).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}};var xt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:_.id}).from(_).where(eq(_.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
207
207
  ${t}.parent_task_id IS NULL
208
208
  OR ${t}.parent_task_id = ''
209
209
  OR NOT EXISTS (
@@ -211,7 +211,7 @@ ${n.join(`
211
211
  WHERE parent.id = ${t}.parent_task_id
212
212
  AND parent.thread_id = ${t}.thread_id
213
213
  )
214
- )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!existsSync(s))continue;let o=w(s);try{let l=t?eq(p.workspace_id,t):void 0,u=o.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let c of u)n.has(c.id)||(n.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let o=eq(p.id,t),l=e?and(o,eq(p.workspace_id,e)):o,u=s.db.select().from(p).where(l).limit(1).get()??void 0;if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find thread by id",o)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let o=eq(p.id,t),l=e?and(o,eq(p.workspace_id,e)):o;if(s.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(o){throw new d("DB_ERROR","Failed to check thread existence",o)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,o=0,l=0,u=0,c=new Set;for(let h of n){if(!existsSync(h))continue;let m=w(h);try{let g=m.db.get(sql`
214
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!existsSync(s))continue;let o=k(s);try{let l=t?eq(p.workspace_id,t):void 0,u=o.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let c of u)n.has(c.id)||(n.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=k(r);try{let o=eq(p.id,t),l=e?and(o,eq(p.workspace_id,e)):o,u=s.db.select().from(p).where(l).limit(1).get()??void 0;if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find thread by id",o)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=k(r);try{let o=eq(p.id,t),l=e?and(o,eq(p.workspace_id,e)):o;if(s.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(o){throw new d("DB_ERROR","Failed to check thread existence",o)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,o=0,l=0,u=0,c=new Set;for(let h of n){if(!existsSync(h))continue;let m=k(h);try{let g=m.db.get(sql`
215
215
  SELECT
216
216
  count(*) AS cnt,
217
217
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -228,7 +228,7 @@ ${n.join(`
228
228
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
229
229
  AND ${this.topLevelTaskPredicateSql()}
230
230
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
231
- `);for(let j of y)c.add(j.agent_id);}catch(g){throw new d("DB_ERROR","Failed to aggregate task stats",g)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let l of r){if(!existsSync(l))continue;let u=w(l);try{let c;n!==void 0?c=u.db.all(sql`
231
+ `);for(let j of y)c.add(j.agent_id);}catch(g){throw new d("DB_ERROR","Failed to aggregate task stats",g)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let l of r){if(!existsSync(l))continue;let u=k(l);try{let c;n!==void 0?c=u.db.all(sql`
232
232
  SELECT * FROM (
233
233
  SELECT child.*,
234
234
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -245,7 +245,7 @@ ${n.join(`
245
245
  AND ${this.topLevelTaskPredicateSql()}
246
246
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
247
247
  ORDER BY child.started_at ASC
248
- `);for(let h of c)s.has(h.id)||(s.add(h.id),o.push(h));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&r.length>1){let l=new Map;for(let u of o){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}o=[];for(let u of l.values())u.sort((c,h)=>(h.started_at??"").localeCompare(c.started_at??"")),o.push(...u.slice(0,n));o.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return o}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=eq(i.thread_id,t),c=e?and(u,eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=w(s);try{let l=and(eq(i.id,e),eq(i.thread_id,t)),u=n?and(l,eq(i.workspace_id,n)):l,c=o.db.select().from(i).where(u).limit(1).get();if(!c)continue;let h=o.db.select().from(i).where(eq(i.parent_task_id,c.id)).orderBy(asc(i.started_at)).all();return {task:c,children:h}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{o.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=w(s);try{let l=o.db.all(sql`
248
+ `);for(let h of c)s.has(h.id)||(s.add(h.id),o.push(h));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&r.length>1){let l=new Map;for(let u of o){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}o=[];for(let u of l.values())u.sort((c,h)=>(h.started_at??"").localeCompare(c.started_at??"")),o.push(...u.slice(0,n));o.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return o}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=eq(i.thread_id,t),c=e?and(u,eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=k(s);try{let l=and(eq(i.id,e),eq(i.thread_id,t)),u=n?and(l,eq(i.workspace_id,n)):l,c=o.db.select().from(i).where(u).limit(1).get();if(!c)continue;let h=o.db.select().from(i).where(eq(i.parent_task_id,c.id)).orderBy(asc(i.started_at)).all();return {task:c,children:h}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{o.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=k(s);try{let l=o.db.all(sql`
249
249
  SELECT child.* FROM tasks child
250
250
  WHERE child.thread_id IN (${sql.join(t.map(u=>sql`${u}`),sql`, `)})
251
251
  AND ${this.topLevelTaskPredicateSql()}
@@ -259,4 +259,4 @@ ${n.join(`
259
259
  message_count = message_count + 1,
260
260
  updated_at = ${s}
261
261
  WHERE id = ${t}
262
- `),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:s}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!s)return null;let o=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(o){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),h=0;for(let m of c){let g=m.metadata?JSON.parse(m.metadata):{};typeof g.pinOrder=="number"&&g.pinOrder>h&&(h=g.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),o=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({starred:p.starred}).from(p).where(r).get();if(!s)return null;let o=s.starred?0:1;return n.db.update(p).set({starred:o}).where(r).run(),{starred:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}};var Dt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(M).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(M).where(eq(M.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(M).where(eq(M.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var At=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(B).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(B).where(eq(B.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:B.tool_name,count:sql`count(*)`}).from(B).where(eq(B.task_id,t)).groupBy(B.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var Ot=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(L).where(eq(L.thread_id,t)).orderBy(asc(L.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(L).where(and(eq(L.id,e),eq(L.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(L).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(L).where(eq(L.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Nt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(tt).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(tt).orderBy(desc(tt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function re(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Ct=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=re(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(x).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[x.provider,x.account_ref,x.limit_window,x.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:x.provider,bucket_start:x.bucket_start,used_percent:x.used_percent,remaining_percent:x.remaining_percent,resets_at:x.resets_at}).from(x).where(and(eq(x.limit_window,t.window),gte(x.bucket_start,t.fromIso),lte(x.bucket_start,t.toIso))).orderBy(asc(x.bucket_start)).all(),r=new Map;for(let s of n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,o])=>({provider:s,points:o}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};export{T as BaseSqliteRepository,d as RepositoryError,Nt as RequestLogRepository,Dt as SpanRepository,Tt as TaskRepository,Ot as ThreadBoxRepository,xt as ThreadRepository,At as ToolCallRepository,Ct as UsageLimitSnapshotRepository,Rt as WorkspaceRepository,re as calcBucketStart,w as openDrizzleDb,Fe as pushSchema,Z as runMigrations,D as runMigrationsOnce,i as tasks};
262
+ `),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:s}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!s)return null;let o=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(o){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),h=0;for(let m of c){let g=m.metadata?JSON.parse(m.metadata):{};typeof g.pinOrder=="number"&&g.pinOrder>h&&(h=g.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),o=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({starred:p.starred}).from(p).where(r).get();if(!s)return null;let o=s.starred?0:1;return n.db.update(p).set({starred:o}).where(r).run(),{starred:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}};var Dt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(M).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(M).where(eq(M.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(M).where(eq(M.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var At=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(B).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(B).where(eq(B.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:B.tool_name,count:sql`count(*)`}).from(B).where(eq(B.task_id,t)).groupBy(B.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var Ot=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(P).where(eq(P.thread_id,t)).orderBy(asc(P.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(P).where(and(eq(P.id,e),eq(P.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(P).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(P).where(eq(P.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Nt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(tt).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(tt).orderBy(desc(tt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function re(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Ct=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=re(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(x).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[x.provider,x.account_ref,x.limit_window,x.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:x.provider,bucket_start:x.bucket_start,used_percent:x.used_percent,remaining_percent:x.remaining_percent,resets_at:x.resets_at}).from(x).where(and(eq(x.limit_window,t.window),gte(x.bucket_start,t.fromIso),lte(x.bucket_start,t.toIso))).orderBy(asc(x.bucket_start)).all(),r=new Map;for(let s of n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,o])=>({provider:s,points:o}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};export{T as BaseSqliteRepository,d as RepositoryError,Nt as RequestLogRepository,Dt as SpanRepository,Tt as TaskRepository,Ot as ThreadBoxRepository,xt as ThreadRepository,At as ToolCallRepository,Ct as UsageLimitSnapshotRepository,Rt as WorkspaceRepository,re as calcBucketStart,k as openDrizzleDb,Fe as pushSchema,Z as runMigrations,D as runMigrationsOnce,i as tasks};
package/dist/index.js CHANGED
@@ -55,7 +55,7 @@ ${n??""}
55
55
  ---
56
56
  `)}c();function ki(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return `${e}-${t}-${r}`}async function Vn(n,e=Oe){let t=e.resolvePath(n,`${ki()}.md`);return await e.exists(t)?e.readFile(t):""}Ee();c();var yt=new async_hooks.AsyncLocalStorage;function Ir(n){if(n)return {parentTaskId:n.parentTaskId??null,rootTraceId:n.rootTraceId,callerAgentId:n.callerAgentId??null}}c();function vi(n){return typeof n!="string"?"":n.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Or(n){return n.messages.map(e=>({text:vi(e.text),isAssistant:e.isAssistant,timestamp:e.timestamp,metadata:e.metadata,files:void 0}))}c();Ee();Ce();c();c();var Qe=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:G.join(Ci__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return so.existsSync(e??this.resolveDbPath())}};c();function ke(n){let e=J("better-sqlite3"),{drizzle:t}=J("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),{db:t(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}c();var Gn=new Set,Ti={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function Nr(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function bi(n,e){if(e>0||!Nr(n,"tasks"))return;let t=n.all("PRAGMA table_info(tasks)"),r=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(Ti))r.has(o)||n.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var Pi={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Si(n,e,t){if(!Nr(n,"__drizzle_migrations")||!Nr(n,"tasks"))return;let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(so.readFileSync(G__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=Pi[i.tag];if(!a)continue;let d=G__namespace.default.join(e,`${i.tag}.sql`);if(!so.existsSync(d))continue;let l=so.readFileSync(d,"utf-8"),u=crypto$1.createHash("sha256").update(l).digest("hex");if(o.has(u))continue;let p=n.all("PRAGMA table_info(tasks)"),f=new Set(p.map(g=>g.name));for(let[g,h]of Object.entries(a))f.has(g)||(n.run(`ALTER TABLE tasks ADD COLUMN ${g} ${h}`),f.add(g));}}function Ii(n,e,t){let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(so.readFileSync(G__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=G__namespace.default.join(e,`${i.tag}.sql`);if(!so.existsSync(a))continue;let d=so.readFileSync(a,"utf-8"),l=crypto$1.createHash("sha256").update(d).digest("hex");if(o.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,p=[],f;for(;(f=u.exec(d))!==null;)p.push({table:f[1],column:f[2]});if(p.length===0||!d.split(/-->\s*statement-breakpoint/).map(x=>x.trim()).filter(Boolean).every(x=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(x)))continue;p.every(({table:x,column:v})=>n.all(`PRAGMA table_info("${x}")`).some(_=>_.name===v))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function Oi(n){let{migrate:e}=J("drizzle-orm/better-sqlite3/migrator"),{sql:t}=J("drizzle-orm"),r=[G__namespace.default.join(__dirname,"../migrations"),G__namespace.default.join(__dirname,"migrations"),G__namespace.default.join(__dirname,"../../../../drizzle/migrations"),G__namespace.default.join(process.cwd(),"drizzle/migrations")],o=r.find(l=>so.existsSync(G__namespace.default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
57
57
  ${r.join(`
58
- `)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),bi(n,i),s?.cnt&&(Ii(n,o,t),Si(n,o,t)),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let l=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${l} (${d} migration${d>1?"s":""} applied).`);}}function Bt(n,e){Gn.has(e)||(Oi(n),Gn.add(e));}c();var M=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};c();c();var Jn=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});c();var m=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},n=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(n.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));c();var Qn=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Jn.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(n.workspace_id)}));c();var Ue=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>m.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Ue.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},n=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(n.parent_span_id)}));c();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>m.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},n=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(n.timestamp)}));c();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>Qn.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(n.thread_id,n.seq)}));c();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},n=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(n.partition_key)}));c();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},n=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));var Fe="2026-05-09",Zi="0.8.9-rc.13",qe=10,Be=parseInt(Zi.split("rc.")[1]),ht=class extends Qe{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=G.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=G.dirname(t);so.existsSync(o)||so.mkdirSync(o,{recursive:true});}else if(!so.existsSync(t))throw new M("NOT_FOUND","Database not found");let r=ke(t);if(e)try{Bt(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(m).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoNothing().run();}catch(r){throw r instanceof M?r:new M("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{let r=e.runEpoch??null;t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
58
+ `)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),bi(n,i),s?.cnt&&(Ii(n,o,t),Si(n,o,t)),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${d} migration${d>1?"s":""} applied).`);}}function Bt(n,e){Gn.has(e)||(Oi(n),Gn.add(e));}c();var M=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};c();c();var Jn=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});c();var m=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},n=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(n.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));c();var Qn=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Jn.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(n.workspace_id)}));c();var Ue=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>m.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Ue.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},n=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(n.parent_span_id)}));c();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>m.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},n=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(n.timestamp)}));c();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>Qn.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(n.thread_id,n.seq)}));c();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},n=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(n.partition_key)}));c();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},n=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));var Fe="2026-05-09",Zi="0.8.9-rc.13",qe=10,Be=parseInt(Zi.split("rc.")[1]),ht=class extends Qe{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=G.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=G.dirname(t);so.existsSync(o)||so.mkdirSync(o,{recursive:true});}else if(!so.existsSync(t))throw new M("NOT_FOUND","Database not found");let r=ke(t);if(e)try{Bt(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(m).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoUpdate({target:m.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${m.pid})`},setWhere:drizzleOrm.eq(m.status,"running")}).run();}catch(r){throw r instanceof M?r:new M("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{let r=e.runEpoch??null;t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
59
59
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
60
60
  model=COALESCE(?, model)
61
61
  WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id,r]);}catch(r){throw r instanceof M?r:new M("DB_ERROR","Failed to finish task",r)}finally{t.close();}}appendLog(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{let s=o.select({logs:m.logs}).from(m).where(drizzleOrm.eq(m.id,e)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(t),o.update(m).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(m.id,e)).run();},{behavior:"immediate"});}catch(o){throw o instanceof M?o:new M("DB_ERROR","Failed to append log",o)}finally{r.close();}}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(m).where(drizzleOrm.eq(m.status,"running")).orderBy(drizzleOrm.desc(m.started_at)).all()}catch(t){throw new M("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(m).orderBy(drizzleOrm.desc(m.started_at)).limit(100).all()}catch(t){throw new M("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(m).where(drizzleOrm.eq(m.id,e)).limit(1).get()??void 0}catch(r){throw new M("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:m.id,status:m.status,pid:m.pid}).from(m).where(drizzleOrm.eq(m.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(m).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(m.id,e),drizzleOrm.eq(m.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof M?r:new M("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:m.id,pid:m.pid}).from(m).where(drizzleOrm.eq(m.status,"running")).all(),r=0;for(let o of t){if(!o.pid)continue;let s=!1;try{process.kill(o.pid,0),s=!0;}catch{}s||(e.db.update(m).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(m.id,o.id),drizzleOrm.eq(m.status,"running"))).run(),r++);}return r}finally{e.close();}}findTaskStatus(e,t){let r=this.resolveDbPaths();for(let o of r){if(!so.existsSync(o))continue;let s=ke(o);try{let i=t?drizzleOrm.eq(m.workspace_id,t):void 0,a=i?drizzleOrm.and(drizzleOrm.eq(m.id,e),i):drizzleOrm.eq(m.id,e),d=s.db.select().from(m).where(a).limit(1).get()??void 0;if(!d){let l=drizzleOrm.or(drizzleOrm.eq(m.thread_id,e),drizzleOrm.and(drizzleOrm.isNull(m.thread_id),drizzleOrm.like(m.command,`%--thread=${e}%`))),u=i?drizzleOrm.and(l,i):l;d=s.db.select().from(m).where(u).orderBy(drizzleOrm.desc(m.started_at)).limit(1).get()??void 0;}if(d)return d}catch(i){throw new M("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!so.existsSync(i))continue;let a=ke(i);try{let d=t?drizzleOrm.and(drizzleOrm.eq(m.parent_task_id,e),drizzleOrm.eq(m.workspace_id,t)):drizzleOrm.eq(m.parent_task_id,e),l=a.db.select().from(m).where(d).orderBy(drizzleOrm.asc(m.started_at)).all();for(let u of l)o.has(u.id)||(o.add(u.id),s.push(u));}catch(d){throw new M("DB_ERROR","Failed to find child tasks",d)}finally{a.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?drizzleOrm.sql`
@@ -10,7 +10,7 @@ Message: ${e.message}
10
10
  [${n}] INFO: Process closed with exit code: ${e.error?1:0}
11
11
  `;fs.appendFileSync(s,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Pt(d){let t=D__namespace.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 gt(d){let t=Pt(d);return crypto.createHash("sha256").update(t).digest("hex")}var z=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:D.join(Ut__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return fs.existsSync(t??this.resolveDbPath())}};function S(d){let t=G("better-sqlite3"),{drizzle:e}=G("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 kt=new Set,Bt={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function ot(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Ft(d,t){if(t>0||!ot(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),s=new Set(e.map(n=>n.name));for(let[n,r]of Object.entries(Bt))s.has(n)||d.run(`ALTER TABLE tasks ADD COLUMN ${n} ${r}`);}var Ht={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function zt(d,t,e){if(!ot(d,"__drizzle_migrations")||!ot(d,"tasks"))return;let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(i=>i.hash)),r=JSON.parse(fs.readFileSync(D__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let a=Ht[i.tag];if(!a)continue;let l=D__namespace.default.join(t,`${i.tag}.sql`);if(!fs.existsSync(l))continue;let c=fs.readFileSync(l,"utf-8"),p=crypto.createHash("sha256").update(c).digest("hex");if(n.has(p))continue;let g=d.all("PRAGMA table_info(tasks)"),w=new Set(g.map(b=>b.name));for(let[b,K]of Object.entries(a))w.has(b)||(d.run(`ALTER TABLE tasks ADD COLUMN ${b} ${K}`),w.add(b));}}function qt(d,t,e){let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(i=>i.hash)),r=JSON.parse(fs.readFileSync(D__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let a=D__namespace.default.join(t,`${i.tag}.sql`);if(!fs.existsSync(a))continue;let l=fs.readFileSync(a,"utf-8"),c=crypto.createHash("sha256").update(l).digest("hex");if(n.has(c))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,g=[],w;for(;(w=p.exec(l))!==null;)g.push({table:w[1],column:w[2]});if(g.length===0||!l.split(/-->\s*statement-breakpoint/).map(j=>j.trim()).filter(Boolean).every(j=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(j)))continue;g.every(({table:j,column:Ot})=>d.all(`PRAGMA table_info("${j}")`).some(Dt=>Dt.name===Ot))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function Wt(d){let{migrate:t}=G("drizzle-orm/better-sqlite3/migrator"),{sql:e}=G("drizzle-orm"),s=[D__namespace.default.join(__dirname,"../migrations"),D__namespace.default.join(__dirname,"migrations"),D__namespace.default.join(__dirname,"../../../../drizzle/migrations"),D__namespace.default.join(process.cwd(),"drizzle/migrations")],n=s.find(c=>fs.existsSync(D__namespace.default.join(c,"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),Ft(d,i),r?.cnt&&(qt(d,n,e),zt(d,n,e)),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function Y(d,t){kt.has(t)||(Wt(d),kt.add(t));}var _=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=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var o=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},d=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(d.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var u=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>q.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(d.workspace_id)}));var Qt=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Qt.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},d=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},d=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>u.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(d.thread_id,d.seq)}));sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},d=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(d.partition_key)}));sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));var B="2026-05-09",_e="0.8.9-rc.13",F=10,H=parseInt(_e.split("rc.")[1]),et=class extends z{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=D.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=D.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new _("NOT_FOUND","Database not found");let s=S(e);if(t)try{Y(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 _?s:new _("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let s=t.runEpoch??null;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'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ft(d,i),r?.cnt&&(qt(d,n,e),zt(d,n,e)),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=r?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function Y(d,t){kt.has(t)||(Wt(d),kt.add(t));}var _=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=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var o=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},d=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(d.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var u=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>q.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(d.workspace_id)}));var Qt=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Qt.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},d=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},d=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>u.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(d.thread_id,d.seq)}));sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},d=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(d.partition_key)}));sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));var B="2026-05-09",_e="0.8.9-rc.13",F=10,H=parseInt(_e.split("rc.")[1]),et=class extends z{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=D.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=D.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new _("NOT_FOUND","Database not found");let s=S(e);if(t)try{Y(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}).onConflictDoUpdate({target:o.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${o.pid})`},setWhere:drizzleOrm.eq(o.status,"running")}).run();}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let s=t.runEpoch??null;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
15
  model=COALESCE(?, model)
16
16
  WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,s]);}catch(s){throw s instanceof _?s:new _("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(drizzleOrm.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(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof _?n:new _("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(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.started_at)).all()}catch(e){throw new _("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(drizzleOrm.desc(o.started_at)).limit(100).all()}catch(e){throw new _("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new _("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(drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(drizzleOrm.eq(o.status,"running")).all(),s=0;for(let n of e){if(!n.pid)continue;let r=!1;try{process.kill(n.pid,0),r=!0;}catch{}r||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,n.id),drizzleOrm.eq(o.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=S(n);try{let i=e?drizzleOrm.eq(o.workspace_id,e):void 0,a=i?drizzleOrm.and(drizzleOrm.eq(o.id,t),i):drizzleOrm.eq(o.id,t),l=r.db.select().from(o).where(a).limit(1).get()??void 0;if(!l){let c=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),p=i?drizzleOrm.and(c,i):c;l=r.db.select().from(o).where(p).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??void 0;}if(l)return l}catch(i){throw new _("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(!fs.existsSync(i))continue;let a=S(i);try{let l=e?drizzleOrm.and(drizzleOrm.eq(o.parent_task_id,t),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.eq(o.parent_task_id,t),c=a.db.select().from(o).where(l).orderBy(drizzleOrm.asc(o.started_at)).all();for(let p of c)n.has(p.id)||(n.add(p.id),r.push(p));}catch(l){throw new _("DB_ERROR","Failed to find child tasks",l)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
@@ -1,14 +1,14 @@
1
- 'use strict';var Ft=require('fs'),z=require('path'),oe=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ft__default=/*#__PURE__*/_interopDefault(Ft);var z__namespace=/*#__PURE__*/_interopNamespace(z);var oe__default=/*#__PURE__*/_interopDefault(oe);var rt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var S=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:z.join(oe__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return Ft.existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=rt("better-sqlite3"),{drizzle:e}=rt("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(r,s=[])=>n.prepare(r).run(...s),close:()=>n.close()}}var Ct=new Set,ie={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function ft(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ae(a,t){if(t>0||!ft(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,s]of Object.entries(ie))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var de={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function le(a,t,e){if(!ft(a,"__drizzle_migrations")||!ft(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(Ft.readFileSync(z__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=de[o.tag];if(!l)continue;let u=z__namespace.default.join(t,`${o.tag}.sql`);if(!Ft.existsSync(u))continue;let c=Ft.readFileSync(u,"utf-8"),h=crypto.createHash("sha256").update(c).digest("hex");if(r.has(h))continue;let m=a.all("PRAGMA table_info(tasks)"),g=new Set(m.map(R=>R.name));for(let[R,F]of Object.entries(l))g.has(R)||(a.run(`ALTER TABLE tasks ADD COLUMN ${R} ${F}`),g.add(R));}}function ce(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(Ft.readFileSync(z__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=z__namespace.default.join(t,`${o.tag}.sql`);if(!Ft.existsSync(l))continue;let u=Ft.readFileSync(l,"utf-8"),c=crypto.createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],g;for(;(g=h.exec(u))!==null;)m.push({table:g[1],column:g[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(j=>j.trim()).filter(Boolean).every(j=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(j)))continue;m.every(({table:j,column:_t})=>a.all(`PRAGMA table_info("${j}")`).some(ht=>ht.name===_t))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function Q(a){let{migrate:t}=rt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=rt("drizzle-orm"),n=[z__namespace.default.join(__dirname,"../migrations"),z__namespace.default.join(__dirname,"migrations"),z__namespace.default.join(__dirname,"../../../../drizzle/migrations"),z__namespace.default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>Ft.existsSync(z__namespace.default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
1
+ 'use strict';var Ft=require('fs'),z=require('path'),oe=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ft__default=/*#__PURE__*/_interopDefault(Ft);var z__namespace=/*#__PURE__*/_interopNamespace(z);var oe__default=/*#__PURE__*/_interopDefault(oe);var rt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var S=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:z.join(oe__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return Ft.existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function k(a){let t=rt("better-sqlite3"),{drizzle:e}=rt("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(r,s=[])=>n.prepare(r).run(...s),close:()=>n.close()}}var Ct=new Set,ie={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function ft(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ae(a,t){if(t>0||!ft(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,s]of Object.entries(ie))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var de={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function le(a,t,e){if(!ft(a,"__drizzle_migrations")||!ft(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(Ft.readFileSync(z__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=de[o.tag];if(!l)continue;let u=z__namespace.default.join(t,`${o.tag}.sql`);if(!Ft.existsSync(u))continue;let c=Ft.readFileSync(u,"utf-8"),h=crypto.createHash("sha256").update(c).digest("hex");if(r.has(h))continue;let m=a.all("PRAGMA table_info(tasks)"),g=new Set(m.map(R=>R.name));for(let[R,F]of Object.entries(l))g.has(R)||(a.run(`ALTER TABLE tasks ADD COLUMN ${R} ${F}`),g.add(R));}}function ce(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(Ft.readFileSync(z__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=z__namespace.default.join(t,`${o.tag}.sql`);if(!Ft.existsSync(l))continue;let u=Ft.readFileSync(l,"utf-8"),c=crypto.createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],g;for(;(g=h.exec(u))!==null;)m.push({table:g[1],column:g[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(j=>j.trim()).filter(Boolean).every(j=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(j)))continue;m.every(({table:j,column:_t})=>a.all(`PRAGMA table_info("${j}")`).some(ht=>ht.name===_t))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function Q(a){let{migrate:t}=rt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=rt("drizzle-orm"),n=[z__namespace.default.join(__dirname,"../migrations"),z__namespace.default.join(__dirname,"migrations"),z__namespace.default.join(__dirname,"../../../../drizzle/migrations"),z__namespace.default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>Ft.existsSync(z__namespace.default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
3
- `)}`);let s=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;s?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ae(a,o),s?.cnt&&(ce(a,r,e),le(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function x(a,t){Ct.has(t)||(Q(a),Ct.add(t));}var _=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var i=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>_.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id)}));var U=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>U.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var $=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var v=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var Z=sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));var T=sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));function wt(a){let t=z__namespace.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Ut(a){let t=wt(a);return crypto.createHash("sha256").update(t).digest("hex")}function dt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Et=class extends S{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?z.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{Q(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=dt(z.basename(n)),o=`${dt(z.basename(z.dirname(n)))}-${r}`,l=[r,o];try{let u=c=>t.select({id:_.id}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.slug,c),drizzleOrm.ne(_.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let h=`${o}-${c}`;if(!u(h))return h}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,slug:_.slug}).from(_).all(),n=0;for(let r of e)if(r.slug.includes("/")){let s=dt(r.slug.replace(/\//g,"-"));t.db.update(_).set({slug:s,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(_.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:o}=e,l=new Date().toISOString();t.insert(_).values({id:n,slug:r,name:s,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(_).set({workspace_path:o,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(_.id,n),drizzleOrm.isNull(_.workspace_path))).run();}registerWorkspace(t){let e=wt(t),n=this.openHandle(true);try{let r=Ut(e),s=z.basename(e),o=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:o,name:s,workspacePath:e}),{id:r,slug:o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?drizzleOrm.eq(_.is_active,t.isActive?1:0):void 0,r=e.db.select({count:drizzleOrm.sql`count(*)`}).from(_).where(n).get();return {rows:e.db.select().from(_).where(n).orderBy(drizzleOrm.desc(_.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(drizzleOrm.sql`SELECT t.*,
3
+ `)}`);let s=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;s?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ae(a,o),s?.cnt&&(ce(a,r,e),le(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function x(a,t){Ct.has(t)||(Q(a),Ct.add(t));}var _=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var i=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>_.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id)}));var U=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>U.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var $=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var L=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var Z=sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));var T=sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));function wt(a){let t=z__namespace.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Ut(a){let t=wt(a);return crypto.createHash("sha256").update(t).digest("hex")}function dt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Et=class extends S{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?z.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{Q(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=dt(z.basename(n)),o=`${dt(z.basename(z.dirname(n)))}-${r}`,l=[r,o];try{let u=c=>t.select({id:_.id}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.slug,c),drizzleOrm.ne(_.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let h=`${o}-${c}`;if(!u(h))return h}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,slug:_.slug}).from(_).all(),n=0;for(let r of e)if(r.slug.includes("/")){let s=dt(r.slug.replace(/\//g,"-"));t.db.update(_).set({slug:s,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(_.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:o}=e,l=new Date().toISOString();t.insert(_).values({id:n,slug:r,name:s,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(_).set({workspace_path:o,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(_.id,n),drizzleOrm.isNull(_.workspace_path))).run();}registerWorkspace(t){let e=wt(t),n=this.openHandle(true);try{let r=Ut(e),s=z.basename(e),o=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:o,name:s,workspacePath:e}),{id:r,slug:o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?drizzleOrm.eq(_.is_active,t.isActive?1:0):void 0,r=e.db.select({count:drizzleOrm.sql`count(*)`}).from(_).where(n).get();return {rows:e.db.select().from(_).where(n).orderBy(drizzleOrm.desc(_.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(drizzleOrm.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:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(drizzleOrm.eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?drizzleOrm.and(drizzleOrm.eq(_.slug,t),drizzleOrm.ne(_.id,e)):drizzleOrm.eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.insert(_).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:o,updated_at:o}).run();let l=s.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.is_active,1),drizzleOrm.isNotNull(_.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;Ft.existsSync(z.join(s,"crewx.yaml"))||Ft.existsSync(z.join(s,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(_.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(drizzleOrm.eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Wt=[_,i,p,U,$,v,Z];function Pe(){return z__namespace.default.join(oe__default.default.homedir(),".crewx","crewx.db")}function $e(a){if(!Ft__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Ft__default.default.copyFileSync(a,e),e}function Kt(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Be(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function Ie(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Be(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function ze(a,t){let e=t?.dbPath??Pe(),n=t?.force??false,r=t?.dryRun??false,s=r?null:$e(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Kt(a);if(!r)try{Q(a);}catch(m){let g=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw m}let l,u;r?(l=Wt.map(g=>sqliteCore.getTableConfig(g).name).filter(g=>!o.has(g)),u=o):(u=Kt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Wt){let g=sqliteCore.getTableConfig(m),R=g.name;if(!u.has(R))continue;let F=a.all(`PRAGMA table_info("${R}")`),j=new Set(F.map(P=>P.name)),_t=new Set(g.columns.map(P=>P.name));for(let P of g.columns)if(!j.has(P.name)){if(!r){let ht=Ie(P);a.run(`ALTER TABLE "${R}" ADD COLUMN ${ht}`);}c.push({table:R,column:P.name});}for(let P of F)_t.has(P.name)||h.push(`${R}.${P.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:s}}var X="2026-05-09",je="0.8.9-rc.13",J=10,V=parseInt(je.split("rc.")[1]),St=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(drizzleOrm.eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?drizzleOrm.and(drizzleOrm.eq(_.slug,t),drizzleOrm.ne(_.id,e)):drizzleOrm.eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.insert(_).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:o,updated_at:o}).run();let l=s.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.is_active,1),drizzleOrm.isNotNull(_.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;Ft.existsSync(z.join(s,"crewx.yaml"))||Ft.existsSync(z.join(s,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(_.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(drizzleOrm.eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Wt=[_,i,p,U,$,L,Z];function Pe(){return z__namespace.default.join(oe__default.default.homedir(),".crewx","crewx.db")}function $e(a){if(!Ft__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Ft__default.default.copyFileSync(a,e),e}function Kt(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Be(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function Ie(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Be(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function ze(a,t){let e=t?.dbPath??Pe(),n=t?.force??false,r=t?.dryRun??false,s=r?null:$e(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Kt(a);if(!r)try{Q(a);}catch(m){let g=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw m}let l,u;r?(l=Wt.map(g=>sqliteCore.getTableConfig(g).name).filter(g=>!o.has(g)),u=o):(u=Kt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Wt){let g=sqliteCore.getTableConfig(m),R=g.name;if(!u.has(R))continue;let F=a.all(`PRAGMA table_info("${R}")`),j=new Set(F.map(P=>P.name)),_t=new Set(g.columns.map(P=>P.name));for(let P of g.columns)if(!j.has(P.name)){if(!r){let ht=Ie(P);a.run(`ALTER TABLE "${R}" ADD COLUMN ${ht}`);}c.push({table:R,column:P.name});}for(let P of F)_t.has(P.name)||h.push(`${R}.${P.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:s}}var X="2026-05-09",je="0.8.9-rc.13",J=10,V=parseInt(je.split("rc.")[1]),St=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:i.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${i.pid})`},setWhere:drizzleOrm.eq(i.status,"running")}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
9
9
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
10
10
  model=COALESCE(?, model)
11
- WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let s=r.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=s?.logs?JSON.parse(s.logs):[];o.push(e),r.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(drizzleOrm.desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=0;for(let r of e){if(!r.pid)continue;let s=!1;try{process.kill(r.pid,0),s=!0;}catch{}s||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,r.id),drizzleOrm.eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Ft.existsSync(r))continue;let s=w(r);try{let o=e?drizzleOrm.eq(i.workspace_id,e):void 0,l=o?drizzleOrm.and(drizzleOrm.eq(i.id,t),o):drizzleOrm.eq(i.id,t),u=s.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),h=o?drizzleOrm.and(c,o):c;u=s.db.select().from(i).where(h).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Ft.existsSync(o))continue;let l=w(o);try{let u=e?drizzleOrm.and(drizzleOrm.eq(i.parent_task_id,t),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.eq(i.parent_task_id,t),c=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
11
+ WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let s=r.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=s?.logs?JSON.parse(s.logs):[];o.push(e),r.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(drizzleOrm.desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=0;for(let r of e){if(!r.pid)continue;let s=!1;try{process.kill(r.pid,0),s=!0;}catch{}s||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,r.id),drizzleOrm.eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Ft.existsSync(r))continue;let s=k(r);try{let o=e?drizzleOrm.eq(i.workspace_id,e):void 0,l=o?drizzleOrm.and(drizzleOrm.eq(i.id,t),o):drizzleOrm.eq(i.id,t),u=s.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),h=o?drizzleOrm.and(c,o):c;u=s.db.select().from(i).where(h).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Ft.existsSync(o))continue;let l=k(o);try{let u=e?drizzleOrm.and(drizzleOrm.eq(i.parent_task_id,t),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.eq(i.parent_task_id,t),c=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
12
12
  SELECT
13
13
  COALESCE(workspace_id, 'unknown') AS workspace_id,
14
14
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -29,7 +29,7 @@ ${n.join(`
29
29
  FROM tasks
30
30
  GROUP BY workspace_id
31
31
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
32
- `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,s=0,o=0,l=0;for(let u of n){if(!Ft.existsSync(u))continue;let c=w(u);try{let h=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),m=e?drizzleOrm.and(h,drizzleOrm.eq(i.workspace_id,e)):h,g=c.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(m).all();for(let R of g)r.has(R.id)||(r.add(R.id),s+=R.input_tokens??0,o+=R.output_tokens??0,l+=R.cost_usd??0);}catch(h){throw new d("DB_ERROR","Failed to get thread token usage",h)}finally{c.close();}}return {inputTokens:s,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Ft.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),c=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(drizzleOrm.eq(i.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(drizzleOrm.inArray(i.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(drizzleOrm.inArray(i.status,s));let o=t.q??t.search;o&&n.push(drizzleOrm.like(i.prompt,`%${o}%`)),t.from&&n.push(drizzleOrm.gte(i.started_at,t.from)),t.to&&n.push(drizzleOrm.lt(i.started_at,t.to));let l=n.length>0?drizzleOrm.and(...n):void 0,u=e.db.select({count:drizzleOrm.sql`count(*)`}).from(i).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?drizzleOrm.sql`
32
+ `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,s=0,o=0,l=0;for(let u of n){if(!Ft.existsSync(u))continue;let c=k(u);try{let h=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),m=e?drizzleOrm.and(h,drizzleOrm.eq(i.workspace_id,e)):h,g=c.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(m).all();for(let R of g)r.has(R.id)||(r.add(R.id),s+=R.input_tokens??0,o+=R.output_tokens??0,l+=R.cost_usd??0);}catch(h){throw new d("DB_ERROR","Failed to get thread token usage",h)}finally{c.close();}}return {inputTokens:s,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Ft.existsSync(o))continue;let l=k(o);try{let u=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),c=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(drizzleOrm.eq(i.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(drizzleOrm.inArray(i.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(drizzleOrm.inArray(i.status,s));let o=t.q??t.search;o&&n.push(drizzleOrm.like(i.prompt,`%${o}%`)),t.from&&n.push(drizzleOrm.gte(i.started_at,t.from)),t.to&&n.push(drizzleOrm.lt(i.started_at,t.to));let l=n.length>0?drizzleOrm.and(...n):void 0,u=e.db.select({count:drizzleOrm.sql`count(*)`}).from(i).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?drizzleOrm.sql`
33
33
  SELECT
34
34
  t.agent_id,
35
35
  t.workspace_id,
@@ -167,7 +167,7 @@ ${n.join(`
167
167
  AND t.started_at < ${e}
168
168
  GROUP BY date(t.started_at), t.agent_id
169
169
  ORDER BY date(t.started_at) ASC
170
- `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),o=n?drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"),drizzleOrm.eq(i.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"));r.db.update(i).set({status:"failed",error:e,completed_at:s}).where(o).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Ft.existsSync(o))continue;let l=w(o);try{let u=e?drizzleOrm.and(drizzleOrm.like(i.prompt,`%${t}%`),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.like(i.prompt,`%${t}%`),c=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=drizzleOrm.sql`
170
+ `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),o=n?drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"),drizzleOrm.eq(i.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"));r.db.update(i).set({status:"failed",error:e,completed_at:s}).where(o).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Ft.existsSync(o))continue;let l=k(o);try{let u=e?drizzleOrm.and(drizzleOrm.like(i.prompt,`%${t}%`),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.like(i.prompt,`%${t}%`),c=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=drizzleOrm.sql`
171
171
  CASE
172
172
  WHEN ${i.model} LIKE 'claude-%' OR ${i.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
173
173
  WHEN ${i.model} LIKE 'gpt-%' OR ${i.model} LIKE 'codex-%' THEN 'codex'
@@ -203,7 +203,7 @@ ${n.join(`
203
203
  ${l}
204
204
  GROUP BY provider
205
205
  ORDER BY (COALESCE(SUM(${o}), 0) + COALESCE(SUM(${i.output_tokens}), 0)) DESC
206
- `).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}};var Tt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:_.id}).from(_).where(drizzleOrm.eq(_.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return drizzleOrm.sql.raw(`(
206
+ `).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}};var Tt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:_.id}).from(_).where(drizzleOrm.eq(_.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return drizzleOrm.sql.raw(`(
207
207
  ${t}.parent_task_id IS NULL
208
208
  OR ${t}.parent_task_id = ''
209
209
  OR NOT EXISTS (
@@ -211,7 +211,7 @@ ${n.join(`
211
211
  WHERE parent.id = ${t}.parent_task_id
212
212
  AND parent.thread_id = ${t}.thread_id
213
213
  )
214
- )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!Ft.existsSync(s))continue;let o=w(s);try{let l=t?drizzleOrm.eq(p.workspace_id,t):void 0,u=o.db.select().from(p).where(l).orderBy(drizzleOrm.desc(p.updated_at)).all();for(let c of u)n.has(c.id)||(n.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Ft.existsSync(r))continue;let s=w(r);try{let o=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(p.workspace_id,e)):o,u=s.db.select().from(p).where(l).limit(1).get()??void 0;if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find thread by id",o)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Ft.existsSync(r))continue;let s=w(r);try{let o=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(p.workspace_id,e)):o;if(s.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(o){throw new d("DB_ERROR","Failed to check thread existence",o)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,o=0,l=0,u=0,c=new Set;for(let h of n){if(!Ft.existsSync(h))continue;let m=w(h);try{let g=m.db.get(drizzleOrm.sql`
214
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!Ft.existsSync(s))continue;let o=k(s);try{let l=t?drizzleOrm.eq(p.workspace_id,t):void 0,u=o.db.select().from(p).where(l).orderBy(drizzleOrm.desc(p.updated_at)).all();for(let c of u)n.has(c.id)||(n.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Ft.existsSync(r))continue;let s=k(r);try{let o=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(p.workspace_id,e)):o,u=s.db.select().from(p).where(l).limit(1).get()??void 0;if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find thread by id",o)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Ft.existsSync(r))continue;let s=k(r);try{let o=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(p.workspace_id,e)):o;if(s.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(o){throw new d("DB_ERROR","Failed to check thread existence",o)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,o=0,l=0,u=0,c=new Set;for(let h of n){if(!Ft.existsSync(h))continue;let m=k(h);try{let g=m.db.get(drizzleOrm.sql`
215
215
  SELECT
216
216
  count(*) AS cnt,
217
217
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -228,7 +228,7 @@ ${n.join(`
228
228
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
229
229
  AND ${this.topLevelTaskPredicateSql()}
230
230
  ${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
231
- `);for(let F of R)c.add(F.agent_id);}catch(g){throw new d("DB_ERROR","Failed to aggregate task stats",g)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let l of r){if(!Ft.existsSync(l))continue;let u=w(l);try{let c;n!==void 0?c=u.db.all(drizzleOrm.sql`
231
+ `);for(let F of R)c.add(F.agent_id);}catch(g){throw new d("DB_ERROR","Failed to aggregate task stats",g)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let l of r){if(!Ft.existsSync(l))continue;let u=k(l);try{let c;n!==void 0?c=u.db.all(drizzleOrm.sql`
232
232
  SELECT * FROM (
233
233
  SELECT child.*,
234
234
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -245,7 +245,7 @@ ${n.join(`
245
245
  AND ${this.topLevelTaskPredicateSql()}
246
246
  ${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
247
247
  ORDER BY child.started_at ASC
248
- `);for(let h of c)s.has(h.id)||(s.add(h.id),o.push(h));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&r.length>1){let l=new Map;for(let u of o){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}o=[];for(let u of l.values())u.sort((c,h)=>(h.started_at??"").localeCompare(c.started_at??"")),o.push(...u.slice(0,n));o.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return o}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Ft.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.eq(i.thread_id,t),c=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!Ft.existsSync(s))continue;let o=w(s);try{let l=drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.thread_id,t)),u=n?drizzleOrm.and(l,drizzleOrm.eq(i.workspace_id,n)):l,c=o.db.select().from(i).where(u).limit(1).get();if(!c)continue;let h=o.db.select().from(i).where(drizzleOrm.eq(i.parent_task_id,c.id)).orderBy(drizzleOrm.asc(i.started_at)).all();return {task:c,children:h}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{o.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let s of r){if(!Ft.existsSync(s))continue;let o=w(s);try{let l=o.db.all(drizzleOrm.sql`
248
+ `);for(let h of c)s.has(h.id)||(s.add(h.id),o.push(h));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&r.length>1){let l=new Map;for(let u of o){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}o=[];for(let u of l.values())u.sort((c,h)=>(h.started_at??"").localeCompare(c.started_at??"")),o.push(...u.slice(0,n));o.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return o}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Ft.existsSync(o))continue;let l=k(o);try{let u=drizzleOrm.eq(i.thread_id,t),c=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!Ft.existsSync(s))continue;let o=k(s);try{let l=drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.thread_id,t)),u=n?drizzleOrm.and(l,drizzleOrm.eq(i.workspace_id,n)):l,c=o.db.select().from(i).where(u).limit(1).get();if(!c)continue;let h=o.db.select().from(i).where(drizzleOrm.eq(i.parent_task_id,c.id)).orderBy(drizzleOrm.asc(i.started_at)).all();return {task:c,children:h}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{o.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let s of r){if(!Ft.existsSync(s))continue;let o=k(s);try{let l=o.db.all(drizzleOrm.sql`
249
249
  SELECT child.* FROM tasks child
250
250
  WHERE child.thread_id IN (${drizzleOrm.sql.join(t.map(u=>drizzleOrm.sql`${u}`),drizzleOrm.sql`, `)})
251
251
  AND ${this.topLevelTaskPredicateSql()}
@@ -259,4 +259,4 @@ ${n.join(`
259
259
  message_count = message_count + 1,
260
260
  updated_at = ${s}
261
261
  WHERE id = ${t}
262
- `),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:s}).where(drizzleOrm.eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(drizzleOrm.eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),s=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!s)return null;let o=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(o){let u=e?drizzleOrm.and(drizzleOrm.eq(p.pinned,1),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),h=0;for(let m of c){let g=m.metadata?JSON.parse(m.metadata):{};typeof g.pinOrder=="number"&&g.pinOrder>h&&(h=g.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?drizzleOrm.and(drizzleOrm.eq(p.id,t[r]),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t[r]),o=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),s=n.db.select({starred:p.starred}).from(p).where(r).get();if(!s)return null;let o=s.starred?0:1;return n.db.update(p).set({starred:o}).where(r).run(),{starred:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}};var xt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(U).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(U).where(drizzleOrm.eq(U.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(U).where(drizzleOrm.eq(U.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var Dt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert($).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from($).where(drizzleOrm.eq($.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:$.tool_name,count:drizzleOrm.sql`count(*)`}).from($).where(drizzleOrm.eq($.task_id,t)).groupBy($.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var At=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(v).where(drizzleOrm.eq(v.thread_id,t)).orderBy(drizzleOrm.asc(v.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(v).where(drizzleOrm.and(drizzleOrm.eq(v.id,e),drizzleOrm.eq(v.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(v).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(v).where(drizzleOrm.eq(v.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Ot=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(Z).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(Z).orderBy(drizzleOrm.desc(Z.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function ne(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Nt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=ne(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(T).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[T.provider,T.account_ref,T.limit_window,T.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:T.provider,bucket_start:T.bucket_start,used_percent:T.used_percent,remaining_percent:T.remaining_percent,resets_at:T.resets_at}).from(T).where(drizzleOrm.and(drizzleOrm.eq(T.limit_window,t.window),drizzleOrm.gte(T.bucket_start,t.fromIso),drizzleOrm.lte(T.bucket_start,t.toIso))).orderBy(drizzleOrm.asc(T.bucket_start)).all(),r=new Map;for(let s of n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,o])=>({provider:s,points:o}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};exports.BaseSqliteRepository=S;exports.RepositoryError=d;exports.RequestLogRepository=Ot;exports.SpanRepository=xt;exports.TaskRepository=St;exports.ThreadBoxRepository=At;exports.ThreadRepository=Tt;exports.ToolCallRepository=Dt;exports.UsageLimitSnapshotRepository=Nt;exports.WorkspaceRepository=Et;exports.calcBucketStart=ne;exports.openDrizzleDb=w;exports.pushSchema=ze;exports.runMigrations=Q;exports.runMigrationsOnce=x;exports.tasks=i;
262
+ `),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:s}).where(drizzleOrm.eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(drizzleOrm.eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),s=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!s)return null;let o=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(o){let u=e?drizzleOrm.and(drizzleOrm.eq(p.pinned,1),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),h=0;for(let m of c){let g=m.metadata?JSON.parse(m.metadata):{};typeof g.pinOrder=="number"&&g.pinOrder>h&&(h=g.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?drizzleOrm.and(drizzleOrm.eq(p.id,t[r]),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t[r]),o=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),s=n.db.select({starred:p.starred}).from(p).where(r).get();if(!s)return null;let o=s.starred?0:1;return n.db.update(p).set({starred:o}).where(r).run(),{starred:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}};var xt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(U).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(U).where(drizzleOrm.eq(U.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(U).where(drizzleOrm.eq(U.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var Dt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert($).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from($).where(drizzleOrm.eq($.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:$.tool_name,count:drizzleOrm.sql`count(*)`}).from($).where(drizzleOrm.eq($.task_id,t)).groupBy($.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var At=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(L).where(drizzleOrm.eq(L.thread_id,t)).orderBy(drizzleOrm.asc(L.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(L).where(drizzleOrm.and(drizzleOrm.eq(L.id,e),drizzleOrm.eq(L.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(L).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(L).where(drizzleOrm.eq(L.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Ot=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(Z).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(Z).orderBy(drizzleOrm.desc(Z.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function ne(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Nt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=z.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=z.dirname(e);Ft.existsSync(r)||Ft.mkdirSync(r,{recursive:true});}else if(!Ft.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=ne(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(T).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[T.provider,T.account_ref,T.limit_window,T.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:T.provider,bucket_start:T.bucket_start,used_percent:T.used_percent,remaining_percent:T.remaining_percent,resets_at:T.resets_at}).from(T).where(drizzleOrm.and(drizzleOrm.eq(T.limit_window,t.window),drizzleOrm.gte(T.bucket_start,t.fromIso),drizzleOrm.lte(T.bucket_start,t.toIso))).orderBy(drizzleOrm.asc(T.bucket_start)).all(),r=new Map;for(let s of n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,o])=>({provider:s,points:o}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};exports.BaseSqliteRepository=S;exports.RepositoryError=d;exports.RequestLogRepository=Ot;exports.SpanRepository=xt;exports.TaskRepository=St;exports.ThreadBoxRepository=At;exports.ThreadRepository=Tt;exports.ToolCallRepository=Dt;exports.UsageLimitSnapshotRepository=Nt;exports.WorkspaceRepository=Et;exports.calcBucketStart=ne;exports.openDrizzleDb=k;exports.pushSchema=ze;exports.runMigrations=Q;exports.runMigrationsOnce=x;exports.tasks=i;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewx/sdk",
3
- "version": "0.9.0-rc.2",
3
+ "version": "0.9.0-rc.4",
4
4
  "license": "UNLICENSED",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"