@crewx/sdk 0.9.0-rc.36 → 0.9.0-rc.38

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 Q from'path';import Q__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import fe,{existsSync,mkdirSync,readFileSync}from'fs';import Qe from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,lt,or,like,asc,inArray,gte,notLike,lte}from'drizzle-orm';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var xt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var Ye=()=>fileURLToPath(import.meta.url),Xe=()=>Q__default.dirname(Ye()),R=Xe();var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Qe.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,n,e){super(n),this.name="RepositoryError",this.code=t,this.cause=e,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=xt("better-sqlite3"),{drizzle:n}=xt("drizzle-orm/better-sqlite3"),e=new t(a);return e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA busy_timeout = 5000"),e.exec("PRAGMA foreign_keys = ON"),e.exec("PRAGMA analysis_limit = 400"),e.exec("PRAGMA optimize"),{db:n(e),runRaw:(r,s=[])=>e.prepare(r).run(...s),close:()=>e.close()}}var ne=new Set,Ze={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function $t(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function tn(a,t){if(t>0||!$t(a,"tasks"))return;let n=a.all("PRAGMA table_info(tasks)"),e=new Set(n.map(r=>r.name));for(let[r,s]of Object.entries(Ze))e.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var en={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function nn(a,t,n){if(!$t(a,"__drizzle_migrations")||!$t(a,"tasks"))return;let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(readFileSync(Q__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=en[i.tag];if(!l)continue;let u=Q__default.join(t,`${i.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),p=createHash("sha256").update(c).digest("hex");if(r.has(p))continue;let h=a.all("PRAGMA table_info(tasks)"),f=new Set(h.map(S=>S.name));for(let[S,P]of Object.entries(l))f.has(S)||(a.run(`ALTER TABLE tasks ADD COLUMN ${S} ${P}`),f.add(S));}}function rn(a,t,n){let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(readFileSync(Q__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=Q__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 p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,h=[],f;for(;(f=p.exec(u))!==null;)h.push({table:f[1],column:f[2]});if(h.length===0||!u.split(/-->\s*statement-breakpoint/).map($=>$.trim()).filter(Boolean).every($=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test($)))continue;h.every(({table:$,column:H})=>a.all(`PRAGMA table_info("${$}")`).some(G=>G.name===H))&&a.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function _t(a){let{migrate:t}=xt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=xt("drizzle-orm"),e=[Q__default.join(R,"../migrations"),Q__default.join(R,"migrations"),Q__default.join(R,"../../../../drizzle/migrations"),Q__default.join(process.cwd(),"drizzle/migrations")],r=e.find(c=>existsSync(Q__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
1
+ import*as Z from'path';import Z__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import me,{existsSync,mkdirSync,readFileSync}from'fs';import Ze from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,lt,or,like,asc,inArray,gte,notLike,lte}from'drizzle-orm';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var Tt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var Xe=()=>fileURLToPath(import.meta.url),Je=()=>Z__default.dirname(Xe()),R=Je();var T=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ze.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,n,e){super(n),this.name="RepositoryError",this.code=t,this.cause=e,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=Tt("better-sqlite3"),{drizzle:n}=Tt("drizzle-orm/better-sqlite3"),e=new t(a);return e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA busy_timeout = 5000"),e.exec("PRAGMA foreign_keys = ON"),e.exec("PRAGMA analysis_limit = 400"),e.exec("PRAGMA optimize"),{db:n(e),runRaw:(r,s=[])=>e.prepare(r).run(...s),close:()=>e.close()}}var re=new Set,tn={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 Bt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function en(a,t){if(t>0||!Bt(a,"tasks"))return;let n=a.all("PRAGMA table_info(tasks)"),e=new Set(n.map(r=>r.name));for(let[r,s]of Object.entries(tn))e.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var nn={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function rn(a,t,n){if(!Bt(a,"__drizzle_migrations")||!Bt(a,"tasks"))return;let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(readFileSync(Z__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=nn[i.tag];if(!l)continue;let u=Z__default.join(t,`${i.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),p=createHash("sha256").update(c).digest("hex");if(r.has(p))continue;let h=a.all("PRAGMA table_info(tasks)"),f=new Set(h.map(x=>x.name));for(let[x,L]of Object.entries(l))f.has(x)||(a.run(`ALTER TABLE tasks ADD COLUMN ${x} ${L}`),f.add(x));}}function on(a,t,n){let e=a.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(e.map(i=>i.hash)),s=JSON.parse(readFileSync(Z__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=Z__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 p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,h=[],f;for(;(f=p.exec(u))!==null;)h.push({table:f[1],column:f[2]});if(h.length===0||!u.split(/-->\s*statement-breakpoint/).map(B=>B.trim()).filter(Boolean).every(B=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(B)))continue;h.every(({table:B,column:M})=>a.all(`PRAGMA table_info("${B}")`).some(Y=>Y.name===M))&&a.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function _t(a){let{migrate:t}=Tt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=Tt("drizzle-orm"),e=[Z__default.join(R,"../migrations"),Z__default.join(R,"migrations"),Z__default.join(R,"../../../../drizzle/migrations"),Z__default.join(process.cwd(),"drizzle/migrations")],r=e.find(c=>existsSync(Z__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
2
2
  ${e.join(`
3
- `)}`);let s=a.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),tn(a,i),s?.cnt&&(rn(a,r,n),nn(a,r,n)),t(a,{migrationsFolder:r});let u=(a.get(n`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 A(a,t){ne.has(t)||(_t(a),ne.add(t));}var m=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 _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>m.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),idx_threads_title:index("idx_threads_title").on(a.title)}));var tt=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(()=>tt.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 X=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 j=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.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 ht=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 I=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 M=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)}));var k=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},a=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(a.workspace_id,sql`${a.created_at} DESC`)})),C=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},a=>({pk:primaryKey({columns:[a.notification_id,a.user_id]})}));var v=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},a=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(a.workspace_id,a.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(a.workspace_id,a.created_at)}));function Ht(a){let t=Q.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(n,e)=>`${e.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function pe(a){let t=Ht(a);return createHash("sha256").update(t).digest("hex")}function Ct(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Ft=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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{_t(e.db);}catch(r){throw e.close(),r}return e}resolveSlug(t,n,e){let r=Ct(basename(e)),i=`${Ct(basename(dirname(e)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:m.id}).from(m).where(and(eq(m.slug,c),ne$1(m.id,n))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let p=`${i}-${c}`;if(!u(p))return p}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let n=t.db.select({id:m.id,slug:m.slug}).from(m).all(),e=0;for(let r of n)if(r.slug.includes("/")){let s=Ct(r.slug.replace(/\//g,"-"));t.db.update(m).set({slug:s,updated_at:new Date().toISOString()}).where(eq(m.id,r.id)).run(),e+=1;}return {updated:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to normalize legacy slugs",n)}finally{t.close();}}ensureRow(t,n){let{id:e,slug:r,name:s,workspacePath:i}=n,l=new Date().toISOString();t.insert(m).values({id:e,slug:r,name:s,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(m).set({workspace_path:i,updated_at:l}).where(and(eq(m.id,e),isNull(m.workspace_path))).run();}registerWorkspace(t){let n=Ht(t),e=this.openHandle(true);try{let r=pe(n),s=basename(n),i=this.resolveSlug(e.db,r,n);return this.ensureRow(e.db,{id:r,slug:i,name:s,workspacePath:n}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{e.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=t.isActive!==void 0?eq(m.is_active,t.isActive?1:0):void 0,r=n.db.select({count:sql`count(*)`}).from(m).where(e).get();return {rows:n.db.select().from(m).where(e).orderBy(desc(m.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(e){throw new d("DB_ERROR","Failed to list projects",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(m).where(eq(m.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace",e)}finally{n.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.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(e){throw new d("DB_ERROR","Failed to find agents by project",e)}finally{n.close();}}findThreadsByProject(t,n){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let r=e.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:e.db.all(sql`SELECT t.*,
3
+ `)}`);let s=a.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=a.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),en(a,i),s?.cnt&&(on(a,r,n),rn(a,r,n)),t(a,{migrationsFolder:r});let u=(a.get(n`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 O(a,t){re.has(t)||(_t(a),re.add(t));}var m=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 _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>m.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),idx_threads_title:index("idx_threads_title").on(a.title)}));var et=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(()=>et.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 J=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 W=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.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 ht=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 P=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 F=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)}));var k=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},a=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(a.workspace_id,sql`${a.created_at} DESC`)})),I=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},a=>({pk:primaryKey({columns:[a.notification_id,a.user_id]})}));var E=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},a=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(a.workspace_id,a.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(a.workspace_id,a.created_at)}));function Mt(a){let t=Z.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(n,e)=>`${e.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function _e(a){let t=Mt(a);return createHash("sha256").update(t).digest("hex")}function It(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var qt=class extends T{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{_t(e.db);}catch(r){throw e.close(),r}return e}resolveSlug(t,n,e){let r=It(basename(e)),i=`${It(basename(dirname(e)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:m.id}).from(m).where(and(eq(m.slug,c),ne(m.id,n))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let p=`${i}-${c}`;if(!u(p))return p}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let n=t.db.select({id:m.id,slug:m.slug}).from(m).all(),e=0;for(let r of n)if(r.slug.includes("/")){let s=It(r.slug.replace(/\//g,"-"));t.db.update(m).set({slug:s,updated_at:new Date().toISOString()}).where(eq(m.id,r.id)).run(),e+=1;}return {updated:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to normalize legacy slugs",n)}finally{t.close();}}ensureRow(t,n){let{id:e,slug:r,name:s,workspacePath:i}=n,l=new Date().toISOString();t.insert(m).values({id:e,slug:r,name:s,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(m).set({workspace_path:i,updated_at:l}).where(and(eq(m.id,e),isNull(m.workspace_path))).run();}registerWorkspace(t){let n=Mt(t),e=this.openHandle(true);try{let r=_e(n),s=basename(n),i=this.resolveSlug(e.db,r,n);return this.ensureRow(e.db,{id:r,slug:i,name:s,workspacePath:n}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{e.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=t.isActive!==void 0?eq(m.is_active,t.isActive?1:0):void 0,r=n.db.select({count:sql`count(*)`}).from(m).where(e).get();return {rows:n.db.select().from(m).where(e).orderBy(desc(m.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(e){throw new d("DB_ERROR","Failed to list projects",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(m).where(eq(m.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace",e)}finally{n.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.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(e){throw new d("DB_ERROR","Failed to find agents by project",e)}finally{n.close();}}findThreadsByProject(t,n){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let r=e.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:e.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 ${n.limit} OFFSET ${n.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{e.close();}}findBySlug(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(m).where(eq(m.slug,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace by slug",e)}finally{n.close();}}slugExists(t,n){if(!this.dbExists())return false;let e=this.openHandle(false);try{let r=n?and(eq(m.slug,t),ne$1(m.id,n)):eq(m.slug,t);return !!e.db.select({id:m.id}).from(m).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{e.close();}}insert(t,n,e,r){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(m).values({id:t,slug:n,name:e,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(m).where(eq(m.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,n,e){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${n.join(", ")} WHERE id = ?`,e);let s=r.db.select().from(m).where(eq(m.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 n=t.db.select({id:m.id,workspace_path:m.workspace_path}).from(m).where(and(eq(m.is_active,1),isNotNull(m.workspace_path))).all(),e=0;for(let r of n){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(m).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(m.id,r.id)).run(),e+=1);}return {softDeleted:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",n)}finally{t.close();}}delete(t){let n=this.openHandle(true);try{n.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),n.db.delete(m).where(eq(m.id,t)).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to delete workspace",e)}finally{n.close();}}};var ge=[m,o,_,tt,X,j,ht];function $n(){return Q__default.join(Qe.homedir(),".crewx","crewx.db")}function Bn(a){if(!fe.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),n=`${a}.bak-${t}`;return fe.copyFileSync(a,n),n}function we(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(n=>n.name))}function Un(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 Hn(a){let t=a.getSQLType(),n=`"${a.name}" ${t}`,e=Un(a.default);return e!==null&&(n+=` DEFAULT ${e}`),a.notNull&&(n+=" NOT NULL"),n}function Mn(a,t){let n=t?.dbPath??$n(),e=t?.force??false,r=t?.dryRun??false,s=r?null:Bn(n);if(e&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=we(a);if(!r)try{_t(a);}catch(h){let f=h instanceof Error?`${h.message} ${h.cause?.message??""}`:"";if(!e||!f.includes("duplicate column"))throw h}let l,u;r?(l=ge.map(f=>getTableConfig(f).name).filter(f=>!i.has(f)),u=i):(u=we(a),l=[...u].filter(h=>!i.has(h)));let c=[],p=[];for(let h of ge){let f=getTableConfig(h),S=f.name;if(!u.has(S))continue;let P=a.all(`PRAGMA table_info("${S}")`),$=new Set(P.map(N=>N.name)),H=new Set(f.columns.map(N=>N.name));for(let N of f.columns)if(!$.has(N.name)){if(!r){let G=Hn(N);a.run(`ALTER TABLE "${S}" ADD COLUMN ${G}`);}c.push({table:S,column:N.name});}for(let N of P)H.has(N.name)||p.push(`${S}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:p,backupPath:s}}function ke(a){let t=a.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let n=t.lastIndexOf("/");return n>=0&&(t=t.slice(n+1)),t=t.replace(/-\d{8}$/,""),t}var st="2026-05-09",Gn="0.8.9-rc.13",it=10,at=parseInt(Gn.split("rc.")[1]),Yn=new Set(["workflow","mcp"]),Re=600*1e3,jt=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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}startTask(t){let n=this.openHandle(true);try{n.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(e){throw e instanceof d?e:new d("DB_ERROR","Failed to start task",e)}finally{n.close();}}finishTask(t){let n=this.openHandle(true);try{let e=t.runEpoch??null;n.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${n.limit} OFFSET ${n.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{e.close();}}findBySlug(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(m).where(eq(m.slug,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find workspace by slug",e)}finally{n.close();}}slugExists(t,n){if(!this.dbExists())return false;let e=this.openHandle(false);try{let r=n?and(eq(m.slug,t),ne(m.id,n)):eq(m.slug,t);return !!e.db.select({id:m.id}).from(m).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{e.close();}}insert(t,n,e,r){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(m).values({id:t,slug:n,name:e,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(m).where(eq(m.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,n,e){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${n.join(", ")} WHERE id = ?`,e);let s=r.db.select().from(m).where(eq(m.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 n=t.db.select({id:m.id,workspace_path:m.workspace_path}).from(m).where(and(eq(m.is_active,1),isNotNull(m.workspace_path))).all(),e=0;for(let r of n){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(m).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(m.id,r.id)).run(),e+=1);}return {softDeleted:e,checked:n.length}}catch(n){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",n)}finally{t.close();}}delete(t){let n=this.openHandle(true);try{n.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),n.db.delete(m).where(eq(m.id,t)).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to delete workspace",e)}finally{n.close();}}};var we=[m,o,_,et,J,W,ht];function Bn(){return Z__default.join(Ze.homedir(),".crewx","crewx.db")}function Un(a){if(!me.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),n=`${a}.bak-${t}`;return me.copyFileSync(a,n),n}function ke(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(n=>n.name))}function Hn(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 Mn(a){let t=a.getSQLType(),n=`"${a.name}" ${t}`,e=Hn(a.default);return e!==null&&(n+=` DEFAULT ${e}`),a.notNull&&(n+=" NOT NULL"),n}function Fn(a,t){let n=t?.dbPath??Bn(),e=t?.force??false,r=t?.dryRun??false,s=r?null:Un(n);if(e&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=ke(a);if(!r)try{_t(a);}catch(h){let f=h instanceof Error?`${h.message} ${h.cause?.message??""}`:"";if(!e||!f.includes("duplicate column"))throw h}let l,u;r?(l=we.map(f=>getTableConfig(f).name).filter(f=>!i.has(f)),u=i):(u=ke(a),l=[...u].filter(h=>!i.has(h)));let c=[],p=[];for(let h of we){let f=getTableConfig(h),x=f.name;if(!u.has(x))continue;let L=a.all(`PRAGMA table_info("${x}")`),B=new Set(L.map(A=>A.name)),M=new Set(f.columns.map(A=>A.name));for(let A of f.columns)if(!B.has(A.name)){if(!r){let Y=Mn(A);a.run(`ALTER TABLE "${x}" ADD COLUMN ${Y}`);}c.push({table:x,column:A.name});}for(let A of L)M.has(A.name)||p.push(`${x}.${A.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:p,backupPath:s}}function be(a){let t=a.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let n=t.lastIndexOf("/");return n>=0&&(t=t.slice(n+1)),t=t.replace(/-\d{8}$/,""),t}var it="2026-05-09",Yn="0.8.9-rc.13",at=10,dt=parseInt(Yn.split("rc.")[1]),Xn=new Set(["workflow","mcp"]),Ee=600*1e3,Wt=class extends T{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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}startTask(t){let n=this.openHandle(true);try{n.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(e){throw e instanceof d?e:new d("DB_ERROR","Failed to start task",e)}finally{n.close();}}finishTask(t){let n=this.openHandle(true);try{let e=t.runEpoch??null;n.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,e]);}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to finish task",e)}finally{n.close();}}appendLog(t,n){let e=this.openHandle(true);try{e.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(n),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{e.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(n){throw new d("DB_ERROR","Failed to get running tasks",n)}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(n){throw new d("DB_ERROR","Failed to get all tasks",n)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to get task",e)}finally{n.close();}}killTask(t){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let e=n.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!e||e.status!=="running")return {killed:!1};if(e.pid)try{process.kill(e.pid,"SIGTERM");}catch{}return n.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:e.pid??void 0}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to kill task",e)}finally{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=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(),e=Date.now(),r=new Set,s=0;for(let i of n){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(Yn.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,e);continue}e-u>=Re&&(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();}}reapRunningWorkflowTasks(t=Re){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let e=new Date(Date.now()-t).toISOString();return n.db.update(o).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(o.status,"running"),eq(o.platform,"workflow"),isNull(o.pid),lt(o.started_at,e))).run().changes??0}finally{n.close();}}findTaskStatus(t,n){let e=this.resolveDbPaths();for(let r of e){if(!existsSync(r))continue;let s=w(r);try{let i=n?eq(o.workspace_id,n):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}%`))),p=i?and(c,i):c;u=s.db.select().from(o).where(p).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,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!existsSync(i))continue;let l=w(i);try{let u=n?and(eq(o.parent_task_id,t),eq(o.workspace_id,n)):eq(o.parent_task_id,t),c=l.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let p of c)r.has(p.id)||(r.add(p.id),s.push(p));}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 n=this.openHandle(false);try{return n.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,e]);}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to finish task",e)}finally{n.close();}}appendLog(t,n){let e=this.openHandle(true);try{e.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(n),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{e.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(n){throw new d("DB_ERROR","Failed to get running tasks",n)}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(n){throw new d("DB_ERROR","Failed to get all tasks",n)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to get task",e)}finally{n.close();}}killTask(t){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let e=n.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!e||e.status!=="running")return {killed:!1};if(e.pid)try{process.kill(e.pid,"SIGTERM");}catch{}return n.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:e.pid??void 0}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to kill task",e)}finally{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=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(),e=Date.now(),r=new Set,s=0;for(let i of n){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(Xn.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,e);continue}e-u>=Ee&&(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();}}reapRunningWorkflowTasks(t=Ee){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let e=new Date(Date.now()-t).toISOString();return n.db.update(o).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(o.status,"running"),eq(o.platform,"workflow"),isNull(o.pid),lt(o.started_at,e))).run().changes??0}finally{n.close();}}findTaskStatus(t,n){let e=this.resolveDbPaths();for(let r of e){if(!existsSync(r))continue;let s=w(r);try{let i=n?eq(o.workspace_id,n):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}%`))),p=i?and(c,i):c;u=s.db.select().from(o).where(p).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,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!existsSync(i))continue;let l=w(i);try{let u=n?and(eq(o.parent_task_id,t),eq(o.workspace_id,n)):eq(o.parent_task_id,t),c=l.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let p of c)r.has(p.id)||(r.add(p.id),s.push(p));}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 n=this.openHandle(false);try{return n.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 @@ ${e.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(e){throw new d("DB_ERROR","Failed to get workspace usage summary",e)}finally{n.close();}}getThreadTokenUsage(t,n){let e=this.resolveDbPaths(),r=new Set,s=0,i=0,l=0;for(let u of e){if(!existsSync(u))continue;let c=w(u);try{let p=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),h=n?and(p,eq(o.workspace_id,n)):p,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(h).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(p){throw new d("DB_ERROR","Failed to get thread token usage",p)}finally{c.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!existsSync(i))continue;let l=w(i);try{let u=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),c=n?and(u,eq(o.workspace_id,n)):u,p=l.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of p)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}parseWorkflowCardMetadata(t){if(!t)return {};try{let n=JSON.parse(t);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}batchFetchWorkflowCards(t,n){let e=new Map;if(t.length===0)return e;let r=new Set(t),s=new Map,i=n?eq(o.workspace_id,n):void 0,l=(u,c)=>{if(!u)return;let p=s.get(u);if(p&&c.started_at<=p)return;let h=this.parseWorkflowCardMetadata(c.metadata);h.kind==="workflow_card"&&(s.set(u,c.started_at),e.set(u,{taskId:c.id,workflowRunId:h.workflowRunId,raw:c.result??void 0}));};for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let c=w(u);try{let p=and(inArray(o.thread_id,t),like(o.metadata,'%"kind":"workflow_card"%')),h=c.db.select({id:o.id,thread_id:o.thread_id,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(i?and(p,i):p).all();for(let P of h)l(P.thread_id,P);let f=and(isNull(o.thread_id),like(o.metadata,'%"kind":"workflow_card"%')),S=c.db.select({id:o.id,command:o.command,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(i?and(f,i):f).all();for(let P of S){let $=this.extractThreadIdFromCommand(P.command);!$||!r.has($)||l($,P);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{c.close();}}return e}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=[];t.workspaceId&&e.push(eq(o.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&e.push(inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&e.push(inArray(o.status,s));let i=t.q??t.search;i&&e.push(like(o.prompt,`%${i}%`)),t.from&&e.push(gte(o.started_at,t.from)),t.to&&e.push(lt(o.started_at,t.to));let l=e.length>0?and(...e):void 0,u=n.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:n.db.select().from(o).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(e){throw new d("DB_ERROR","Failed to find all tasks",e)}finally{n.close();}}getAgentUsage(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(e?sql`
32
+ `)}catch(e){throw new d("DB_ERROR","Failed to get workspace usage summary",e)}finally{n.close();}}getThreadTokenUsage(t,n){let e=this.resolveDbPaths(),r=new Set,s=0,i=0,l=0;for(let u of e){if(!existsSync(u))continue;let c=w(u);try{let p=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),h=n?and(p,eq(o.workspace_id,n)):p,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(h).all();for(let x of f)r.has(x.id)||(r.add(x.id),s+=x.input_tokens??0,i+=x.output_tokens??0,l+=x.cost_usd??0);}catch(p){throw new d("DB_ERROR","Failed to get thread token usage",p)}finally{c.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,n){let e=this.resolveDbPaths(),r=new Set,s=[];for(let i of e){if(!existsSync(i))continue;let l=w(i);try{let u=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),c=n?and(u,eq(o.workspace_id,n)):u,p=l.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of p)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}parseWorkflowCardMetadata(t){if(!t)return {};try{let n=JSON.parse(t);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}batchFetchWorkflowCards(t,n){let e=new Map;if(t.length===0)return e;let r=new Set(t),s=new Map,i=n?eq(o.workspace_id,n):void 0,l=(u,c)=>{if(!u)return;let p=s.get(u);if(p&&c.started_at<=p)return;let h=this.parseWorkflowCardMetadata(c.metadata);h.kind==="workflow_card"&&(s.set(u,c.started_at),e.set(u,{taskId:c.id,workflowRunId:h.workflowRunId,raw:c.result??void 0}));};for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let c=w(u);try{let p=and(inArray(o.thread_id,t),like(o.metadata,'%"kind":"workflow_card"%')),h=c.db.select({id:o.id,thread_id:o.thread_id,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(i?and(p,i):p).all();for(let L of h)l(L.thread_id,L);let f=and(isNull(o.thread_id),like(o.metadata,'%"kind":"workflow_card"%')),x=c.db.select({id:o.id,command:o.command,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(i?and(f,i):f).all();for(let L of x){let B=this.extractThreadIdFromCommand(L.command);!B||!r.has(B)||l(B,L);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{c.close();}}return e}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let e=[];t.workspaceId&&e.push(eq(o.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&e.push(inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&e.push(inArray(o.status,s));let i=t.q??t.search;i&&e.push(like(o.prompt,`%${i}%`)),t.from&&e.push(gte(o.started_at,t.from)),t.to&&e.push(lt(o.started_at,t.to));let l=e.length>0?and(...e):void 0,u=n.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:n.db.select().from(o).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(e){throw new d("DB_ERROR","Failed to find all tasks",e)}finally{n.close();}}getAgentUsage(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(e?sql`
33
33
  SELECT
34
34
  t.agent_id,
35
35
  t.workspace_id,
@@ -37,11 +37,11 @@ ${e.join(`
37
37
  COALESCE(SUM(
38
38
  COALESCE(t.input_tokens, 0)
39
39
  + CASE
40
- WHEN t.started_at >= ${st}
40
+ WHEN t.started_at >= ${it}
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, ${it}) AS INTEGER) < ${at})
44
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${at}) AS INTEGER) < ${dt})
45
45
  )
46
46
  THEN COALESCE(t.cached_input_tokens, 0)
47
47
  ELSE 0
@@ -60,11 +60,11 @@ ${e.join(`
60
60
  COALESCE(SUM(
61
61
  COALESCE(t.input_tokens, 0)
62
62
  + CASE
63
- WHEN t.started_at >= ${st}
63
+ WHEN t.started_at >= ${it}
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, ${it}) AS INTEGER) < ${at})
67
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${at}) AS INTEGER) < ${dt})
68
68
  )
69
69
  THEN COALESCE(t.cached_input_tokens, 0)
70
70
  ELSE 0
@@ -80,11 +80,11 @@ ${e.join(`
80
80
  COALESCE(SUM(
81
81
  COALESCE(t.input_tokens, 0)
82
82
  + CASE
83
- WHEN t.started_at >= ${st}
83
+ WHEN t.started_at >= ${it}
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, ${it}) AS INTEGER) < ${at})
87
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${at}) AS INTEGER) < ${dt})
88
88
  )
89
89
  THEN COALESCE(t.cached_input_tokens, 0)
90
90
  ELSE 0
@@ -102,11 +102,11 @@ ${e.join(`
102
102
  COALESCE(SUM(
103
103
  COALESCE(t.input_tokens, 0)
104
104
  + CASE
105
- WHEN t.started_at >= ${st}
105
+ WHEN t.started_at >= ${it}
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, ${it}) AS INTEGER) < ${at})
109
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${at}) AS INTEGER) < ${dt})
110
110
  )
111
111
  THEN COALESCE(t.cached_input_tokens, 0)
112
112
  ELSE 0
@@ -121,11 +121,11 @@ ${e.join(`
121
121
  COALESCE(SUM(
122
122
  COALESCE(t.input_tokens, 0)
123
123
  + CASE
124
- WHEN t.started_at >= ${st}
124
+ WHEN t.started_at >= ${it}
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, ${it}) AS INTEGER) < ${at})
128
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${at}) AS INTEGER) < ${dt})
129
129
  )
130
130
  THEN COALESCE(t.cached_input_tokens, 0)
131
131
  ELSE 0
@@ -148,11 +148,11 @@ ${e.join(`
148
148
  COALESCE(SUM(
149
149
  COALESCE(t.input_tokens, 0)
150
150
  + CASE
151
- WHEN t.started_at >= ${st}
151
+ WHEN t.started_at >= ${it}
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, ${it}) AS INTEGER) < ${at})
155
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${at}) AS INTEGER) < ${dt})
156
156
  )
157
157
  THEN COALESCE(t.cached_input_tokens, 0)
158
158
  ELSE 0
@@ -180,11 +180,11 @@ ${e.join(`
180
180
  `,i=sql`
181
181
  COALESCE(${o.input_tokens}, 0)
182
182
  + CASE
183
- WHEN ${o.started_at} >= ${st}
183
+ WHEN ${o.started_at} >= ${it}
184
184
  AND (
185
185
  ${o.crewx_version} IS NULL
186
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}, ${it}) AS INTEGER) < ${at})
187
+ OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${at}) AS INTEGER) < ${dt})
188
188
  )
189
189
  THEN COALESCE(${o.cached_input_tokens}, 0)
190
190
  ELSE 0
@@ -216,11 +216,11 @@ ${e.join(`
216
216
  `,i=sql`
217
217
  COALESCE(${o.input_tokens}, 0)
218
218
  + CASE
219
- WHEN ${o.started_at} >= ${st}
219
+ WHEN ${o.started_at} >= ${it}
220
220
  AND (
221
221
  ${o.crewx_version} IS NULL
222
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}, ${it}) AS INTEGER) < ${at})
223
+ OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${at}) AS INTEGER) < ${dt})
224
224
  )
225
225
  THEN COALESCE(${o.cached_input_tokens}, 0)
226
226
  ELSE 0
@@ -239,7 +239,7 @@ ${e.join(`
239
239
  FROM ${o}
240
240
  ${l}
241
241
  GROUP BY ${o.model}
242
- `),c=new Map;for(let p of u){let h=ke(p.model??""),f=c.get(h);f?(f.totalTasks+=p.total_tasks,f.inputTokens+=p.input_tokens,f.outputTokens+=p.output_tokens,f.cachedInputTokens+=p.cached_input_tokens,f.costUsd+=p.cost_usd,f.totalTokens+=p.input_tokens+p.output_tokens,f.activeDurationMs+=p.active_duration_ms??0,p.last_active_at&&(!f.lastActiveAt||p.last_active_at>f.lastActiveAt)&&(f.lastActiveAt=p.last_active_at)):c.set(h,{model:h,provider:p.provider,totalTasks:p.total_tasks,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null});}return Array.from(c.values()).sort((p,h)=>h.costUsd-p.costUsd)}catch(s){throw new d("DB_ERROR","Failed to get model usage",s)}finally{r.close();}}getTasksForReport(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=e?sql`WHERE ${o.started_at} >= ${t} AND ${o.started_at} < ${n} AND ${o.workspace_id} = ${e}`:sql`WHERE ${o.started_at} >= ${t} AND ${o.started_at} < ${n}`;return r.db.all(sql`
242
+ `),c=new Map;for(let p of u){let h=be(p.model??""),f=c.get(h);f?(f.totalTasks+=p.total_tasks,f.inputTokens+=p.input_tokens,f.outputTokens+=p.output_tokens,f.cachedInputTokens+=p.cached_input_tokens,f.costUsd+=p.cost_usd,f.totalTokens+=p.input_tokens+p.output_tokens,f.activeDurationMs+=p.active_duration_ms??0,p.last_active_at&&(!f.lastActiveAt||p.last_active_at>f.lastActiveAt)&&(f.lastActiveAt=p.last_active_at)):c.set(h,{model:h,provider:p.provider,totalTasks:p.total_tasks,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null});}return Array.from(c.values()).sort((p,h)=>h.costUsd-p.costUsd)}catch(s){throw new d("DB_ERROR","Failed to get model usage",s)}finally{r.close();}}getTasksForReport(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=e?sql`WHERE ${o.started_at} >= ${t} AND ${o.started_at} < ${n} AND ${o.workspace_id} = ${e}`:sql`WHERE ${o.started_at} >= ${t} AND ${o.started_at} < ${n}`;return r.db.all(sql`
243
243
  SELECT
244
244
  ${o.thread_id} AS thread_id,
245
245
  ${o.agent_id} AS agent_id,
@@ -250,7 +250,7 @@ ${e.join(`
250
250
  FROM ${o}
251
251
  ${s}
252
252
  ORDER BY ${o.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(s){throw new d("DB_ERROR","Failed to get tasks for report",s)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=[];t.workspaceId&&e.push(eq(o.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&e.push(inArray(o.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&e.push(inArray(o.status,t.statuses)),t.from&&e.push(gte(o.started_at,t.from)),t.to&&e.push(lt(o.started_at,t.to));let r=e.length>0?and(...e):void 0,s=(t.order??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at),i={id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id};return t.limit?n.db.select(i).from(o).where(r).orderBy(s).limit(t.limit).all():n.db.select(i).from(o).where(r).orderBy(s).all()}catch(e){throw new d("DB_ERROR","Failed to find task evidence",e)}finally{n.close();}}findThreadChains(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=t.maxThreads??8,r=t.maxTurnsPerThread??4,s=[isNotNull(o.thread_id),isNull(o.parent_task_id),isNull(o.caller_agent_id),or(isNull(o.platform),ne$1(o.platform,"workflow")),or(isNull(o.metadata),notLike(o.metadata,'%"kind":"workflow_card"%')),or(isNull(o.metadata),notLike(o.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&s.push(eq(o.workspace_id,t.workspaceId)),t.from&&s.push(gte(o.started_at,t.from)),t.to&&s.push(lt(o.started_at,t.to));let i=n.db.select({id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id}).from(o).where(and(...s)).orderBy(asc(o.started_at),asc(o.id)).all(),l=new Map;for(let c of i){if(!c.thread_id)continue;let p={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},h=l.get(c.thread_id);h?h.push(p):l.set(c.thread_id,[p]);}let u=[];for(let[c,p]of l){let h=p.filter(f=>f.agentId===t.targetAgentId).length;h<2||u.push({threadId:c,targetAgentTurnCount:h,turns:p});}return u.sort((c,p)=>{let h=c.turns[c.turns.length-1].startedAt,f=p.turns[p.turns.length-1].startedAt;return h<f?1:h>f?-1:0}),u.slice(0,e).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-r)}))}catch(e){throw new d("DB_ERROR","Failed to find thread chains",e)}finally{n.close();}}};var Wt=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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}validateWorkspaceId(t,n){return t.db.select({id:m.id}).from(m).where(eq(m.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
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(s){throw new d("DB_ERROR","Failed to get tasks for report",s)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=[];t.workspaceId&&e.push(eq(o.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&e.push(inArray(o.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&e.push(inArray(o.status,t.statuses)),t.from&&e.push(gte(o.started_at,t.from)),t.to&&e.push(lt(o.started_at,t.to));let r=e.length>0?and(...e):void 0,s=(t.order??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at),i={id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id};return t.limit?n.db.select(i).from(o).where(r).orderBy(s).limit(t.limit).all():n.db.select(i).from(o).where(r).orderBy(s).all()}catch(e){throw new d("DB_ERROR","Failed to find task evidence",e)}finally{n.close();}}findThreadChains(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=t.maxThreads??8,r=t.maxTurnsPerThread??4,s=[isNotNull(o.thread_id),isNull(o.parent_task_id),isNull(o.caller_agent_id),or(isNull(o.platform),ne(o.platform,"workflow")),or(isNull(o.metadata),notLike(o.metadata,'%"kind":"workflow_card"%')),or(isNull(o.metadata),notLike(o.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&s.push(eq(o.workspace_id,t.workspaceId)),t.from&&s.push(gte(o.started_at,t.from)),t.to&&s.push(lt(o.started_at,t.to));let i=n.db.select({id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id}).from(o).where(and(...s)).orderBy(asc(o.started_at),asc(o.id)).all(),l=new Map;for(let c of i){if(!c.thread_id)continue;let p={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},h=l.get(c.thread_id);h?h.push(p):l.set(c.thread_id,[p]);}let u=[];for(let[c,p]of l){let h=p.filter(f=>f.agentId===t.targetAgentId).length;h<2||u.push({threadId:c,targetAgentTurnCount:h,turns:p});}return u.sort((c,p)=>{let h=c.turns[c.turns.length-1].startedAt,f=p.turns[p.turns.length-1].startedAt;return h<f?1:h>f?-1:0}),u.slice(0,e).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-r)}))}catch(e){throw new d("DB_ERROR","Failed to find thread chains",e)}finally{n.close();}}};var Kt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}validateWorkspaceId(t,n){return t.db.select({id:m.id}).from(m).where(eq(m.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
254
254
  SELECT 1 FROM tasks parent
255
255
  WHERE parent.id = ${t}.parent_task_id
256
256
  AND parent.thread_id = ${t}.thread_id
@@ -265,13 +265,13 @@ ${e.join(`
265
265
  WHERE child.thread_id = ${t}
266
266
  AND ${this.topLevelTaskPredicateSql()}
267
267
  ${n?sql`AND child.workspace_id = ${n}`:sql``}
268
- `);f&&(r+=f.cnt,s+=f.total_input,i+=f.total_output,l+=f.total_cached,u+=f.total_cost);let S=h.db.all(sql`
268
+ `);f&&(r+=f.cnt,s+=f.total_input,i+=f.total_output,l+=f.total_cached,u+=f.total_cost);let x=h.db.all(sql`
269
269
  SELECT DISTINCT child.agent_id FROM tasks child
270
270
  WHERE child.thread_id = ${t}
271
271
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
272
272
  AND ${this.topLevelTaskPredicateSql()}
273
273
  ${n?sql`AND child.workspace_id = ${n}`:sql``}
274
- `);for(let P of S)c.add(P.agent_id);}catch(f){throw new d("DB_ERROR","Failed to aggregate task stats",f)}finally{h.close();}}return {taskCount:r,inputTokens:s,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,n,e){let r=this.resolveDbPaths(),s=new Set,i=[];for(let l of r){if(!existsSync(l))continue;let u=w(l);try{let c;e!==void 0?c=u.db.all(sql`
274
+ `);for(let L of x)c.add(L.agent_id);}catch(f){throw new d("DB_ERROR","Failed to aggregate task stats",f)}finally{h.close();}}return {taskCount:r,inputTokens:s,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,n,e){let r=this.resolveDbPaths(),s=new Set,i=[];for(let l of r){if(!existsSync(l))continue;let u=w(l);try{let c;e!==void 0?c=u.db.all(sql`
275
275
  SELECT * FROM (
276
276
  SELECT child.*,
277
277
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -306,4 +306,4 @@ ${e.join(`
306
306
  message_count = message_count + 1,
307
307
  updated_at = ${s}
308
308
  WHERE id = ${t}
309
- `),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,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(_).set({last_message:n,updated_at:s}).where(eq(_.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,n){if(!this.dbExists())return;let e=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),e.db.update(_).set(r).where(eq(_.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{e.close();}}togglePin(t,n){let e=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),s=e.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),c=e.db.select({metadata:_.metadata}).from(_).where(u).all(),p=null;for(let h of c){let f=h.metadata?JSON.parse(h.metadata):{};typeof f.pinOrder=="number"&&(p===null||f.pinOrder<p)&&(p=f.pinOrder);}l.pinOrder=p===null?0:p-1;}else delete l.pinOrder;return e.db.update(_).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{e.close();}}reorderPins(t,n){let e=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=n?and(eq(_.id,t[r]),eq(_.workspace_id,n)):eq(_.id,t[r]),i=e.db.select({metadata:_.metadata}).from(_).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,e.db.update(_).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{e.close();}}toggleStar(t,n){let e=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),s=e.db.select({starred:_.starred}).from(_).where(r).get();if(!s)return null;let i=s.starred?0:1;return e.db.update(_).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{e.close();}}resolveOverdriveForRequest(t,n,e,r){let i=this.openHandle(true);try{let l=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t);return i.db.transaction(c=>{let p=c.select({metadata:_.metadata}).from(_).where(l).get();if(!p)return null;let h=p.metadata?JSON.parse(p.metadata):{},f=h.overdrive??{},S=r?.defaultTurns??f.defaultTurns??3,P=r?.updatedBy??"ui",$=new Date().toISOString(),H,N,G,wt;switch(e){case "enable-count":{let kt=r?.turns??S,bt=r?.consumeCurrent?Math.max(kt-1,0):kt;H=bt>0?"count":"off",N=bt,G=!0,wt="count";break}case "enable-latch":{H="latch",N=0,G=!0,wt="latch";break}case "disable":{H="off",N=0,G=!1;break}default:{let kt=f.state??"off",bt=typeof f.remaining=="number"?f.remaining:0;if(kt==="count"&&bt>0){let ee=bt-1;ee<=0?(H="off",N=0):(H="count",N=ee),G=!0,wt="count";}else kt==="latch"?(H="latch",N=0,G=!0,wt="latch"):(H="off",N=0,G=!1);break}}return h.overdrive={state:H,remaining:N,defaultTurns:S,updatedAt:$,updatedBy:P},c.update(_).set({metadata:JSON.stringify(h),updated_at:$}).where(l).run(),{applied:G,appliedMode:wt,state:H,remaining:N}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Kt=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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}insertSpan(t){let n=this.openHandle(true);try{n.db.insert(tt).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert span",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(tt).where(eq(tt.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find spans by task id",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(tt).where(eq(tt.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find span by id",e)}finally{n.close();}}};var Gt=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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}insertToolCall(t){let n=this.openHandle(true);try{n.db.insert(X).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert tool call",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(X).where(eq(X.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find tool calls by task id",e)}finally{n.close();}}aggregateByName(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select({toolName:X.tool_name,count:sql`count(*)`}).from(X).where(eq(X.task_id,t)).groupBy(X.tool_name).all().map(e=>({toolName:e.toolName,count:e.count}))}catch(e){throw new d("DB_ERROR","Failed to aggregate tool calls by name",e)}finally{n.close();}}};var Yt=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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}ensureThreadExists(t,n){if(!t.db.select({id:_.id}).from(_).where(eq(_.id,n)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${n}`)}findByThreadId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return this.ensureThreadExists(n,t),n.db.select().from(j).where(eq(j.thread_id,t)).orderBy(asc(j.seq)).all()}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to find boxes by thread id",e)}finally{n.close();}}findById(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(j).where(and(eq(j.id,n),eq(j.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{e.close();}}insert(t){let n=this.openHandle(true);try{this.ensureThreadExists(n,t.threadId);try{n.db.insert(j).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 e=n.db.select().from(j).where(eq(j.id,t.id)).limit(1).get();if(!e)throw new d("DB_ERROR","Insert did not return a row");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert thread box",e)}finally{n.close();}}};var Xt=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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}bulkInsert(t){if(t.length===0)return;let n=this.openHandle(true);try{let e=new Date().toISOString();n.db.transaction(r=>{for(let s of t)r.insert(ht).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:e,metadata:s.metadata??null}).run();});}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to bulk insert request logs",e)}finally{n.close();}}findRecent(t=100){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(ht).orderBy(desc(ht.timestamp)).limit(t).all()}catch(e){throw new d("DB_ERROR","Failed to find recent request logs",e)}finally{n.close();}}};function ve(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Jt=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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}upsert(t){let n=this.openHandle(true);try{let e=ve(t.bucketStartMs),r=t.accountRef??"default";n.db.insert(I).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:e,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:[I.provider,I.account_ref,I.limit_window,I.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(e){throw e instanceof d?e:new d("DB_ERROR","Failed to upsert usage limit snapshot",e)}finally{n.close();}}getTrends(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=n.db.select({provider:I.provider,bucket_start:I.bucket_start,used_percent:I.used_percent,remaining_percent:I.remaining_percent,resets_at:I.resets_at}).from(I).where(and(eq(I.limit_window,t.window),gte(I.bucket_start,t.fromIso),lte(I.bucket_start,t.toIso))).orderBy(asc(I.bucket_start)).all(),r=new Map;for(let s of e)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(e){throw new d("DB_ERROR","Failed to get usage limit trends",e)}finally{n.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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}publish(t){let n=this.openHandle(true);try{n.db.insert(M).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:[M.workspace_id,M.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 e=n.db.select().from(M).where(and(eq(M.workspace_id,t.workspaceId),eq(M.month,t.month))).limit(1).get();if(!e)throw new d("DB_ERROR","Failed to read back published usage report");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to publish usage report",e)}finally{n.close();}}findByMonth(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(M).where(and(eq(M.workspace_id,t),eq(M.month,n))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{e.close();}}listByWorkspace(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(M).where(eq(M.workspace_id,t)).orderBy(desc(M.month)).all()}catch(e){throw new d("DB_ERROR","Failed to list usage reports",e)}finally{n.close();}}};var $e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Nr(a){let t=randomBytes(a*2),n="";for(let e=0;e<t.length&&n.length<a;e++){let r=t[e];r<248&&(n+=$e[r%62]);}for(;n.length<a;)n+=$e[randomBytes(1)[0]%62];return n}function Lt(a){return `${a}_${Nr(8)}`}var ze=500,Fe=50,Qt=class extends x{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??ze;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=Lt("ntf"),r=new Date().toISOString();return n.db.insert(k).values({id:e,workspace_id:t.workspaceId,agent_id:t.agentId??null,task_id:t.taskId??null,thread_id:t.threadId??null,source:t.source??"agent",level:t.level??"info",title:t.title,body:t.body??null,target_user_id:t.targetUserId??null,created_at:r,metadata:t.metadata??null}).run(),this.enforceCap(n,t.workspaceId),{id:e}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create notification",e)}finally{n.close();}}enforceCap(t,n){let s=(t.db.select({count:sql`count(*)`}).from(k).where(eq(k.workspace_id,n)).get()?.count??0)-this.cap;if(s<=0)return;let l=t.db.select({id:k.id}).from(k).innerJoin(C,eq(C.notification_id,k.id)).where(eq(k.workspace_id,n)).groupBy(k.id).orderBy(asc(k.created_at)).limit(s).all().map(u=>u.id);l.length!==0&&(t.db.delete(C).where(inArray(C.notification_id,l)).run(),t.db.delete(k).where(inArray(k.id,l)).run());}list(t){if(!this.dbExists())return [];let n=t.limit??Fe,e=this.openHandle(false);try{return e.db.select({id:k.id,workspace_id:k.workspace_id,agent_id:k.agent_id,task_id:k.task_id,thread_id:k.thread_id,source:k.source,level:k.level,title:k.title,body:k.body,target_user_id:k.target_user_id,created_at:k.created_at,metadata:k.metadata,read_at:C.read_at}).from(k).leftJoin(C,and(eq(C.notification_id,k.id),eq(C.user_id,t.userId))).where(eq(k.workspace_id,t.workspaceId)).orderBy(desc(k.created_at)).limit(n).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(r){throw new d("DB_ERROR","Failed to list notifications",r)}finally{e.close();}}unreadCount(t){if(!this.dbExists())return 0;let n=this.openHandle(false);try{return n.db.select({count:sql`count(*)`}).from(k).leftJoin(C,and(eq(C.notification_id,k.id),eq(C.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(C.notification_id))).get()?.count??0}catch(e){throw new d("DB_ERROR","Failed to count unread notifications",e)}finally{n.close();}}markRead(t){let n=this.openHandle(true);try{if(!n.db.select({id:k.id}).from(k).where(and(eq(k.id,t.notificationId),eq(k.workspace_id,t.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return n.db.insert(C).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark notification read",e)}finally{n.close();}}markAllRead(t){let n=this.openHandle(true);try{let e=n.db.select({id:k.id}).from(k).leftJoin(C,and(eq(C.notification_id,k.id),eq(C.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(C.notification_id))).all();if(e.length===0)return 0;let r=new Date().toISOString();return n.db.transaction(s=>{for(let i of e)s.insert(C).values({notification_id:i.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),e.length}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark all notifications read",e)}finally{n.close();}}};var We=50,te=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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{A(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=new Date().toISOString(),r=[],s=t.map(i=>{let l=Lt("sug");return r.push(l),{id:l,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:e,updated_at:e}});return s.length>0&&n.db.insert(v).values(s).run(),{ids:r}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create agent suggestions",e)}finally{n.close();}}findLatestSet(t,n){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=e.db.select({task_id:v.task_id}).from(v).where(and(eq(v.workspace_id,t),eq(v.agent_id,n))).orderBy(desc(v.created_at)).limit(1).get();if(!r)return [];let s=r.task_id===null?isNull(v.task_id):eq(v.task_id,r.task_id);return e.db.select().from(v).where(and(eq(v.workspace_id,t),eq(v.agent_id,n),s)).orderBy(asc(v.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{e.close();}}updateStatus(t,n,e){let r=this.openHandle(true);try{let s={status:n,updated_at:new Date().toISOString()};return e!==void 0&&(s.applied_commit_sha=e),r.db.update(v).set(s).where(eq(v.id,t)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{r.close();}}listByAgent(t,n,e=We){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(v).where(and(eq(v.workspace_id,t),eq(v.agent_id,n))).orderBy(desc(v.created_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{r.close();}}};export{te as AgentSuggestionRepository,x as BaseSqliteRepository,We as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,ze as DEFAULT_NOTIFICATION_CAP,Fe as DEFAULT_NOTIFICATION_LIST_LIMIT,Qt as NotificationRepository,d as RepositoryError,Xt as RequestLogRepository,Kt as SpanRepository,jt as TaskRepository,Yt as ThreadBoxRepository,Wt as ThreadRepository,Gt as ToolCallRepository,Jt as UsageLimitSnapshotRepository,Vt as UsageReportRepository,Ft as WorkspaceRepository,ve as calcBucketStart,w as openDrizzleDb,Mn as pushSchema,_t as runMigrations,A as runMigrationsOnce,o as tasks};
309
+ `),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,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(_).set({last_message:n,updated_at:s}).where(eq(_.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,n){if(!this.dbExists())return;let e=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),e.db.update(_).set(r).where(eq(_.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{e.close();}}togglePin(t,n){let e=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),s=e.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!s)return null;let i=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(i){let u=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),c=e.db.select({metadata:_.metadata}).from(_).where(u).all(),p=null;for(let h of c){let f=h.metadata?JSON.parse(h.metadata):{};typeof f.pinOrder=="number"&&(p===null||f.pinOrder<p)&&(p=f.pinOrder);}l.pinOrder=p===null?0:p-1;}else delete l.pinOrder;return e.db.update(_).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{e.close();}}reorderPins(t,n){let e=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=n?and(eq(_.id,t[r]),eq(_.workspace_id,n)):eq(_.id,t[r]),i=e.db.select({metadata:_.metadata}).from(_).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,e.db.update(_).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{e.close();}}toggleStar(t,n){let e=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),s=e.db.select({starred:_.starred}).from(_).where(r).get();if(!s)return null;let i=s.starred?0:1;return e.db.update(_).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{e.close();}}resolveOverdriveForRequest(t,n,e,r){let i=this.openHandle(true);try{let l=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t);return i.db.transaction(c=>{let p=c.select({metadata:_.metadata}).from(_).where(l).get();if(!p)return null;let h=p.metadata?JSON.parse(p.metadata):{},f=h.overdrive??{},x=r?.defaultTurns??f.defaultTurns??3,L=r?.updatedBy??"ui",B=new Date().toISOString(),M,A,Y,kt;switch(e){case "enable-count":{let bt=r?.turns??x,Rt=r?.consumeCurrent?Math.max(bt-1,0):bt;M=Rt>0?"count":"off",A=Rt,Y=!0,kt="count";break}case "enable-latch":{M="latch",A=0,Y=!0,kt="latch";break}case "disable":{M="off",A=0,Y=!1;break}default:{let bt=f.state??"off",Rt=typeof f.remaining=="number"?f.remaining:0;if(bt==="count"&&Rt>0){let ne=Rt-1;ne<=0?(M="off",A=0):(M="count",A=ne),Y=!0,kt="count";}else bt==="latch"?(M="latch",A=0,Y=!0,kt="latch"):(M="off",A=0,Y=!1);break}}return h.overdrive={state:M,remaining:A,defaultTurns:x,updatedAt:B,updatedBy:L},c.update(_).set({metadata:JSON.stringify(h),updated_at:B}).where(l).run(),{applied:Y,appliedMode:kt,state:M,remaining:A}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Gt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}insertSpan(t){let n=this.openHandle(true);try{n.db.insert(et).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert span",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(et).where(eq(et.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find spans by task id",e)}finally{n.close();}}findById(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(et).where(eq(et.id,t)).limit(1).get()??void 0}catch(e){throw new d("DB_ERROR","Failed to find span by id",e)}finally{n.close();}}};var Yt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}insertToolCall(t){let n=this.openHandle(true);try{n.db.insert(J).values(t).run();}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert tool call",e)}finally{n.close();}}findByTaskId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(J).where(eq(J.task_id,t)).all()}catch(e){throw new d("DB_ERROR","Failed to find tool calls by task id",e)}finally{n.close();}}aggregateByName(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select({toolName:J.tool_name,count:sql`count(*)`}).from(J).where(eq(J.task_id,t)).groupBy(J.tool_name).all().map(e=>({toolName:e.toolName,count:e.count}))}catch(e){throw new d("DB_ERROR","Failed to aggregate tool calls by name",e)}finally{n.close();}}};var Xt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}ensureThreadExists(t,n){if(!t.db.select({id:_.id}).from(_).where(eq(_.id,n)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${n}`)}findByThreadId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return this.ensureThreadExists(n,t),n.db.select().from(W).where(eq(W.thread_id,t)).orderBy(asc(W.seq)).all()}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to find boxes by thread id",e)}finally{n.close();}}findById(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(W).where(and(eq(W.id,n),eq(W.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{e.close();}}insert(t){let n=this.openHandle(true);try{this.ensureThreadExists(n,t.threadId);try{n.db.insert(W).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 e=n.db.select().from(W).where(eq(W.id,t.id)).limit(1).get();if(!e)throw new d("DB_ERROR","Insert did not return a row");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to insert thread box",e)}finally{n.close();}}};var Jt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}bulkInsert(t){if(t.length===0)return;let n=this.openHandle(true);try{let e=new Date().toISOString();n.db.transaction(r=>{for(let s of t)r.insert(ht).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:e,metadata:s.metadata??null}).run();});}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to bulk insert request logs",e)}finally{n.close();}}findRecent(t=100){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(ht).orderBy(desc(ht.timestamp)).limit(t).all()}catch(e){throw new d("DB_ERROR","Failed to find recent request logs",e)}finally{n.close();}}};function ve(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Vt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}upsert(t){let n=this.openHandle(true);try{let e=ve(t.bucketStartMs),r=t.accountRef??"default";n.db.insert(P).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:e,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:[P.provider,P.account_ref,P.limit_window,P.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(e){throw e instanceof d?e:new d("DB_ERROR","Failed to upsert usage limit snapshot",e)}finally{n.close();}}getTrends(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let e=n.db.select({provider:P.provider,bucket_start:P.bucket_start,used_percent:P.used_percent,remaining_percent:P.remaining_percent,resets_at:P.resets_at}).from(P).where(and(eq(P.limit_window,t.window),gte(P.bucket_start,t.fromIso),lte(P.bucket_start,t.toIso))).orderBy(asc(P.bucket_start)).all(),r=new Map;for(let s of e)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(e){throw new d("DB_ERROR","Failed to get usage limit trends",e)}finally{n.close();}}};var Qt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}publish(t){let n=this.openHandle(true);try{n.db.insert(F).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:[F.workspace_id,F.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 e=n.db.select().from(F).where(and(eq(F.workspace_id,t.workspaceId),eq(F.month,t.month))).limit(1).get();if(!e)throw new d("DB_ERROR","Failed to read back published usage report");return e}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to publish usage report",e)}finally{n.close();}}findByMonth(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(F).where(and(eq(F.workspace_id,t),eq(F.month,n))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{e.close();}}listByWorkspace(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(F).where(eq(F.workspace_id,t)).orderBy(desc(F.month)).all()}catch(e){throw new d("DB_ERROR","Failed to list usage reports",e)}finally{n.close();}}};var Be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Ar(a){let t=randomBytes(a*2),n="";for(let e=0;e<t.length&&n.length<a;e++){let r=t[e];r<248&&(n+=Be[r%62]);}for(;n.length<a;)n+=Be[randomBytes(1)[0]%62];return n}function $t(a){return `${a}_${Ar(8)}`}var ze=500,qe=50,Zt=class extends T{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??ze;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=$t("ntf"),r=new Date().toISOString();return n.db.insert(k).values({id:e,workspace_id:t.workspaceId,agent_id:t.agentId??null,task_id:t.taskId??null,thread_id:t.threadId??null,source:t.source??"agent",level:t.level??"info",title:t.title,body:t.body??null,target_user_id:t.targetUserId??null,created_at:r,metadata:t.metadata??null}).run(),this.enforceCap(n,t.workspaceId),{id:e}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create notification",e)}finally{n.close();}}enforceCap(t,n){let s=(t.db.select({count:sql`count(*)`}).from(k).where(eq(k.workspace_id,n)).get()?.count??0)-this.cap;if(s<=0)return;let l=t.db.select({id:k.id}).from(k).innerJoin(I,eq(I.notification_id,k.id)).where(eq(k.workspace_id,n)).groupBy(k.id).orderBy(asc(k.created_at)).limit(s).all().map(u=>u.id);l.length!==0&&(t.db.delete(I).where(inArray(I.notification_id,l)).run(),t.db.delete(k).where(inArray(k.id,l)).run());}list(t){if(!this.dbExists())return [];let n=t.limit??qe,e=this.openHandle(false);try{return e.db.select({id:k.id,workspace_id:k.workspace_id,agent_id:k.agent_id,task_id:k.task_id,thread_id:k.thread_id,source:k.source,level:k.level,title:k.title,body:k.body,target_user_id:k.target_user_id,created_at:k.created_at,metadata:k.metadata,read_at:I.read_at}).from(k).leftJoin(I,and(eq(I.notification_id,k.id),eq(I.user_id,t.userId))).where(eq(k.workspace_id,t.workspaceId)).orderBy(desc(k.created_at)).limit(n).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(r){throw new d("DB_ERROR","Failed to list notifications",r)}finally{e.close();}}unreadCount(t){if(!this.dbExists())return 0;let n=this.openHandle(false);try{return n.db.select({count:sql`count(*)`}).from(k).leftJoin(I,and(eq(I.notification_id,k.id),eq(I.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(I.notification_id))).get()?.count??0}catch(e){throw new d("DB_ERROR","Failed to count unread notifications",e)}finally{n.close();}}markRead(t){let n=this.openHandle(true);try{if(!n.db.select({id:k.id}).from(k).where(and(eq(k.id,t.notificationId),eq(k.workspace_id,t.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return n.db.insert(I).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark notification read",e)}finally{n.close();}}markAllRead(t){let n=this.openHandle(true);try{let e=n.db.select({id:k.id}).from(k).leftJoin(I,and(eq(I.notification_id,k.id),eq(I.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(I.notification_id))).all();if(e.length===0)return 0;let r=new Date().toISOString();return n.db.transaction(s=>{for(let i of e)s.insert(I).values({notification_id:i.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),e.length}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to mark all notifications read",e)}finally{n.close();}}};var Ke=50,ee=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new d("NOT_FOUND","Database not found");let e=w(n);if(t)try{O(e.db,n);}catch(r){throw e.close(),r}return e}create(t){let n=this.openHandle(true);try{let e=new Date().toISOString(),r=[],s=t.map(i=>{let l=$t("sug");return r.push(l),{id:l,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:e,updated_at:e}});return s.length>0&&n.db.insert(E).values(s).run(),{ids:r}}catch(e){throw e instanceof d?e:new d("DB_ERROR","Failed to create agent suggestions",e)}finally{n.close();}}findLatestSet(t,n){if(!this.dbExists())return [];let e=this.openHandle(false);try{let r=e.db.select({task_id:E.task_id}).from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n))).orderBy(desc(E.created_at)).limit(1).get();if(!r)return [];let s=r.task_id===null?isNull(E.task_id):eq(E.task_id,r.task_id);return e.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),s)).orderBy(asc(E.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{e.close();}}findSetByTaskId(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),eq(E.task_id,e))).orderBy(asc(E.created_at)).all()}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{r.close();}}findById(t,n,e){if(!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),eq(E.id,e))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{r.close();}}updateStatus(t,n,e){let r=this.openHandle(true);try{let s={status:n,updated_at:new Date().toISOString()};return e!==void 0&&(s.applied_commit_sha=e),r.db.update(E).set(s).where(eq(E.id,t)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{r.close();}}listByAgent(t,n,e=Ke){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n))).orderBy(desc(E.created_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{r.close();}}findDismissed(t,n,e=20){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(E).where(and(eq(E.workspace_id,t),eq(E.agent_id,n),eq(E.status,"dismissed"))).orderBy(desc(E.updated_at)).limit(e).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{r.close();}}};export{ee as AgentSuggestionRepository,T as BaseSqliteRepository,Ke as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,ze as DEFAULT_NOTIFICATION_CAP,qe as DEFAULT_NOTIFICATION_LIST_LIMIT,Zt as NotificationRepository,d as RepositoryError,Jt as RequestLogRepository,Gt as SpanRepository,Wt as TaskRepository,Xt as ThreadBoxRepository,Kt as ThreadRepository,Yt as ToolCallRepository,Vt as UsageLimitSnapshotRepository,Qt as UsageReportRepository,qt as WorkspaceRepository,ve as calcBucketStart,w as openDrizzleDb,Fn as pushSchema,_t as runMigrations,O as runMigrationsOnce,o as tasks};
@@ -1 +1 @@
1
- function f(){let e=[];return {events:e,async log(t,r){e.push({event:t,payload:r});}}}function h(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,r){e.debug.push({msg:t,meta:r});},info(t,r){e.info.push({msg:t,meta:r});},warn(t,r){e.warn.push({msg:t,meta:r});},error(t,r){e.error.push({msg:t,meta:r});}}}function A(){let e=200,t,r,n={},o={status(i){return e=i,o},set(i,s){return n[i]=s,o},send(i){return r=i,o},json(i){return t=i,o},end(){return o},getStatusCode:()=>e,getJsonBody:()=>t,getSentBody:()=>r,getHeaders:()=>({...n})};return o}function y(){let e=[];return {routes:e,registerRoute(r,n,o){e.push({path:r,handler:n,opts:o});},async simulate(r,n,o=Buffer.alloc(0),i={},s={},p={}){let g=e.find(m=>m.path===n);if(!g)return {status:404,body:{error:"Not found"},headers:{}};let l={method:r,url:n,headers:i,body:o,params:s,query:p},c=A();return await g.handler(l,c),{status:c.getStatusCode(),body:c.getJsonBody()??c.getSentBody(),headers:c.getHeaders()}}}}function R(e){let t=new Map,r=n=>n.startsWith(`${e}::`)?n:`${e}::${n}`;return {async get(n){let o=t.get(r(n));return o?o.value:void 0},async set(n,o){t.set(r(n),{value:o});},async delete(n){return t.delete(r(n))},async list(n){let o=n?r(n):`${e}::`,i=[];for(let s of t.keys())s.startsWith(o)&&i.push(s.slice(e.length+2));return i}}}function x(e){return R(e)}function M(){let e=new Map;return {blobs:e,async put(t,r,n){return e.set(t,{data:r,contentType:n}),t},async get(t){let r=e.get(t);return r?r.data:void 0},async delete(t){return e.delete(t)}}}function S(e){let t=e.instanceId??"mock-instance",r=f(),n=h(),o=y(),i=x(t),s=M(),p=[],g=[],l=[],c={run:async()=>({output:""}),...e.agentRunner},m=new AbortController,v=async u=>(p.push(u),{accepted:true}),C=async u=>(g.push(u),{accepted:true}),k=async(u,w)=>{l.push({messageId:u,patch:w});},E=async u=>({userId:u,displayName:u}),b=async()=>{},O=async()=>({messageId:"mock-proactive",sentAt:Date.now()});return {instanceId:t,installationId:e.installationId,config:e.config,capabilities:new Set(e.capabilities??[]),log:n,agentRunner:c,db:i,storage:s,audit:r,abortSignal:e.abortSignal??m.signal,httpRouter:o,router:o,inbound:v,emitEvent:C,updateMessage:k,resolveUser:E,respondSync:b,proactive:O,inboundCalls:p,emittedEvents:g,sentMessages:l}}function T(){}var P={claude:{models:[{id:"claude-fable-5",name:"Claude Fable 5"},{id:"claude-sonnet-5",name:"Claude Sonnet 5"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8 (Extended)"},{id:"claude-opus-4-8",name:"Claude Opus 4.8"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7 (Extended)"},{id:"claude-opus-4-7",name:"Claude Opus 4.7"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6 (Extended)"},{id:"claude-opus-4-6",name:"Claude Opus 4.6"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6 (Extended)"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5"}],modes:[{id:"default",name:"Default"},{id:"acceptEdits",name:"Accept Edits"},{id:"plan",name:"Plan"},{id:"auto",name:"Auto"},{id:"dontAsk",name:"Don't Ask"},{id:"bypassPermissions",name:"Bypass Permissions"}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-opus-4-6":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}}},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna"},{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark"}],modes:[{id:"agent",name:"Agent"},{id:"read-only",name:"Read Only"},{id:"plan",name:"Plan"},{id:"agent-full-access",name:"Agent Full Access"},{id:"yolo",name:"YOLO"}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","low","medium","high","xhigh"],defaultEffort:"high"}}},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro"}],modes:[{id:"interactive",name:"Interactive"},{id:"plan",name:"Plan"},{id:"autopilot",name:"Autopilot"}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{}},antigravity:{models:[{id:"Gemini 3.5 Flash (Medium)",name:"Gemini 3.5 Flash (Medium)"},{id:"Gemini 3.5 Flash (High)",name:"Gemini 3.5 Flash (High)"},{id:"Gemini 3.5 Flash (Low)",name:"Gemini 3.5 Flash (Low)"},{id:"Gemini 3.1 Pro (Low)",name:"Gemini 3.1 Pro (Low)"},{id:"Gemini 3.1 Pro (High)",name:"Gemini 3.1 Pro (High)"},{id:"Claude Sonnet 4.6 (Thinking)",name:"Claude Sonnet 4.6 (Thinking)"},{id:"Claude Opus 4.6 (Thinking)",name:"Claude Opus 4.6 (Thinking)"},{id:"GPT-OSS 120B (Medium)",name:"GPT-OSS 120B (Medium)"}],modes:[],effort:[],modelOverrides:{}}};Object.fromEntries(Object.entries(P).map(([e,t])=>[e,t.models]));function B(){}export{f as createMockAudit,S as createMockContext,h as createMockLogger,y as createMockRouter,M as createMockStorage,x as createMockStore,B as resetModelsOverride,T as resetPricingOverride};
1
+ function f(){let e=[];return {events:e,async log(t,r){e.push({event:t,payload:r});}}}function h(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,r){e.debug.push({msg:t,meta:r});},info(t,r){e.info.push({msg:t,meta:r});},warn(t,r){e.warn.push({msg:t,meta:r});},error(t,r){e.error.push({msg:t,meta:r});}}}function A(){let e=200,t,r,n={},o={status(i){return e=i,o},set(i,s){return n[i]=s,o},send(i){return r=i,o},json(i){return t=i,o},end(){return o},getStatusCode:()=>e,getJsonBody:()=>t,getSentBody:()=>r,getHeaders:()=>({...n})};return o}function y(){let e=[];return {routes:e,registerRoute(r,n,o){e.push({path:r,handler:n,opts:o});},async simulate(r,n,o=Buffer.alloc(0),i={},s={},p={}){let g=e.find(m=>m.path===n);if(!g)return {status:404,body:{error:"Not found"},headers:{}};let l={method:r,url:n,headers:i,body:o,params:s,query:p},c=A();return await g.handler(l,c),{status:c.getStatusCode(),body:c.getJsonBody()??c.getSentBody(),headers:c.getHeaders()}}}}function R(e){let t=new Map,r=n=>n.startsWith(`${e}::`)?n:`${e}::${n}`;return {async get(n){let o=t.get(r(n));return o?o.value:void 0},async set(n,o){t.set(r(n),{value:o});},async delete(n){return t.delete(r(n))},async list(n){let o=n?r(n):`${e}::`,i=[];for(let s of t.keys())s.startsWith(o)&&i.push(s.slice(e.length+2));return i}}}function x(e){return R(e)}function M(){let e=new Map;return {blobs:e,async put(t,r,n){return e.set(t,{data:r,contentType:n}),t},async get(t){let r=e.get(t);return r?r.data:void 0},async delete(t){return e.delete(t)}}}function S(e){let t=e.instanceId??"mock-instance",r=f(),n=h(),o=y(),i=x(t),s=M(),p=[],g=[],l=[],c={run:async()=>({output:""}),...e.agentRunner},m=new AbortController,C=async u=>(p.push(u),{accepted:true}),v=async u=>(g.push(u),{accepted:true}),E=async(u,w)=>{l.push({messageId:u,patch:w});},k=async u=>({userId:u,displayName:u}),b=async()=>{},O=async()=>({messageId:"mock-proactive",sentAt:Date.now()});return {instanceId:t,installationId:e.installationId,config:e.config,capabilities:new Set(e.capabilities??[]),log:n,agentRunner:c,db:i,storage:s,audit:r,abortSignal:e.abortSignal??m.signal,httpRouter:o,router:o,inbound:C,emitEvent:v,updateMessage:E,resolveUser:k,respondSync:b,proactive:O,inboundCalls:p,emittedEvents:g,sentMessages:l}}function T(){}var P={claude:{models:[{id:"claude-fable-5",name:"Claude Fable 5"},{id:"claude-opus-5",name:"Claude Opus 5"},{id:"claude-sonnet-5",name:"Claude Sonnet 5"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8 (Extended)"},{id:"claude-opus-4-8",name:"Claude Opus 4.8"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7 (Extended)"},{id:"claude-opus-4-7",name:"Claude Opus 4.7"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6 (Extended)"},{id:"claude-opus-4-6",name:"Claude Opus 4.6"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6 (Extended)"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5"}],modes:[{id:"default",name:"Default"},{id:"acceptEdits",name:"Accept Edits"},{id:"plan",name:"Plan"},{id:"auto",name:"Auto"},{id:"dontAsk",name:"Don't Ask"},{id:"bypassPermissions",name:"Bypass Permissions"}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-opus-4-6":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}}},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna"},{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark"}],modes:[{id:"agent",name:"Agent"},{id:"read-only",name:"Read Only"},{id:"plan",name:"Plan"},{id:"agent-full-access",name:"Agent Full Access"},{id:"yolo",name:"YOLO"}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","low","medium","high","xhigh"],defaultEffort:"high"}}},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro"}],modes:[{id:"interactive",name:"Interactive"},{id:"plan",name:"Plan"},{id:"autopilot",name:"Autopilot"}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{}},antigravity:{models:[{id:"Gemini 3.5 Flash (Medium)",name:"Gemini 3.5 Flash (Medium)"},{id:"Gemini 3.5 Flash (High)",name:"Gemini 3.5 Flash (High)"},{id:"Gemini 3.5 Flash (Low)",name:"Gemini 3.5 Flash (Low)"},{id:"Gemini 3.1 Pro (Low)",name:"Gemini 3.1 Pro (Low)"},{id:"Gemini 3.1 Pro (High)",name:"Gemini 3.1 Pro (High)"},{id:"Claude Sonnet 4.6 (Thinking)",name:"Claude Sonnet 4.6 (Thinking)"},{id:"Claude Opus 4.6 (Thinking)",name:"Claude Opus 4.6 (Thinking)"},{id:"GPT-OSS 120B (Medium)",name:"GPT-OSS 120B (Medium)"}],modes:[],effort:[],modelOverrides:{}}};Object.fromEntries(Object.entries(P).map(([e,t])=>[e,t.models]));function B(){}export{f as createMockAudit,S as createMockContext,h as createMockLogger,y as createMockRouter,M as createMockStorage,x as createMockStore,B as resetModelsOverride,T as resetPricingOverride};