@crewx/sdk 0.9.0-rc.12 → 0.9.0-rc.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,14 @@
1
- import*as F from'path';import F__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Yt,{existsSync,mkdirSync,readFileSync}from'fs';import fe 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 lt=(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 ue=()=>fileURLToPath(import.meta.url),pe=()=>F__default.dirname(ue()),E=pe();var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(fe.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=lt("better-sqlite3"),{drizzle:e}=lt("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 It=new Set,me={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 kt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ge(a,t){if(t>0||!kt(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(me))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var we={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ke(a,t,e){if(!kt(a,"__drizzle_migrations")||!kt(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),s=JSON.parse(readFileSync(F__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=we[i.tag];if(!l)continue;let u=F__default.join(t,`${i.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),_=createHash("sha256").update(c).digest("hex");if(r.has(_))continue;let m=a.all("PRAGMA table_info(tasks)"),f=new Set(m.map(S=>S.name));for(let[S,q]of Object.entries(l))f.has(S)||(a.run(`ALTER TABLE tasks ADD COLUMN ${S} ${q}`),f.add(S));}}function Ee(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),s=JSON.parse(readFileSync(F__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=F__default.join(t,`${i.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 _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],f;for(;(f=_.exec(u))!==null;)m.push({table:f[1],column:f[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(M=>M.trim()).filter(Boolean).every(M=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(M)))continue;m.every(({table:M,column:v})=>a.all(`PRAGMA table_info("${M}")`).some(B=>B.name===v))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function et(a){let{migrate:t}=lt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=lt("drizzle-orm"),n=[F__default.join(E,"../migrations"),F__default.join(E,"migrations"),F__default.join(E,"../../../../drizzle/migrations"),F__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(F__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
1
+ import*as W from'path';import W__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Qt,{existsSync,mkdirSync,readFileSync}from'fs';import Ee from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt,lte}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,getTableConfig}from'drizzle-orm/sqlite-core';var pt=(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 ge=()=>fileURLToPath(import.meta.url),we=()=>W__default.dirname(ge()),b=we();var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ee.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=pt("better-sqlite3"),{drizzle:e}=pt("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,o=[])=>n.prepare(r).run(...o),close:()=>n.close()}}var zt=new Set,Re={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function Rt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ye(a,t){if(t>0||!Rt(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,o]of Object.entries(Re))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${o}`);}var Se={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function xe(a,t,e){if(!Rt(a,"__drizzle_migrations")||!Rt(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(W__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=Se[i.tag];if(!l)continue;let u=W__default.join(t,`${i.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),_=createHash("sha256").update(c).digest("hex");if(r.has(_))continue;let m=a.all("PRAGMA table_info(tasks)"),f=new Set(m.map(y=>y.name));for(let[y,j]of Object.entries(l))f.has(y)||(a.run(`ALTER TABLE tasks ADD COLUMN ${y} ${j}`),f.add(y));}}function Te(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(W__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=W__default.join(t,`${i.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 _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],f;for(;(f=_.exec(u))!==null;)m.push({table:f[1],column:f[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(z=>z.trim()).filter(Boolean).every(z=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(z)))continue;m.every(({table:z,column:v})=>a.all(`PRAGMA table_info("${z}")`).some(U=>U.name===v))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function rt(a){let{migrate:t}=pt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=pt("drizzle-orm"),n=[W__default.join(b,"../migrations"),W__default.join(b,"migrations"),W__default.join(b,"../../../../drizzle/migrations"),W__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(W__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'`),i=0;s?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ge(a,i),s?.cnt&&(Ee(a,r,e),ke(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function N(a,t){It.has(t)||(et(a),It.add(t));}var h=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var 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)},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(()=>h.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},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 W=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(()=>W.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 H=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var I=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 nt=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 A=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 Rt(a){let t=F.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 Wt(a){let t=Rt(a);return createHash("sha256").update(t).digest("hex")}function ht(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Tt=class extends x{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{et(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=ht(basename(n)),i=`${ht(basename(dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:h.id}).from(h).where(and(eq(h.slug,c),ne(h.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 _=`${i}-${c}`;if(!u(_))return _}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let r of e)if(r.slug.includes("/")){let s=ht(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:s,updated_at:new Date().toISOString()}).where(eq(h.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:i}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:s,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:i,updated_at:l}).where(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(t){let e=Rt(t),n=this.openHandle(true);try{let r=Wt(e),s=basename(e),i=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:i,name:s,workspacePath:e}),{id:r,slug:i}}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(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total: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(h).where(eq(h.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 o=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ye(a,i),o?.cnt&&(Te(a,r,e),xe(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function A(a,t){zt.has(t)||(rt(a),zt.add(t));}var h=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var s=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(()=>h.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},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),idx_threads_ws_updated:index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at)}));var G=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>G.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 q=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.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 B=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 st=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 O=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)}));var L=sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},a=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));function Tt(a){let t=W.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 Xt(a){let t=Tt(a);return createHash("sha256").update(t).digest("hex")}function gt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Ot=class extends x{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{rt(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=gt(basename(n)),i=`${gt(basename(dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:h.id}).from(h).where(and(eq(h.slug,c),ne$1(h.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 _=`${i}-${c}`;if(!u(_))return _}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let r of e)if(r.slug.includes("/")){let o=gt(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:o,updated_at:new Date().toISOString()}).where(eq(h.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:o,workspacePath:i}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:o,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:i,updated_at:l}).where(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(t){let e=Tt(t),n=this.openHandle(true);try{let r=Xt(e),o=basename(e),i=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:i,name:o,workspacePath:e}),{id:r,slug:i}}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(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total: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(h).where(eq(h.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(h).where(eq(h.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(h.slug,t),ne(h.id,e)):eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).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 i=new Date().toISOString();s.db.insert(h).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof d?i:new d("DB_ERROR","Failed to insert workspace",i)}finally{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(h).where(eq(h.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:h.id,workspace_path:h.workspace_path}).from(h).where(and(eq(h.is_active,1),isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(h.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(h).where(eq(h.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Jt=[h,o,p,W,H,I,nt];function je(){return F__default.join(fe.homedir(),".crewx","crewx.db")}function We(a){if(!Yt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Yt.copyFileSync(a,e),e}function Vt(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 Ke(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 Ge(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Ke(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Ye(a,t){let e=t?.dbPath??je(),n=t?.force??false,r=t?.dryRun??false,s=r?null:We(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=Vt(a);if(!r)try{et(a);}catch(m){let f=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!f.includes("duplicate column"))throw m}let l,u;r?(l=Jt.map(f=>getTableConfig(f).name).filter(f=>!i.has(f)),u=i):(u=Vt(a),l=[...u].filter(m=>!i.has(m)));let c=[],_=[];for(let m of Jt){let f=getTableConfig(m),S=f.name;if(!u.has(S))continue;let q=a.all(`PRAGMA table_info("${S}")`),M=new Set(q.map(y=>y.name)),v=new Set(f.columns.map(y=>y.name));for(let y of f.columns)if(!M.has(y.name)){if(!r){let B=Ge(y);a.run(`ALTER TABLE "${S}" ADD COLUMN ${B}`);}c.push({table:S,column:y.name});}for(let y of q)v.has(y.name)||_.push(`${S}.${y.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:_,backupPath:s}}function Qt(a){let t=a.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var Y="2026-05-09",en="0.8.9-rc.13",X=10,J=parseInt(en.split("rc.")[1]),nn=new Set(["workflow","mcp"]),rn=600*1e3,At=class extends x{dbPath;pidNullObservedSince=new Map;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{N(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:o.id,set:{pid:sql`COALESCE(excluded.pid, ${o.pid})`},setWhere:eq(o.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=?,
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(h).where(eq(h.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(h.slug,t),ne$1(h.id,e)):eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).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 o=this.openHandle(true);try{let i=new Date().toISOString();o.db.insert(h).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=o.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof d?i:new d("DB_ERROR","Failed to insert workspace",i)}finally{o.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let o=r.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!o)throw new d("NOT_FOUND",`Workspace ${t} not found`);return o}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update workspace",o)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(and(eq(h.is_active,1),isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let o=r.workspace_path;existsSync(join(o,"crewx.yaml"))||existsSync(join(o,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(h.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(h).where(eq(h.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var te=[h,s,p,G,q,B,st];function tn(){return W__default.join(Ee.homedir(),".crewx","crewx.db")}function en(a){if(!Qt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Qt.copyFileSync(a,e),e}function ee(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 nn(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 rn(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=nn(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function sn(a,t){let e=t?.dbPath??tn(),n=t?.force??false,r=t?.dryRun??false,o=r?null:en(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=ee(a);if(!r)try{rt(a);}catch(m){let f=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!f.includes("duplicate column"))throw m}let l,u;r?(l=te.map(f=>getTableConfig(f).name).filter(f=>!i.has(f)),u=i):(u=ee(a),l=[...u].filter(m=>!i.has(m)));let c=[],_=[];for(let m of te){let f=getTableConfig(m),y=f.name;if(!u.has(y))continue;let j=a.all(`PRAGMA table_info("${y}")`),z=new Set(j.map(S=>S.name)),v=new Set(f.columns.map(S=>S.name));for(let S of f.columns)if(!z.has(S.name)){if(!r){let U=rn(S);a.run(`ALTER TABLE "${y}" ADD COLUMN ${U}`);}c.push({table:y,column:S.name});}for(let S of j)v.has(S.name)||_.push(`${y}.${S.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:_,backupPath:o}}function ne(a){let t=a.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var J="2026-05-09",pn="0.8.9-rc.13",V=10,Q=parseInt(pn.split("rc.")[1]),_n=new Set(["workflow","mcp"]),hn=600*1e3,vt=class extends x{dbPath;pidNullObservedSince=new Map;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{A(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(s).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:s.id,set:{pid:sql`COALESCE(excluded.pid, ${s.pid})`},setWhere:eq(s.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:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(e),r.update(o).set({logs:JSON.stringify(i)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof 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(o).where(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(desc(o.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid,platform:o.platform,run_epoch:o.run_epoch}).from(o).where(eq(o.status,"running")).all(),n=Date.now(),r=new Set,s=0;for(let i of e){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,i.id),eq(o.status,"running"))).run(),s++);continue}if(nn.has(i.platform??"cli"))continue;let l=`${i.id}:${i.run_epoch??0}`;r.add(l);let u=this.pidNullObservedSince.get(l);if(u===void 0){this.pidNullObservedSince.set(l,n);continue}n-u>=rn&&(t.db.update(o).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(o.id,i.id),eq(o.status,"running"))).run(),s++,this.pidNullObservedSince.delete(l));}for(let i of Array.from(this.pidNullObservedSince.keys()))r.has(i)||this.pidNullObservedSince.delete(i);return s}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 i=e?eq(o.workspace_id,e):void 0,l=i?and(eq(o.id,t),i):eq(o.id,t),u=s.db.select().from(o).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),_=i?and(c,i):c;u=s.db.select().from(o).where(_).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),c=l.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let _ of c)r.has(_.id)||(r.add(_.id),s.push(_));}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 o=r.select({logs:s.logs}).from(s).where(eq(s.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(e),r.update(s).set({logs:JSON.stringify(i)}).where(eq(s.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(s).where(eq(s.status,"running")).orderBy(desc(s.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(s).orderBy(desc(s.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(s).where(eq(s.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:s.id,status:s.status,pid:s.pid}).from(s).where(eq(s.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(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(s.id,t),eq(s.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:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(eq(s.status,"running")).all(),n=Date.now(),r=new Set,o=0;for(let i of e){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(t.db.update(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(s.id,i.id),eq(s.status,"running"))).run(),o++);continue}if(_n.has(i.platform??"cli"))continue;let l=`${i.id}:${i.run_epoch??0}`;r.add(l);let u=this.pidNullObservedSince.get(l);if(u===void 0){this.pidNullObservedSince.set(l,n);continue}n-u>=hn&&(t.db.update(s).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(s.id,i.id),eq(s.status,"running"))).run(),o++,this.pidNullObservedSince.delete(l));}for(let i of Array.from(this.pidNullObservedSince.keys()))r.has(i)||this.pidNullObservedSince.delete(i);return o}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=k(r);try{let i=e?eq(s.workspace_id,e):void 0,l=i?and(eq(s.id,t),i):eq(s.id,t),u=o.db.select().from(s).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),_=i?and(c,i):c;u=o.db.select().from(s).where(_).orderBy(desc(s.started_at)).limit(1).get()??void 0;}if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=e?and(eq(s.parent_task_id,t),eq(s.workspace_id,e)):eq(s.parent_task_id,t),c=l.db.select().from(s).where(u).orderBy(asc(s.started_at)).all();for(let _ of c)r.has(_.id)||(r.add(_.id),o.push(_));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return o}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,i=0,l=0;for(let u of n){if(!existsSync(u))continue;let c=k(u);try{let _=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),m=e?and(_,eq(o.workspace_id,e)):_,f=c.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(m).all();for(let S of f)r.has(S.id)||(r.add(S.id),s+=S.input_tokens??0,i+=S.output_tokens??0,l+=S.cost_usd??0);}catch(_){throw new d("DB_ERROR","Failed to get thread token usage",_)}finally{c.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),c=e?and(u,eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new 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(o.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(inArray(o.status,s));let i=t.q??t.search;i&&n.push(like(o.prompt,`%${i}%`)),t.from&&n.push(gte(o.started_at,t.from)),t.to&&n.push(lt$1(o.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(o).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).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,o=0,i=0,l=0;for(let u of n){if(!existsSync(u))continue;let c=k(u);try{let _=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),m=e?and(_,eq(s.workspace_id,e)):_,f=c.db.select({id:s.id,input_tokens:s.input_tokens,output_tokens:s.output_tokens,cost_usd:s.cost_usd}).from(s).where(m).all();for(let y of f)r.has(y.id)||(r.add(y.id),o+=y.input_tokens??0,i+=y.output_tokens??0,l+=y.cost_usd??0);}catch(_){throw new d("DB_ERROR","Failed to get thread token usage",_)}finally{c.close();}}return {inputTokens:o,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),c=e?and(u,eq(s.workspace_id,e)):u,_=l.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),o.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return o}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(s.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(s.agent_id,r));let o=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;o&&n.push(inArray(s.status,o));let i=t.q??t.search;i&&n.push(like(s.prompt,`%${i}%`)),t.from&&n.push(gte(s.started_at,t.from)),t.to&&n.push(lt(s.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(s).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at);return {rows:e.db.select().from(s).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,
@@ -37,11 +37,11 @@ ${n.join(`
37
37
  COALESCE(SUM(
38
38
  COALESCE(t.input_tokens, 0)
39
39
  + CASE
40
- WHEN t.started_at >= ${Y}
40
+ WHEN t.started_at >= ${J}
41
41
  AND (
42
42
  t.crewx_version IS NULL
43
43
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
44
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
44
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
45
45
  )
46
46
  THEN COALESCE(t.cached_input_tokens, 0)
47
47
  ELSE 0
@@ -60,11 +60,11 @@ ${n.join(`
60
60
  COALESCE(SUM(
61
61
  COALESCE(t.input_tokens, 0)
62
62
  + CASE
63
- WHEN t.started_at >= ${Y}
63
+ WHEN t.started_at >= ${J}
64
64
  AND (
65
65
  t.crewx_version IS NULL
66
66
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
67
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
67
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
68
68
  )
69
69
  THEN COALESCE(t.cached_input_tokens, 0)
70
70
  ELSE 0
@@ -80,11 +80,11 @@ ${n.join(`
80
80
  COALESCE(SUM(
81
81
  COALESCE(t.input_tokens, 0)
82
82
  + CASE
83
- WHEN t.started_at >= ${Y}
83
+ WHEN t.started_at >= ${J}
84
84
  AND (
85
85
  t.crewx_version IS NULL
86
86
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
87
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
87
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
88
88
  )
89
89
  THEN COALESCE(t.cached_input_tokens, 0)
90
90
  ELSE 0
@@ -102,11 +102,11 @@ ${n.join(`
102
102
  COALESCE(SUM(
103
103
  COALESCE(t.input_tokens, 0)
104
104
  + CASE
105
- WHEN t.started_at >= ${Y}
105
+ WHEN t.started_at >= ${J}
106
106
  AND (
107
107
  t.crewx_version IS NULL
108
108
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
109
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
109
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
110
110
  )
111
111
  THEN COALESCE(t.cached_input_tokens, 0)
112
112
  ELSE 0
@@ -114,18 +114,18 @@ ${n.join(`
114
114
  ), 0)
115
115
  + COALESCE(SUM(t.output_tokens), 0)
116
116
  ) DESC
117
- `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage",s)}finally{r.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
117
+ `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(o){throw new d("DB_ERROR","Failed to get agent usage",o)}finally{r.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
118
118
  SELECT
119
119
  date(t.started_at) AS date,
120
120
  t.agent_id,
121
121
  COALESCE(SUM(
122
122
  COALESCE(t.input_tokens, 0)
123
123
  + CASE
124
- WHEN t.started_at >= ${Y}
124
+ WHEN t.started_at >= ${J}
125
125
  AND (
126
126
  t.crewx_version IS NULL
127
127
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
128
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
128
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
129
129
  )
130
130
  THEN COALESCE(t.cached_input_tokens, 0)
131
131
  ELSE 0
@@ -148,11 +148,11 @@ ${n.join(`
148
148
  COALESCE(SUM(
149
149
  COALESCE(t.input_tokens, 0)
150
150
  + CASE
151
- WHEN t.started_at >= ${Y}
151
+ WHEN t.started_at >= ${J}
152
152
  AND (
153
153
  t.crewx_version IS NULL
154
154
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
155
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
155
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
156
156
  )
157
157
  THEN COALESCE(t.cached_input_tokens, 0)
158
158
  ELSE 0
@@ -167,79 +167,90 @@ ${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(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(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(o).where(and(eq(o.id,t),eq(o.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(),i=n?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,n)):and(eq(o.id,t),eq(o.status,"running"));r.db.update(o).set({status:"failed",error:e,completed_at:s}).where(i).run();}catch(s){throw s instanceof 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 i of n){if(!existsSync(i))continue;let l=k(i);try{let u=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),c=l.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let _ of c)r.has(_.id)||(r.add(_.id),s.push(_));}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(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(o){throw new d("DB_ERROR","Failed to get agent usage trend",o)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(s).where(and(eq(s.id,t),eq(s.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 o=new Date().toISOString(),i=n?and(eq(s.id,t),eq(s.status,"running"),eq(s.workspace_id,n)):and(eq(s.id,t),eq(s.status,"running"));r.db.update(s).set({status:"failed",error:e,completed_at:o}).where(i).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to mark task failed",o)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=e?and(like(s.prompt,`%${t}%`),eq(s.workspace_id,e)):like(s.prompt,`%${t}%`),c=l.db.select().from(s).where(u).orderBy(asc(s.started_at)).all();for(let _ of c)r.has(_.id)||(r.add(_.id),o.push(_));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return o}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=sql`
171
171
  CASE
172
- WHEN ${o.model} LIKE 'claude-%' OR ${o.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
173
- WHEN ${o.model} LIKE 'gpt-%' OR ${o.model} LIKE 'codex-%' THEN 'codex'
174
- WHEN ${o.model} LIKE 'gemini-%' THEN 'gemini'
175
- WHEN ${o.model} LIKE 'zai-%' OR ${o.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
176
- WHEN ${o.model} LIKE 'minimax/%' THEN 'minimax'
177
- WHEN ${o.model} LIKE 'qwen%' THEN 'qwen'
172
+ WHEN ${s.model} LIKE 'claude-%' OR ${s.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
173
+ WHEN ${s.model} LIKE 'gpt-%' OR ${s.model} LIKE 'codex-%' THEN 'codex'
174
+ WHEN ${s.model} LIKE 'gemini-%' THEN 'gemini'
175
+ WHEN ${s.model} LIKE 'zai-%' OR ${s.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
176
+ WHEN ${s.model} LIKE 'minimax/%' THEN 'minimax'
177
+ WHEN ${s.model} LIKE 'qwen%' THEN 'qwen'
178
178
  ELSE 'unknown'
179
179
  END
180
180
  `,i=sql`
181
- COALESCE(${o.input_tokens}, 0)
181
+ COALESCE(${s.input_tokens}, 0)
182
182
  + CASE
183
- WHEN ${o.started_at} >= ${Y}
183
+ WHEN ${s.started_at} >= ${J}
184
184
  AND (
185
- ${o.crewx_version} IS NULL
186
- OR (${o.crewx_version} LIKE '0.8.%' AND ${o.crewx_version} NOT LIKE '0.8.9%')
187
- OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${X}) AS INTEGER) < ${J})
185
+ ${s.crewx_version} IS NULL
186
+ OR (${s.crewx_version} LIKE '0.8.%' AND ${s.crewx_version} NOT LIKE '0.8.9%')
187
+ OR (${s.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${s.crewx_version}, ${V}) AS INTEGER) < ${Q})
188
188
  )
189
- THEN COALESCE(${o.cached_input_tokens}, 0)
189
+ THEN COALESCE(${s.cached_input_tokens}, 0)
190
190
  ELSE 0
191
191
  END
192
- `,l=n?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e} AND ${o.workspace_id} = ${n}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e}`;return r.db.all(sql`
192
+ `,l=n?sql`WHERE ${s.status} IN ('completed', 'success') AND ${s.started_at} >= ${t} AND ${s.started_at} < ${e} AND ${s.workspace_id} = ${n}`:sql`WHERE ${s.status} IN ('completed', 'success') AND ${s.started_at} >= ${t} AND ${s.started_at} < ${e}`;return r.db.all(sql`
193
193
  SELECT
194
- ${s} AS provider,
194
+ ${o} AS provider,
195
195
  COUNT(*) AS total_tasks,
196
196
  COALESCE(SUM(${i}), 0) AS input_tokens,
197
- COALESCE(SUM(${o.output_tokens}), 0) AS output_tokens,
198
- COALESCE(SUM(${o.cached_input_tokens}), 0) AS cached_input_tokens,
199
- COALESCE(SUM(${o.cost_usd}), 0) AS cost_usd,
200
- COALESCE(SUM(${o.duration_ms}), 0) AS active_duration_ms,
201
- MAX(${o.completed_at}) AS last_active_at
202
- FROM ${o}
197
+ COALESCE(SUM(${s.output_tokens}), 0) AS output_tokens,
198
+ COALESCE(SUM(${s.cached_input_tokens}), 0) AS cached_input_tokens,
199
+ COALESCE(SUM(${s.cost_usd}), 0) AS cost_usd,
200
+ COALESCE(SUM(${s.duration_ms}), 0) AS active_duration_ms,
201
+ MAX(${s.completed_at}) AS last_active_at
202
+ FROM ${s}
203
203
  ${l}
204
204
  GROUP BY provider
205
- ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${o.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();}}getModelUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=sql`
205
+ ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${s.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(o){throw new d("DB_ERROR","Failed to get provider usage",o)}finally{r.close();}}getModelUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=sql`
207
207
  CASE
208
- WHEN ${o.model} LIKE 'claude-%' OR ${o.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
209
- WHEN ${o.model} LIKE 'gpt-%' OR ${o.model} LIKE 'codex-%' THEN 'codex'
210
- WHEN ${o.model} LIKE 'gemini-%' THEN 'gemini'
211
- WHEN ${o.model} LIKE 'zai-%' OR ${o.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
212
- WHEN ${o.model} LIKE 'minimax/%' THEN 'minimax'
213
- WHEN ${o.model} LIKE 'qwen%' THEN 'qwen'
208
+ WHEN ${s.model} LIKE 'claude-%' OR ${s.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
209
+ WHEN ${s.model} LIKE 'gpt-%' OR ${s.model} LIKE 'codex-%' THEN 'codex'
210
+ WHEN ${s.model} LIKE 'gemini-%' THEN 'gemini'
211
+ WHEN ${s.model} LIKE 'zai-%' OR ${s.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
212
+ WHEN ${s.model} LIKE 'minimax/%' THEN 'minimax'
213
+ WHEN ${s.model} LIKE 'qwen%' THEN 'qwen'
214
214
  ELSE 'unknown'
215
215
  END
216
216
  `,i=sql`
217
- COALESCE(${o.input_tokens}, 0)
217
+ COALESCE(${s.input_tokens}, 0)
218
218
  + CASE
219
- WHEN ${o.started_at} >= ${Y}
219
+ WHEN ${s.started_at} >= ${J}
220
220
  AND (
221
- ${o.crewx_version} IS NULL
222
- OR (${o.crewx_version} LIKE '0.8.%' AND ${o.crewx_version} NOT LIKE '0.8.9%')
223
- OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${X}) AS INTEGER) < ${J})
221
+ ${s.crewx_version} IS NULL
222
+ OR (${s.crewx_version} LIKE '0.8.%' AND ${s.crewx_version} NOT LIKE '0.8.9%')
223
+ OR (${s.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${s.crewx_version}, ${V}) AS INTEGER) < ${Q})
224
224
  )
225
- THEN COALESCE(${o.cached_input_tokens}, 0)
225
+ THEN COALESCE(${s.cached_input_tokens}, 0)
226
226
  ELSE 0
227
227
  END
228
- `,l=n?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e} AND ${o.workspace_id} = ${n}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e}`,u=r.db.all(sql`
228
+ `,l=n?sql`WHERE ${s.status} IN ('completed', 'success') AND ${s.started_at} >= ${t} AND ${s.started_at} < ${e} AND ${s.workspace_id} = ${n}`:sql`WHERE ${s.status} IN ('completed', 'success') AND ${s.started_at} >= ${t} AND ${s.started_at} < ${e}`,u=r.db.all(sql`
229
229
  SELECT
230
- ${o.model} AS model,
231
- ${s} AS provider,
230
+ ${s.model} AS model,
231
+ ${o} AS provider,
232
232
  COUNT(*) AS total_tasks,
233
233
  COALESCE(SUM(${i}), 0) AS input_tokens,
234
- COALESCE(SUM(${o.output_tokens}), 0) AS output_tokens,
235
- COALESCE(SUM(${o.cached_input_tokens}), 0) AS cached_input_tokens,
236
- COALESCE(SUM(${o.cost_usd}), 0) AS cost_usd,
237
- COALESCE(SUM(${o.duration_ms}), 0) AS active_duration_ms,
238
- MAX(${o.completed_at}) AS last_active_at
239
- FROM ${o}
234
+ COALESCE(SUM(${s.output_tokens}), 0) AS output_tokens,
235
+ COALESCE(SUM(${s.cached_input_tokens}), 0) AS cached_input_tokens,
236
+ COALESCE(SUM(${s.cost_usd}), 0) AS cost_usd,
237
+ COALESCE(SUM(${s.duration_ms}), 0) AS active_duration_ms,
238
+ MAX(${s.completed_at}) AS last_active_at
239
+ FROM ${s}
240
240
  ${l}
241
- GROUP BY ${o.model}
242
- `),c=new Map;for(let _ of u){let m=Qt(_.model??""),f=c.get(m);f?(f.totalTasks+=_.total_tasks,f.inputTokens+=_.input_tokens,f.outputTokens+=_.output_tokens,f.cachedInputTokens+=_.cached_input_tokens,f.costUsd+=_.cost_usd,f.totalTokens+=_.input_tokens+_.output_tokens,f.activeDurationMs+=_.active_duration_ms??0,_.last_active_at&&(!f.lastActiveAt||_.last_active_at>f.lastActiveAt)&&(f.lastActiveAt=_.last_active_at)):c.set(m,{model:m,provider:_.provider,totalTasks:_.total_tasks,inputTokens:_.input_tokens,outputTokens:_.output_tokens,cachedInputTokens:_.cached_input_tokens,costUsd:_.cost_usd,totalTokens:_.input_tokens+_.output_tokens,activeDurationMs:_.active_duration_ms??0,lastActiveAt:_.last_active_at??null});}return Array.from(c.values()).sort((_,m)=>m.costUsd-_.costUsd)}catch(s){throw new d("DB_ERROR","Failed to get model usage",s)}finally{r.close();}}};var Ot=class extends x{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{N(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(eq(h.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
241
+ GROUP BY ${s.model}
242
+ `),c=new Map;for(let _ of u){let m=ne(_.model??""),f=c.get(m);f?(f.totalTasks+=_.total_tasks,f.inputTokens+=_.input_tokens,f.outputTokens+=_.output_tokens,f.cachedInputTokens+=_.cached_input_tokens,f.costUsd+=_.cost_usd,f.totalTokens+=_.input_tokens+_.output_tokens,f.activeDurationMs+=_.active_duration_ms??0,_.last_active_at&&(!f.lastActiveAt||_.last_active_at>f.lastActiveAt)&&(f.lastActiveAt=_.last_active_at)):c.set(m,{model:m,provider:_.provider,totalTasks:_.total_tasks,inputTokens:_.input_tokens,outputTokens:_.output_tokens,cachedInputTokens:_.cached_input_tokens,costUsd:_.cost_usd,totalTokens:_.input_tokens+_.output_tokens,activeDurationMs:_.active_duration_ms??0,lastActiveAt:_.last_active_at??null});}return Array.from(c.values()).sort((_,m)=>m.costUsd-_.costUsd)}catch(o){throw new d("DB_ERROR","Failed to get model usage",o)}finally{r.close();}}getTasksForReport(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=n?sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e} AND ${s.workspace_id} = ${n}`:sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e}`;return r.db.all(sql`
243
+ SELECT
244
+ ${s.thread_id} AS thread_id,
245
+ ${s.agent_id} AS agent_id,
246
+ ${s.started_at} AS started_at,
247
+ ${s.status} AS status,
248
+ ${s.error} AS error,
249
+ ${s.exit_code} AS exit_code
250
+ FROM ${s}
251
+ ${o}
252
+ ORDER BY ${s.started_at} ASC
253
+ `).map(l=>({threadId:l.thread_id,agentId:l.agent_id,startedAt:l.started_at,status:l.status,error:l.error,exitCode:l.exit_code}))}catch(o){throw new d("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}};var Lt=class extends x{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{A(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(eq(h.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
243
254
  ${t}.parent_task_id IS NULL
244
255
  OR ${t}.parent_task_id = ''
245
256
  OR NOT EXISTS (
@@ -247,7 +258,7 @@ ${n.join(`
247
258
  WHERE parent.id = ${t}.parent_task_id
248
259
  AND parent.thread_id = ${t}.thread_id
249
260
  )
250
- )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!existsSync(s))continue;let i=k(s);try{let l=t?eq(p.workspace_id,t):void 0,u=i.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{i.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 i=eq(p.id,t),l=e?and(i,eq(p.workspace_id,e)):i,u=s.db.select().from(p).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=k(r);try{let i=eq(p.id,t),l=e?and(i,eq(p.workspace_id,e)):i;if(s.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(i){throw new d("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,i=0,l=0,u=0,c=new Set;for(let _ of n){if(!existsSync(_))continue;let m=k(_);try{let f=m.db.get(sql`
261
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let o of e){if(!existsSync(o))continue;let i=k(o);try{let l=t?eq(p.workspace_id,t):void 0,u=i.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{i.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=k(r);try{let i=eq(p.id,t),l=e?and(i,eq(p.workspace_id,e)):i,u=o.db.select().from(p).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find thread by id",i)}finally{o.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=k(r);try{let i=eq(p.id,t),l=e?and(i,eq(p.workspace_id,e)):i;if(o.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(i){throw new d("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,o=0,i=0,l=0,u=0,c=new Set;for(let _ of n){if(!existsSync(_))continue;let m=k(_);try{let f=m.db.get(sql`
251
262
  SELECT
252
263
  count(*) AS cnt,
253
264
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -258,13 +269,13 @@ ${n.join(`
258
269
  WHERE child.thread_id = ${t}
259
270
  AND ${this.topLevelTaskPredicateSql()}
260
271
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
261
- `);f&&(r+=f.cnt,s+=f.total_input,i+=f.total_output,l+=f.total_cached,u+=f.total_cost);let S=m.db.all(sql`
272
+ `);f&&(r+=f.cnt,o+=f.total_input,i+=f.total_output,l+=f.total_cached,u+=f.total_cost);let y=m.db.all(sql`
262
273
  SELECT DISTINCT child.agent_id FROM tasks child
263
274
  WHERE child.thread_id = ${t}
264
275
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
265
276
  AND ${this.topLevelTaskPredicateSql()}
266
277
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
267
- `);for(let q of S)c.add(q.agent_id);}catch(f){throw new d("DB_ERROR","Failed to aggregate task stats",f)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),s=new Set,i=[];for(let l of r){if(!existsSync(l))continue;let u=k(l);try{let c;n!==void 0?c=u.db.all(sql`
278
+ `);for(let j of y)c.add(j.agent_id);}catch(f){throw new d("DB_ERROR","Failed to aggregate task stats",f)}finally{m.close();}}return {taskCount:r,inputTokens:o,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),o=new Set,i=[];for(let l of r){if(!existsSync(l))continue;let u=k(l);try{let c;n!==void 0?c=u.db.all(sql`
268
279
  SELECT * FROM (
269
280
  SELECT child.*,
270
281
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -281,18 +292,18 @@ ${n.join(`
281
292
  AND ${this.topLevelTaskPredicateSql()}
282
293
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
283
294
  ORDER BY child.started_at ASC
284
- `);for(let _ of c)s.has(_.id)||(s.add(_.id),i.push(_));}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 i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,_)=>(_.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,n));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=eq(o.thread_id,t),c=e?and(u,eq(o.workspace_id,e)):u,_=l.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new 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 i=k(s);try{let l=and(eq(o.id,e),eq(o.thread_id,t)),u=n?and(l,eq(o.workspace_id,n)):l,c=i.db.select().from(o).where(u).limit(1).get();if(!c)continue;let _=i.db.select().from(o).where(eq(o.parent_task_id,c.id)).orderBy(asc(o.started_at)).all();return {task:c,children:_}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=k(s);try{let l=i.db.all(sql`
295
+ `);for(let _ of c)o.has(_.id)||(o.add(_.id),i.push(_));}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 i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,_)=>(_.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,n));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=eq(s.thread_id,t),c=e?and(u,eq(s.workspace_id,e)):u,_=l.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),o.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return o}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let i=k(o);try{let l=and(eq(s.id,e),eq(s.thread_id,t)),u=n?and(l,eq(s.workspace_id,n)):l,c=i.db.select().from(s).where(u).limit(1).get();if(!c)continue;let _=i.db.select().from(s).where(eq(s.parent_task_id,c.id)).orderBy(asc(s.started_at)).all();return {task:c,children:_}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let i=k(o);try{let l=i.db.all(sql`
285
296
  SELECT child.* FROM tasks child
286
297
  WHERE child.thread_id IN (${sql.join(t.map(u=>sql`${u}`),sql`, `)})
287
298
  AND ${this.topLevelTaskPredicateSql()}
288
299
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
289
300
  ORDER BY child.started_at ASC
290
- `);for(let u of l){let c=u.thread_id;n.has(c)||n.set(c,[]),n.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=eq(p.id,t),i=n?and(s,eq(p.workspace_id,n)):s;if(!r.db.select({id:p.id}).from(p).where(i).limit(1).get())return;r.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,s=new Date().toISOString();if(n.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let l={updated_at:s};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(p).set(l).where(eq(p.id,t)).run();}else n.db.insert(p).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let s=n?this.validateWorkspaceId(r,n):null,i=r.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get();if(i){s&&!i.workspace_id&&r.db.update(p).set({workspace_id:s}).where(eq(p.id,t)).run();return}let l=new Date().toISOString();r.db.insert(p).values({id:t,platform:e,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:r.db.transaction(l=>{let c=l.select({message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()?.message_count===0;return l.run(sql`
301
+ `);for(let u of l){let c=u.thread_id;n.has(c)||n.set(c,[]),n.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=eq(p.id,t),i=n?and(o,eq(p.workspace_id,n)):o;if(!r.db.select({id:p.id}).from(p).where(i).limit(1).get())return;r.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update thread title",o)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,o=new Date().toISOString();if(n.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let l={updated_at:o};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(p).set(l).where(eq(p.id,t)).run();}else n.db.insert(p).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:o,updated_at:o}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let o=n?this.validateWorkspaceId(r,n):null,i=r.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get();if(i){o&&!i.workspace_id&&r.db.update(p).set({workspace_id:o}).where(eq(p.id,t)).run();return}let l=new Date().toISOString();r.db.insert(p).values({id:t,platform:e,workspace_id:o,message_count:0,created_at:l,updated_at:l}).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to ensure thread",o)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let o=new Date().toISOString();return {firstMessage:r.db.transaction(l=>{let c=l.select({message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()?.message_count===0;return l.run(sql`
291
302
  UPDATE threads
292
303
  SET first_message = COALESCE(first_message, ${e}),
293
304
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
294
305
  last_message = ${e},
295
306
  message_count = message_count + 1,
296
- updated_at = ${s}
307
+ updated_at = ${o}
297
308
  WHERE id = ${t}
298
- `),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 i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){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(),_=0;for(let m of c){let f=m.metadata?JSON.parse(m.metadata):{};typeof f.pinOrder=="number"&&f.pinOrder>_&&(_=f.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}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]),i=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.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 i=s.starred?0:1;return n.db.update(p).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let l=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return i.db.transaction(c=>{let _=c.select({metadata:p.metadata}).from(p).where(l).get();if(!_)return null;let m=_.metadata?JSON.parse(_.metadata):{},f=m.overdrive??{},S=r?.defaultTurns??f.defaultTurns??3,q=r?.updatedBy??"ui",M=new Date().toISOString(),v,y,B,st;switch(n){case "enable-count":{let ot=r?.turns??S,it=r?.consumeCurrent?Math.max(ot-1,0):ot;v=it>0?"count":"off",y=it,B=!0,st="count";break}case "enable-latch":{v="latch",y=0,B=!0,st="latch";break}case "disable":{v="off",y=0,B=!1;break}default:{let ot=f.state??"off",it=typeof f.remaining=="number"?f.remaining:0;if(ot==="count"&&it>0){let $t=it-1;$t<=0?(v="off",y=0):(v="count",y=$t),B=!0,st="count";}else ot==="latch"?(v="latch",y=0,B=!0,st="latch"):(v="off",y=0,B=!1);break}}return m.overdrive={state:v,remaining:y,defaultTurns:S,updatedAt:M,updatedBy:q},c.update(p).set({metadata:JSON.stringify(m),updated_at:M}).where(l).run(),{applied:B,appliedMode:st,state:v,remaining:y}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Nt=class extends x{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{N(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(W).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(W).where(eq(W.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(W).where(eq(W.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 Ct=class extends x{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{N(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(H).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(H).where(eq(H.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find 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:H.tool_name,count:sql`count(*)`}).from(H).where(eq(H.task_id,t)).groupBy(H.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 vt=class extends x{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{N(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(I).where(eq(I.thread_id,t)).orderBy(asc(I.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(I).where(and(eq(I.id,e),eq(I.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(I).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(I).where(eq(I.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 Lt=class extends x{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{N(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(nt).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(nt).orderBy(desc(nt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function de(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Pt=class extends x{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{N(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=de(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(A).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:[A.provider,A.account_ref,A.limit_window,A.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:A.provider,bucket_start:A.bucket_start,used_percent:A.used_percent,remaining_percent:A.remaining_percent,resets_at:A.resets_at}).from(A).where(and(eq(A.limit_window,t.window),gte(A.bucket_start,t.fromIso),lte(A.bucket_start,t.toIso))).orderBy(asc(A.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,i])=>({provider:s,points:i}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};export{x as BaseSqliteRepository,d as RepositoryError,Lt as RequestLogRepository,Nt as SpanRepository,At as TaskRepository,vt as ThreadBoxRepository,Ot as ThreadRepository,Ct as ToolCallRepository,Pt as UsageLimitSnapshotRepository,Tt as WorkspaceRepository,de as calcBucketStart,k as openDrizzleDb,Ye as pushSchema,et as runMigrations,N as runMigrationsOnce,o as tasks};
309
+ `),c},{behavior:"immediate"})}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save assistant message",o)}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),o=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!o)return null;let i=o.pinned?0:1,l=o.metadata?JSON.parse(o.metadata):{};if(i){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(),_=0;for(let m of c){let f=m.metadata?JSON.parse(m.metadata):{};typeof f.pinOrder=="number"&&f.pinOrder>_&&(_=f.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}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 o=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),i=n.db.select({metadata:p.metadata}).from(p).where(o).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(o).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),o=n.db.select({starred:p.starred}).from(p).where(r).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(p).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let l=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return i.db.transaction(c=>{let _=c.select({metadata:p.metadata}).from(p).where(l).get();if(!_)return null;let m=_.metadata?JSON.parse(_.metadata):{},f=m.overdrive??{},y=r?.defaultTurns??f.defaultTurns??3,j=r?.updatedBy??"ui",z=new Date().toISOString(),v,S,U,it;switch(n){case "enable-count":{let at=r?.turns??y,dt=r?.consumeCurrent?Math.max(at-1,0):at;v=dt>0?"count":"off",S=dt,U=!0,it="count";break}case "enable-latch":{v="latch",S=0,U=!0,it="latch";break}case "disable":{v="off",S=0,U=!1;break}default:{let at=f.state??"off",dt=typeof f.remaining=="number"?f.remaining:0;if(at==="count"&&dt>0){let Mt=dt-1;Mt<=0?(v="off",S=0):(v="count",S=Mt),U=!0,it="count";}else at==="latch"?(v="latch",S=0,U=!0,it="latch"):(v="off",S=0,U=!1);break}}return m.overdrive={state:v,remaining:S,defaultTurns:y,updatedAt:z,updatedBy:j},c.update(p).set({metadata:JSON.stringify(m),updated_at:z}).where(l).run(),{applied:U,appliedMode:it,state:v,remaining:S}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var $t=class extends x{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{A(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(G).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(G).where(eq(G.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(G).where(eq(G.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 Pt=class extends x{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{A(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(q).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(q).where(eq(q.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:q.tool_name,count:sql`count(*)`}).from(q).where(eq(q.task_id,t)).groupBy(q.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 It=class extends x{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{A(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(B).where(eq(B.thread_id,t)).orderBy(asc(B.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(B).where(and(eq(B.id,e),eq(B.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(B).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(B).where(eq(B.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 Bt=class extends x{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{A(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 o of t)r.insert(st).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:n,metadata:o.metadata??null}).run();});}catch(n){throw n instanceof 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(st).orderBy(desc(st.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function pe(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Ut=class extends x{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{A(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=pe(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(O).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:[O.provider,O.account_ref,O.limit_window,O.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:O.provider,bucket_start:O.bucket_start,used_percent:O.used_percent,remaining_percent:O.remaining_percent,resets_at:O.resets_at}).from(O).where(and(eq(O.limit_window,t.window),gte(O.bucket_start,t.fromIso),lte(O.bucket_start,t.toIso))).orderBy(asc(O.bucket_start)).all(),r=new Map;for(let o of n)r.has(o.provider)||r.set(o.provider,[]),r.get(o.provider).push({bucketStart:o.bucket_start,usedPercent:o.used_percent,remainingPercent:o.remaining_percent,resetsAt:o.resets_at??null});return Array.from(r.entries()).map(([o,i])=>({provider:o,points:i}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var Ht=class extends x{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{A(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(L).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[L.workspace_id,L.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let n=e.db.select().from(L).where(and(eq(L.workspace_id,t.workspaceId),eq(L.month,t.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{e.close();}}findByMonth(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(L).where(and(eq(L.workspace_id,t),eq(L.month,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{n.close();}}listByWorkspace(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(L).where(eq(L.workspace_id,t)).orderBy(desc(L.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};export{x as BaseSqliteRepository,d as RepositoryError,Bt as RequestLogRepository,$t as SpanRepository,vt as TaskRepository,It as ThreadBoxRepository,Lt as ThreadRepository,Pt as ToolCallRepository,Ut as UsageLimitSnapshotRepository,Ht as UsageReportRepository,Ot as WorkspaceRepository,pe as calcBucketStart,k as openDrizzleDb,sn as pushSchema,rt as runMigrations,A as runMigrationsOnce,s as tasks};