@crewx/sdk 0.9.0-rc.57 → 0.9.0-rc.59

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.
Files changed (40) hide show
  1. package/dist/config/migrate-grok-mode.d.ts +6 -0
  2. package/dist/config/models.generated.d.ts +12 -2
  3. package/dist/config/overdrive.d.ts +2 -0
  4. package/dist/config/pricing.generated.d.ts +2 -2
  5. package/dist/conversation/index.d.ts +1 -1
  6. package/dist/conversation/to-template-messages.d.ts +7 -0
  7. package/dist/conversation/types.d.ts +1 -0
  8. package/dist/esm/index.js +221 -147
  9. package/dist/esm/plugins/index.js +85 -72
  10. package/dist/esm/repository/index.js +92 -79
  11. package/dist/esm/testing/index.js +1 -1
  12. package/dist/facade/Crewx.d.ts +2 -0
  13. package/dist/index.browser.js +4 -4
  14. package/dist/index.d.ts +8 -1
  15. package/dist/index.js +221 -147
  16. package/dist/migrations/0014_organic_mongu.sql +73 -0
  17. package/dist/migrations/meta/0014_snapshot.json +1975 -0
  18. package/dist/migrations/meta/_journal.json +7 -0
  19. package/dist/plugins/index.js +85 -72
  20. package/dist/provider/acp/meta.d.ts +2 -0
  21. package/dist/provider/bridge.d.ts +1 -0
  22. package/dist/provider/cli/adapters/cli-knob.util.d.ts +2 -0
  23. package/dist/provider/models.d.ts +1 -1
  24. package/dist/repository/index.js +92 -79
  25. package/dist/repository/task.repository.d.ts +1 -0
  26. package/dist/schema/index.d.ts +2 -0
  27. package/dist/schema/ui-action-receipts.d.ts +303 -0
  28. package/dist/schema/ui-instances.d.ts +267 -0
  29. package/dist/testing/index.js +1 -1
  30. package/dist/types/index.d.ts +2 -0
  31. package/dist/ui-card/index.d.ts +2 -0
  32. package/dist/ui-card/legacy-card-parser.d.ts +11 -0
  33. package/dist/ui-instance/definition.d.ts +6 -0
  34. package/dist/ui-instance/errors.d.ts +17 -0
  35. package/dist/ui-instance/index.d.ts +6 -0
  36. package/dist/ui-instance/json.d.ts +5 -0
  37. package/dist/ui-instance/runtime.d.ts +13 -0
  38. package/dist/ui-instance/store.d.ts +65 -0
  39. package/dist/ui-instance/types.d.ts +200 -0
  40. package/package.json +1 -1
@@ -1,14 +1,47 @@
1
- import*as Z from'path';import Z__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import ge,{existsSync,mkdirSync,readFileSync}from'fs';import Ze from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,lt,or,notLike,like,asc,inArray,gte,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 oe=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 f=a.all("PRAGMA table_info(tasks)"),h=new Set(f.map(x=>x.name));for(let[x,L]of Object.entries(l))h.has(x)||(a.run(`ALTER TABLE tasks ADD COLUMN ${x} ${L}`),h.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,f=[],h;for(;(h=p.exec(u))!==null;)f.push({table:h[1],column:h[2]});if(f.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;f.every(({table:B,column:H})=>a.all(`PRAGMA table_info("${B}")`).some(Y=>Y.name===H))&&a.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function ht(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
- ${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),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){oe.has(t)||(ht(a),oe.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 V=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},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 mt=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 v=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`)})),P=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 Ht(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 fe(a){let t=Ht(a);return createHash("sha256").update(t).digest("hex")}function Pt(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{ht(e.db);}catch(r){throw e.close(),r}return e}resolveSlug(t,n,e){let r=Pt(basename(e)),i=`${Pt(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=Pt(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=fe(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.*,
1
+ import*as at from'path';import at__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Te,{existsSync,mkdirSync,readFileSync}from'fs';import ln from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,lt,or,notLike,like,asc,inArray,gte,lte}from'drizzle-orm';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey,check,getTableConfig}from'drizzle-orm/sqlite-core';var Pt=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var sn=()=>fileURLToPath(import.meta.url),an=()=>at__default.dirname(sn()),b=an();var D=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(ln.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function w(i){let t=Pt("better-sqlite3"),{drizzle:e}=Pt("drizzle-orm/better-sqlite3"),n=new t(i);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:e(n),runRaw:(r,s=[])=>n.prepare(r).run(...s),close:()=>n.close()}}var _e=new Set,un={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function Kt(i,t){return (i.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function _n(i,t){if(t>0||!Kt(i,"tasks"))return;let e=i.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,s]of Object.entries(un))n.has(r)||i.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var pn={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function fn(i,t,e){if(!Kt(i,"__drizzle_migrations")||!Kt(i,"tasks"))return;let n=i.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(a=>a.hash)),s=JSON.parse(readFileSync(at__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=pn[a.tag];if(!c)continue;let u=at__default.join(t,`${a.tag}.sql`);if(!existsSync(u))continue;let l=readFileSync(u,"utf-8"),_=createHash("sha256").update(l).digest("hex");if(r.has(_))continue;let f=i.all("PRAGMA table_info(tasks)"),m=new Set(f.map(E=>E.name));for(let[E,B]of Object.entries(c))m.has(E)||(i.run(`ALTER TABLE tasks ADD COLUMN ${E} ${B}`),m.add(E));}}function hn(i,t,e){let n=i.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(a=>a.hash)),s=JSON.parse(readFileSync(at__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=at__default.join(t,`${a.tag}.sql`);if(!existsSync(c))continue;let u=readFileSync(c,"utf-8"),l=createHash("sha256").update(u).digest("hex");if(r.has(l))continue;let _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],m;for(;(m=_.exec(u))!==null;)f.push({table:m[1],column:m[2]});if(f.length===0||!u.split(/-->\s*statement-breakpoint/).map(M=>M.trim()).filter(Boolean).every(M=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(M)))continue;f.every(({table:M,column:z})=>i.all(`PRAGMA table_info("${M}")`).some(Z=>Z.name===z))&&i.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${a.when})`);}}function Rt(i){let{migrate:t}=Pt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Pt("drizzle-orm"),n=[at__default.join(b,"../migrations"),at__default.join(b,"migrations"),at__default.join(b,"../../../../drizzle/migrations"),at__default.join(process.cwd(),"drizzle/migrations")],r=n.find(l=>existsSync(at__default.join(l,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
2
+ ${n.join(`
3
+ `)}`);let s=i.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;s?.cnt&&(a=i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),_n(i,a),s?.cnt&&(hn(i,r,e),fn(i,r,e)),t(i,{migrationsFolder:r});let u=(i.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(u>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${u} migration${u>1?"s":""} applied).`);}}function O(i,t){_e.has(t)||(Rt(i),_e.add(t));}var h=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},i=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(i.agent_id),idx_tasks_status:index("idx_tasks_status").on(i.status),idx_tasks_started_at:index("idx_tasks_started_at").on(i.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(i.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(i.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(i.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(i.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(i.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(i.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(i.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(i.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(i.workspace_id,i.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>h.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},i=>({idx_threads_updated_at:index("idx_threads_updated_at").on(i.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(i.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(i.workspace_id,i.updated_at),idx_threads_title:index("idx_threads_title").on(i.title)}));var ct=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(()=>ct.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")},i=>({idx_spans_task_id:index("idx_spans_task_id").on(i.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(i.parent_span_id)}));var rt=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()},i=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(i.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(i.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(i.timestamp)}));var J=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},i=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(i.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(i.thread_id,i.seq),uniq_thread_boxes_thread_seq:unique().on(i.thread_id,i.seq)}));var Et=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")},i=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(i.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(i.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(i.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(i.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")},i=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(i.provider,i.account_ref,i.limit_window,i.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(i.limit_window,i.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(i.provider,i.limit_window,i.bucket_start)}));var q=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")},i=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(i.workspace_id,i.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")},i=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(i.workspace_id,sql`${i.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()},i=>({pk:primaryKey({columns:[i.notification_id,i.user_id]})}));var S=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()},i=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(i.workspace_id,i.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(i.workspace_id,i.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},i=>({idCheck:check("ui_instances_id_ck",sql`length(${i.id}) BETWEEN 5 AND 128 AND ${i.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${i.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${i.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${i.definition_hash}) = 64 AND ${i.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${i.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${i.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${i.domain_ref_json}) AND json_type(${i.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${i.state_json}) AND json_type(${i.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${i.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${i.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${i.granted_capabilities_json}) AND json_type(${i.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${i.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${i.updated_at} >= ${i.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(i.workspace_id,i.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},i=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${i.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${i.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${i.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${i.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${i.actor_json}) AND json_type(${i.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${i.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${i.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${i.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${i.after_revision} IS NULL OR ${i.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${i.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${i.outcome} IS NULL OR ${i.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${i.input_json}) AND json_type(${i.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${i.result_json} IS NULL OR (json_valid(${i.result_json}) AND json_type(${i.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${i.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${i.settled_at} IS NULL OR ${i.settled_at} >= ${i.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
4
+ (${i.status} = 'requested' AND ${i.after_revision} IS NULL AND ${i.outcome} IS NULL AND ${i.settled_at} IS NULL)
5
+ OR
6
+ (${i.status} = 'settled' AND ${i.after_revision} IS NOT NULL AND ${i.outcome} IS NOT NULL AND ${i.settled_at} IS NOT NULL)
7
+ )`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(i.instance_id,i.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(i.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(i.requested_at)}));function Jt(i){let t=at.resolve(i);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function ye(i){let t=Jt(i);return createHash("sha256").update(t).digest("hex")}function Ft(i){return i.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Qt=class extends D{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{Rt(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=Ft(basename(n)),a=`${Ft(basename(dirname(n)))}-${r}`,c=[r,a];try{let u=l=>t.select({id:h.id}).from(h).where(and(eq(h.slug,l),ne$1(h.id,e))).limit(1).all().length>0;for(let l of c)if(!u(l))return l;for(let l=2;l<1e3;l+=1){let _=`${a}-${l}`;if(!u(_))return _}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let r of e)if(r.slug.includes("/")){let s=Ft(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:s,updated_at:new Date().toISOString()}).where(eq(h.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:a}=e,c=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:s,workspace_path:a,is_active:1,created_at:c,updated_at:c}).onConflictDoNothing().run(),t.update(h).set({workspace_path:a,updated_at:c}).where(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(t){let e=Jt(t),n=this.openHandle(true);try{let r=ye(e),s=basename(e),a=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:a,name:s,workspacePath:e}),{id:r,slug:a}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
4
8
  (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
9
  FROM threads t
6
10
  WHERE t.workspace_id = ${t}
7
11
  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 ke=[m,o,_,et,V,W,mt];function Bn(){return Z__default.join(Ze.homedir(),".crewx","crewx.db")}function Un(a){if(!ge.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),n=`${a}.bak-${t}`;return ge.copyFileSync(a,n),n}function be(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 Mn(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=Mn(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=be(a);if(!r)try{ht(a);}catch(f){let h=f instanceof Error?`${f.message} ${f.cause?.message??""}`:"";if(!e||!h.includes("duplicate column"))throw f}let l,u;r?(l=ke.map(h=>getTableConfig(h).name).filter(h=>!i.has(h)),u=i):(u=be(a),l=[...u].filter(f=>!i.has(f)));let c=[],p=[];for(let f of ke){let h=getTableConfig(f),x=h.name;if(!u.has(x))continue;let L=a.all(`PRAGMA table_info("${x}")`),B=new Set(L.map(N=>N.name)),H=new Set(h.columns.map(N=>N.name));for(let N of h.columns)if(!B.has(N.name)){if(!r){let Y=Hn(N);a.run(`ALTER TABLE "${x}" ADD COLUMN ${Y}`);}c.push({table:x,column:N.name});}for(let N of L)H.has(N.name)||p.push(`${x}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:p,backupPath:s}}function Re(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",Xn="0.8.9-rc.13",at=10,dt=parseInt(Xn.split("rc.")[1]),Jn=new Set(["workflow","mcp"]),Ee=600*1e3,Kt=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=?,
12
+ LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?and(eq(h.slug,t),ne$1(h.id,e)):eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let a=new Date().toISOString();s.db.insert(h).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:a,updated_at:a}).run();let c=s.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!c)throw new d("DB_ERROR","Insert did not return a row");return c}catch(a){throw a instanceof d?a:new d("DB_ERROR","Failed to insert workspace",a)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(and(eq(h.is_active,1),isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(h.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(eq(h.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var De=[h,o,p,ct,rt,J,Et];function Vn(){return at__default.join(ln.homedir(),".crewx","crewx.db")}function Qn(i){if(!Te.existsSync(i))return null;let t=Math.floor(Date.now()/1e3),e=`${i}.bak-${t}`;return Te.copyFileSync(i,e),e}function Ae(i){let t=i.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Zn(i){return i==null||typeof i=="object"&&"queryChunks"in i?null:typeof i=="number"?String(i):typeof i=="boolean"?i?"1":"0":typeof i=="string"?`'${i.replace(/'/g,"''")}'`:String(i)}function tr(i){let t=i.getSQLType(),e=`"${i.name}" ${t}`,n=Zn(i.default);return n!==null&&(e+=` DEFAULT ${n}`),i.notNull&&(e+=" NOT NULL"),e}function er(i,t){let e=t?.dbPath??Vn(),n=t?.force??false,r=t?.dryRun??false,s=r?null:Qn(e);if(n&&!r)try{i.run("DELETE FROM __drizzle_migrations");}catch{}let a=Ae(i);if(!r)try{Rt(i);}catch(f){let m=f instanceof Error?`${f.message} ${f.cause?.message??""}`:"";if(!n||!m.includes("duplicate column"))throw f}let c,u;r?(c=De.map(m=>getTableConfig(m).name).filter(m=>!a.has(m)),u=a):(u=Ae(i),c=[...u].filter(f=>!a.has(f)));let l=[],_=[];for(let f of De){let m=getTableConfig(f),E=m.name;if(!u.has(E))continue;let B=i.all(`PRAGMA table_info("${E}")`),M=new Set(B.map(A=>A.name)),z=new Set(m.columns.map(A=>A.name));for(let A of m.columns)if(!M.has(A.name)){if(!r){let Z=tr(A);i.run(`ALTER TABLE "${E}" ADD COLUMN ${Z}`);}l.push({table:E,column:A.name});}for(let A of B)z.has(A.name)||_.push(`${E}.${A.name} exists in DB but not in schema (untouched)`);}return {created:c,altered:l,warnings:_,backupPath:s}}function Oe(i){let t=i.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var pt="2026-05-09",cr="0.8.9-rc.13",ft=10,ht=parseInt(cr.split("rc.")[1]);function ve(){let i=sql`
13
+ CASE
14
+ WHEN ${o.model} LIKE 'claude-%' OR ${o.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
15
+ WHEN ${o.model} LIKE 'gpt-%' OR ${o.model} LIKE 'codex-%' THEN 'codex'
16
+ WHEN ${o.model} LIKE 'gemini-%' THEN 'gemini'
17
+ WHEN ${o.model} LIKE 'grok-%' THEN 'grok'
18
+ WHEN ${o.model} LIKE 'zai-%' OR ${o.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
19
+ WHEN ${o.model} LIKE 'minimax/%' THEN 'minimax'
20
+ WHEN ${o.model} LIKE 'qwen%' THEN 'qwen'
21
+ ELSE 'unknown'
22
+ END
23
+ `,t=sql`json_extract(${o.metadata}, '$.provider')`,e=sql`trim(${t})`,n=sql`substr(${e}, 1, instr(${e}, '/') - 1)`,r=sql`
24
+ CASE
25
+ WHEN instr(${e}, '/') > 0
26
+ AND ${n} IN ('cli', 'acp', 'api', 'plugin', 'remote')
27
+ THEN substr(${e}, instr(${e}, '/') + 1)
28
+ ELSE ${e}
29
+ END
30
+ `;return sql`
31
+ CASE
32
+ WHEN ${o.metadata} IS NULL THEN ${i}
33
+ WHEN json_valid(${o.metadata}) = 0 THEN 'unknown'
34
+ WHEN json_type(${o.metadata}, '$') IS NOT 'object' THEN 'unknown'
35
+ WHEN json_type(${o.metadata}, '$.provider') IS NULL THEN ${i}
36
+ WHEN json_type(${o.metadata}, '$.provider') IS NOT 'text' THEN 'unknown'
37
+ WHEN ${e} = '' THEN 'unknown'
38
+ WHEN trim(${r}) = '' THEN 'unknown'
39
+ ELSE ${r}
40
+ END
41
+ `}var lr=new Set(["workflow","mcp"]),Ce=600*1e3,te=class extends D{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:o.id,set:{pid:sql`COALESCE(excluded.pid, ${o.pid})`},setWhere:eq(o.status,"running")}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
9
42
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
10
43
  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(Jn.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),or(isNull(o.metadata),notLike(o.metadata,'%"kind":"workflow_card"%')))).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`
44
+ WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let s=r.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),a=s?.logs?JSON.parse(s.logs):[];a.push(e),r.update(o).set({logs:JSON.stringify(a)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(desc(o.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid,platform:o.platform,run_epoch:o.run_epoch}).from(o).where(eq(o.status,"running")).all(),n=Date.now(),r=new Set,s=0;for(let a of e){if(a.pid){let l=!1;try{process.kill(a.pid,0),l=!0;}catch{}l||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,a.id),eq(o.status,"running"))).run(),s++);continue}if(lr.has(a.platform??"cli"))continue;let c=`${a.id}:${a.run_epoch??0}`;r.add(c);let u=this.pidNullObservedSince.get(c);if(u===void 0){this.pidNullObservedSince.set(c,n);continue}n-u>=Ce&&(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,a.id),eq(o.status,"running"))).run(),s++,this.pidNullObservedSince.delete(c));}for(let a of Array.from(this.pidNullObservedSince.keys()))r.has(a)||this.pidNullObservedSince.delete(a);return s}finally{t.close();}}reapRunningWorkflowTasks(t=Ce){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let n=new Date(Date.now()-t).toISOString();return e.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,n),or(isNull(o.metadata),and(notLike(o.metadata,'%"kind":"workflow_card"%'),notLike(o.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let a=e?eq(o.workspace_id,e):void 0,c=a?and(eq(o.id,t),a):eq(o.id,t),u=s.db.select().from(o).where(c).limit(1).get()??void 0;if(!u){let l=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),_=a?and(l,a):l;u=s.db.select().from(o).where(_).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(u)return u}catch(a){throw new d("DB_ERROR","Failed to find task status",a)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),l=c.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let _ of l)r.has(_.id)||(r.add(_.id),s.push(_));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{c.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
12
45
  SELECT
13
46
  COALESCE(workspace_id, 'unknown') AS workspace_id,
14
47
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -29,7 +62,7 @@ ${e.join(`
29
62
  FROM tasks
30
63
  GROUP BY workspace_id
31
64
  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}%`))),f=n?and(p,eq(o.workspace_id,n)):p,h=c.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(f).all();for(let x of h)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 f of p)r.has(f.id)||(r.add(f.id),s.push(f));}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}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let e=w(n);try{t.push(...e.db.select({id:o.id,agent_id:o.agent_id,thread_id:o.thread_id,workspace_id:o.workspace_id,platform:o.platform,status:o.status,error:o.error,completed_at:o.completed_at,duration_ms:o.duration_ms,started_at:o.started_at,metadata:o.metadata}).from(o).where(and(eq(o.platform,"workflow"),like(o.metadata,'%"kind":"workflow_card"%'))).orderBy(desc(o.started_at)).all());}catch(r){throw new d("DB_ERROR","Failed to find workflow parent tasks",r)}finally{e.close();}}return t}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 f=this.parseWorkflowCardMetadata(c.metadata);f.kind==="workflow_card"&&(s.set(u,c.started_at),e.set(u,{taskId:c.id,workflowRunId:f.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"%')),f=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 f)l(L.thread_id,L);let h=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(h,i):h).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`
65
+ `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,s=0,a=0,c=0;for(let u of n){if(!existsSync(u))continue;let l=w(u);try{let _=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),f=e?and(_,eq(o.workspace_id,e)):_,m=l.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(f).all();for(let E of m)r.has(E.id)||(r.add(E.id),s+=E.input_tokens??0,a+=E.output_tokens??0,c+=E.cost_usd??0);}catch(_){throw new d("DB_ERROR","Failed to get thread token usage",_)}finally{l.close();}}return {inputTokens:s,outputTokens:a,costUsd:c}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),l=e?and(u,eq(o.workspace_id,e)):u,_=c.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let f of _)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{c.close();}}return s}parseWorkflowCardMetadata(t){if(!t)return {};try{let e=JSON.parse(t);return {kind:typeof e.kind=="string"?e.kind:void 0,workflowRunId:typeof e.workflowRunId=="string"?e.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let e of this.resolveDbPaths()){if(!existsSync(e))continue;let n=w(e);try{t.push(...n.db.select({id:o.id,agent_id:o.agent_id,thread_id:o.thread_id,workspace_id:o.workspace_id,platform:o.platform,status:o.status,error:o.error,completed_at:o.completed_at,duration_ms:o.duration_ms,started_at:o.started_at,metadata:o.metadata}).from(o).where(and(eq(o.platform,"workflow"),or(like(o.metadata,'%"kind":"workflow_card"%'),like(o.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(o.started_at)).all());}catch(r){throw new d("DB_ERROR","Failed to find workflow parent tasks",r)}finally{n.close();}}return t}batchFetchWorkflowCards(t,e){let n=new Map;if(t.length===0)return n;let r=new Set(t),s=new Map,a=e?eq(o.workspace_id,e):void 0,c=(u,l)=>{if(!u)return;let _=s.get(u);if(_&&l.started_at<=_)return;let f=this.parseWorkflowCardMetadata(l.metadata);f.kind!=="workflow_card"&&f.kind!=="workflow_ui_instance"||(s.set(u,l.started_at),n.set(u,{taskId:l.id,workflowRunId:f.workflowRunId,raw:l.result??void 0}));};for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let l=w(u);try{let _=and(inArray(o.thread_id,t),or(like(o.metadata,'%"kind":"workflow_card"%'),like(o.metadata,'%"kind":"workflow_ui_instance"%'))),f=l.db.select({id:o.id,thread_id:o.thread_id,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(a?and(_,a):_).all();for(let B of f)c(B.thread_id,B);let m=and(isNull(o.thread_id),or(like(o.metadata,'%"kind":"workflow_card"%'),like(o.metadata,'%"kind":"workflow_ui_instance"%'))),E=l.db.select({id:o.id,command:o.command,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(a?and(m,a):m).all();for(let B of E){let M=this.extractThreadIdFromCommand(B.command);!M||!r.has(M)||c(M,B);}}catch(_){throw new d("DB_ERROR","Failed to batch fetch workflow cards",_)}finally{l.close();}}return n}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(o.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(o.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(inArray(o.status,s));let a=t.q??t.search;a&&n.push(like(o.prompt,`%${a}%`)),t.from&&n.push(gte(o.started_at,t.from)),t.to&&n.push(lt(o.started_at,t.to));let c=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(o).where(c).get(),l=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(c).orderBy(l).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
33
66
  SELECT
34
67
  t.agent_id,
35
68
  t.workspace_id,
@@ -37,11 +70,11 @@ ${e.join(`
37
70
  COALESCE(SUM(
38
71
  COALESCE(t.input_tokens, 0)
39
72
  + CASE
40
- WHEN t.started_at >= ${it}
73
+ WHEN t.started_at >= ${pt}
41
74
  AND (
42
75
  t.crewx_version IS NULL
43
76
  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, ${at}) AS INTEGER) < ${dt})
77
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ft}) AS INTEGER) < ${ht})
45
78
  )
46
79
  THEN COALESCE(t.cached_input_tokens, 0)
47
80
  ELSE 0
@@ -53,18 +86,18 @@ ${e.join(`
53
86
  FROM tasks t
54
87
  WHERE t.status IN ('completed', 'success')
55
88
  AND t.started_at >= ${t}
56
- AND t.started_at < ${n}
57
- AND t.workspace_id = ${e}
89
+ AND t.started_at < ${e}
90
+ AND t.workspace_id = ${n}
58
91
  GROUP BY t.agent_id, t.workspace_id
59
92
  ORDER BY (
60
93
  COALESCE(SUM(
61
94
  COALESCE(t.input_tokens, 0)
62
95
  + CASE
63
- WHEN t.started_at >= ${it}
96
+ WHEN t.started_at >= ${pt}
64
97
  AND (
65
98
  t.crewx_version IS NULL
66
99
  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, ${at}) AS INTEGER) < ${dt})
100
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ft}) AS INTEGER) < ${ht})
68
101
  )
69
102
  THEN COALESCE(t.cached_input_tokens, 0)
70
103
  ELSE 0
@@ -80,11 +113,11 @@ ${e.join(`
80
113
  COALESCE(SUM(
81
114
  COALESCE(t.input_tokens, 0)
82
115
  + CASE
83
- WHEN t.started_at >= ${it}
116
+ WHEN t.started_at >= ${pt}
84
117
  AND (
85
118
  t.crewx_version IS NULL
86
119
  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, ${at}) AS INTEGER) < ${dt})
120
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ft}) AS INTEGER) < ${ht})
88
121
  )
89
122
  THEN COALESCE(t.cached_input_tokens, 0)
90
123
  ELSE 0
@@ -96,17 +129,17 @@ ${e.join(`
96
129
  FROM tasks t
97
130
  WHERE t.status IN ('completed', 'success')
98
131
  AND t.started_at >= ${t}
99
- AND t.started_at < ${n}
132
+ AND t.started_at < ${e}
100
133
  GROUP BY t.agent_id, t.workspace_id
101
134
  ORDER BY (
102
135
  COALESCE(SUM(
103
136
  COALESCE(t.input_tokens, 0)
104
137
  + CASE
105
- WHEN t.started_at >= ${it}
138
+ WHEN t.started_at >= ${pt}
106
139
  AND (
107
140
  t.crewx_version IS NULL
108
141
  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, ${at}) AS INTEGER) < ${dt})
142
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ft}) AS INTEGER) < ${ht})
110
143
  )
111
144
  THEN COALESCE(t.cached_input_tokens, 0)
112
145
  ELSE 0
@@ -114,18 +147,18 @@ ${e.join(`
114
147
  ), 0)
115
148
  + COALESCE(SUM(t.output_tokens), 0)
116
149
  ) DESC
117
- `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage",s)}finally{r.close();}}getAgentUsageTrendRaw(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(e?sql`
150
+ `).map(a=>({agentId:a.agent_id,workspaceId:a.workspace_id??null,totalTasks:a.total_tasks,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage",s)}finally{r.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
118
151
  SELECT
119
152
  date(t.started_at) AS date,
120
153
  t.agent_id,
121
154
  COALESCE(SUM(
122
155
  COALESCE(t.input_tokens, 0)
123
156
  + CASE
124
- WHEN t.started_at >= ${it}
157
+ WHEN t.started_at >= ${pt}
125
158
  AND (
126
159
  t.crewx_version IS NULL
127
160
  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, ${at}) AS INTEGER) < ${dt})
161
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ft}) AS INTEGER) < ${ht})
129
162
  )
130
163
  THEN COALESCE(t.cached_input_tokens, 0)
131
164
  ELSE 0
@@ -137,8 +170,8 @@ ${e.join(`
137
170
  FROM tasks t
138
171
  WHERE t.status IN ('completed', 'success')
139
172
  AND t.started_at >= ${t}
140
- AND t.started_at < ${n}
141
- AND t.workspace_id = ${e}
173
+ AND t.started_at < ${e}
174
+ AND t.workspace_id = ${n}
142
175
  GROUP BY date(t.started_at), t.agent_id
143
176
  ORDER BY date(t.started_at) ASC
144
177
  `:sql`
@@ -148,11 +181,11 @@ ${e.join(`
148
181
  COALESCE(SUM(
149
182
  COALESCE(t.input_tokens, 0)
150
183
  + CASE
151
- WHEN t.started_at >= ${it}
184
+ WHEN t.started_at >= ${pt}
152
185
  AND (
153
186
  t.crewx_version IS NULL
154
187
  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, ${at}) AS INTEGER) < ${dt})
188
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ft}) AS INTEGER) < ${ht})
156
189
  )
157
190
  THEN COALESCE(t.cached_input_tokens, 0)
158
191
  ELSE 0
@@ -164,82 +197,62 @@ ${e.join(`
164
197
  FROM tasks t
165
198
  WHERE t.status IN ('completed', 'success')
166
199
  AND t.started_at >= ${t}
167
- AND t.started_at < ${n}
200
+ AND t.started_at < ${e}
168
201
  GROUP BY date(t.started_at), t.agent_id
169
202
  ORDER BY date(t.started_at) ASC
170
- `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,n){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(and(eq(o.id,t),eq(o.workspace_id,n))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{e.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:o.id,thread_id:o.thread_id,status:o.status,result:o.result,error:o.error,started_at:o.started_at,completed_at:o.completed_at}).from(o).where(and(eq(o.agent_id,t.agentId),eq(o.workspace_id,t.workspaceId),sql`${o.metadata} IS NOT NULL AND json_valid(${o.metadata}) AND json_extract(${o.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(o.started_at)).limit(1).get()??null}catch(e){throw new d("DB_ERROR","Failed to find latest task by metadata",e)}finally{n.close();}}markTaskFailed(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),i=e?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,e)):and(eq(o.id,t),eq(o.status,"running"));r.db.update(o).set({status:"failed",error:n,completed_at:s}).where(i).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,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(like(o.prompt,`%${t}%`),eq(o.workspace_id,n)):like(o.prompt,`%${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 tasks by prompt hint",u)}finally{l.close();}}return s}getProviderUsage(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=sql`
171
- CASE
172
- WHEN ${o.model} LIKE 'claude-%' OR ${o.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
173
- WHEN ${o.model} LIKE 'gpt-%' OR ${o.model} LIKE 'codex-%' THEN 'codex'
174
- WHEN ${o.model} LIKE 'gemini-%' THEN 'gemini'
175
- WHEN ${o.model} LIKE 'zai-%' OR ${o.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
176
- WHEN ${o.model} LIKE 'minimax/%' THEN 'minimax'
177
- WHEN ${o.model} LIKE 'qwen%' THEN 'qwen'
178
- ELSE 'unknown'
179
- END
180
- `,i=sql`
203
+ `).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(and(eq(o.id,t),eq(o.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let e=this.openHandle(false);try{return e.db.select({id:o.id,thread_id:o.thread_id,status:o.status,result:o.result,error:o.error,started_at:o.started_at,completed_at:o.completed_at,metadata:o.metadata}).from(o).where(and(eq(o.agent_id,t.agentId),eq(o.workspace_id,t.workspaceId),sql`${o.metadata} IS NOT NULL AND json_valid(${o.metadata}) AND json_extract(${o.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(o.started_at)).limit(1).get()??null}catch(n){throw new d("DB_ERROR","Failed to find latest task by metadata",n)}finally{e.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),a=n?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,n)):and(eq(o.id,t),eq(o.status,"running"));r.db.update(o).set({status:"failed",error:e,completed_at:s}).where(a).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),l=c.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let _ of l)r.has(_.id)||(r.add(_.id),s.push(_));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{c.close();}}return s}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=ve(),a=sql`
181
204
  COALESCE(${o.input_tokens}, 0)
182
205
  + CASE
183
- WHEN ${o.started_at} >= ${it}
206
+ WHEN ${o.started_at} >= ${pt}
184
207
  AND (
185
208
  ${o.crewx_version} IS NULL
186
209
  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}, ${at}) AS INTEGER) < ${dt})
210
+ OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${ft}) AS INTEGER) < ${ht})
188
211
  )
189
212
  THEN COALESCE(${o.cached_input_tokens}, 0)
190
213
  ELSE 0
191
214
  END
192
- `,l=e?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${n} AND ${o.workspace_id} = ${e}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${n}`;return r.db.all(sql`
215
+ `,c=n?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e} AND ${o.workspace_id} = ${n}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e}`;return r.db.all(sql`
193
216
  SELECT
194
217
  ${s} AS provider,
195
218
  COUNT(*) AS total_tasks,
196
- COALESCE(SUM(${i}), 0) AS input_tokens,
219
+ COALESCE(SUM(${a}), 0) AS input_tokens,
197
220
  COALESCE(SUM(${o.output_tokens}), 0) AS output_tokens,
198
221
  COALESCE(SUM(${o.cached_input_tokens}), 0) AS cached_input_tokens,
199
222
  COALESCE(SUM(${o.cost_usd}), 0) AS cost_usd,
200
223
  COALESCE(SUM(${o.duration_ms}), 0) AS active_duration_ms,
201
224
  MAX(${o.completed_at}) AS last_active_at
202
225
  FROM ${o}
203
- ${l}
204
- GROUP BY provider
205
- ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${o.output_tokens}), 0)) DESC
206
- `).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}getModelUsage(t,n,e){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=sql`
207
- CASE
208
- WHEN ${o.model} LIKE 'claude-%' OR ${o.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
209
- WHEN ${o.model} LIKE 'gpt-%' OR ${o.model} LIKE 'codex-%' THEN 'codex'
210
- WHEN ${o.model} LIKE 'gemini-%' THEN 'gemini'
211
- WHEN ${o.model} LIKE 'zai-%' OR ${o.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
212
- WHEN ${o.model} LIKE 'minimax/%' THEN 'minimax'
213
- WHEN ${o.model} LIKE 'qwen%' THEN 'qwen'
214
- ELSE 'unknown'
215
- END
216
- `,i=sql`
226
+ ${c}
227
+ GROUP BY ${s}
228
+ ORDER BY (COALESCE(SUM(${a}), 0) + COALESCE(SUM(${o.output_tokens}), 0)) DESC
229
+ `).map(l=>({provider:l.provider,totalTasks:l.total_tasks,inputTokens:l.input_tokens,outputTokens:l.output_tokens,cachedInputTokens:l.cached_input_tokens,costUsd:l.cost_usd,totalTokens:l.input_tokens+l.output_tokens,activeDurationMs:l.active_duration_ms??0,lastActiveAt:l.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}getModelUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=ve(),a=sql`
217
230
  COALESCE(${o.input_tokens}, 0)
218
231
  + CASE
219
- WHEN ${o.started_at} >= ${it}
232
+ WHEN ${o.started_at} >= ${pt}
220
233
  AND (
221
234
  ${o.crewx_version} IS NULL
222
235
  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}, ${at}) AS INTEGER) < ${dt})
236
+ OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${ft}) AS INTEGER) < ${ht})
224
237
  )
225
238
  THEN COALESCE(${o.cached_input_tokens}, 0)
226
239
  ELSE 0
227
240
  END
228
- `,l=e?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${n} AND ${o.workspace_id} = ${e}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${n}`,u=r.db.all(sql`
241
+ `,c=n?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e} AND ${o.workspace_id} = ${n}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e}`,u=r.db.all(sql`
229
242
  SELECT
230
243
  ${o.model} AS model,
231
244
  ${s} AS provider,
232
245
  COUNT(*) AS total_tasks,
233
- COALESCE(SUM(${i}), 0) AS input_tokens,
246
+ COALESCE(SUM(${a}), 0) AS input_tokens,
234
247
  COALESCE(SUM(${o.output_tokens}), 0) AS output_tokens,
235
248
  COALESCE(SUM(${o.cached_input_tokens}), 0) AS cached_input_tokens,
236
249
  COALESCE(SUM(${o.cost_usd}), 0) AS cost_usd,
237
250
  COALESCE(SUM(${o.duration_ms}), 0) AS active_duration_ms,
238
251
  MAX(${o.completed_at}) AS last_active_at
239
252
  FROM ${o}
240
- ${l}
241
- GROUP BY ${o.model}
242
- `),c=new Map;for(let p of u){let f=Re(p.model??""),h=c.get(f);h?(h.totalTasks+=p.total_tasks,h.inputTokens+=p.input_tokens,h.outputTokens+=p.output_tokens,h.cachedInputTokens+=p.cached_input_tokens,h.costUsd+=p.cost_usd,h.totalTokens+=p.input_tokens+p.output_tokens,h.activeDurationMs+=p.active_duration_ms??0,p.last_active_at&&(!h.lastActiveAt||p.last_active_at>h.lastActiveAt)&&(h.lastActiveAt=p.last_active_at)):c.set(f,{model:f,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,f)=>f.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`
253
+ ${c}
254
+ GROUP BY ${o.model}, ${s}
255
+ `),l=new Map;for(let _ of u){let f=Oe(_.model??""),m=JSON.stringify([_.provider,f]),E=l.get(m);E?(E.totalTasks+=_.total_tasks,E.inputTokens+=_.input_tokens,E.outputTokens+=_.output_tokens,E.cachedInputTokens+=_.cached_input_tokens,E.costUsd+=_.cost_usd,E.totalTokens+=_.input_tokens+_.output_tokens,E.activeDurationMs+=_.active_duration_ms??0,_.last_active_at&&(!E.lastActiveAt||_.last_active_at>E.lastActiveAt)&&(E.lastActiveAt=_.last_active_at)):l.set(m,{model:f,provider:_.provider,totalTasks:_.total_tasks,inputTokens:_.input_tokens,outputTokens:_.output_tokens,cachedInputTokens:_.cached_input_tokens,costUsd:_.cost_usd,totalTokens:_.input_tokens+_.output_tokens,activeDurationMs:_.active_duration_ms??0,lastActiveAt:_.last_active_at??null});}return Array.from(l.values()).sort((_,f)=>f.costUsd-_.costUsd)}catch(s){throw new d("DB_ERROR","Failed to get model usage",s)}finally{r.close();}}getTasksForReport(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=n?sql`WHERE ${o.started_at} >= ${t} AND ${o.started_at} < ${e} AND ${o.workspace_id} = ${n}`:sql`WHERE ${o.started_at} >= ${t} AND ${o.started_at} < ${e}`;return r.db.all(sql`
243
256
  SELECT
244
257
  ${o.thread_id} AS thread_id,
245
258
  ${o.agent_id} AS agent_id,
@@ -250,11 +263,11 @@ ${e.join(`
250
263
  FROM ${o}
251
264
  ${s}
252
265
  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},f=l.get(c.thread_id);f?f.push(p):l.set(c.thread_id,[p]);}let u=[];for(let[c,p]of l){let f=p.filter(h=>h.agentId===t.targetAgentId).length;f<2||u.push({threadId:c,targetAgentTurnCount:f,turns:p});}return u.sort((c,p)=>{let f=c.turns[c.turns.length-1].startedAt,h=p.turns[p.turns.length-1].startedAt;return f<h?1:f>h?-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 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}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 (
266
+ `).map(c=>({threadId:c.thread_id,agentId:c.agent_id,startedAt:c.started_at,status:c.status,error:c.error,exitCode:c.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 e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(o.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&n.push(inArray(o.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&n.push(inArray(o.status,t.statuses)),t.from&&n.push(gte(o.started_at,t.from)),t.to&&n.push(lt(o.started_at,t.to));let r=n.length>0?and(...n):void 0,s=(t.order??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at),a={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?e.db.select(a).from(o).where(r).orderBy(s).limit(t.limit).all():e.db.select(a).from(o).where(r).orderBy(s).all()}catch(n){throw new d("DB_ERROR","Failed to find task evidence",n)}finally{e.close();}}findThreadChains(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=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),and(notLike(o.metadata,'%"kind":"workflow_card"%'),notLike(o.metadata,'%"kind":"workflow_ui_instance"%'))),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 a=e.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(),c=new Map;for(let l of a){if(!l.thread_id)continue;let _={id:l.id,agentId:l.agent_id,status:l.status,prompt:l.prompt,startedAt:l.started_at,completedAt:l.completed_at},f=c.get(l.thread_id);f?f.push(_):c.set(l.thread_id,[_]);}let u=[];for(let[l,_]of c){let f=_.filter(m=>m.agentId===t.targetAgentId).length;f<2||u.push({threadId:l,targetAgentTurnCount:f,turns:_});}return u.sort((l,_)=>{let f=l.turns[l.turns.length-1].startedAt,m=_.turns[_.turns.length-1].startedAt;return f<m?1:f>m?-1:0}),u.slice(0,n).map(l=>({threadId:l.threadId,targetAgentTurnCount:l.targetAgentTurnCount,turns:l.turns.slice(-r)}))}catch(n){throw new d("DB_ERROR","Failed to find thread chains",n)}finally{e.close();}}};var ee=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(eq(h.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
254
267
  SELECT 1 FROM tasks parent
255
268
  WHERE parent.id = ${t}.parent_task_id
256
269
  AND parent.thread_id = ${t}.thread_id
257
- )`)}findAllThreads(t){let n=this.resolveDbPaths(),e=new Set,r=[];for(let s of n){if(!existsSync(s))continue;let i=w(s);try{let l=t?eq(_.workspace_id,t):void 0,u=i.db.select().from(_).where(l).orderBy(desc(_.updated_at)).all();for(let c of u)e.has(c.id)||(e.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadsByIdsOrTitles(t,n){if(t.length===0)return [];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(inArray(_.id,t),inArray(_.title,t)),c=n?and(u,eq(_.workspace_id,n)):u,p=l.db.select().from(_).where(c).orderBy(desc(_.updated_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find threads by ids or titles",u)}finally{l.close();}}return s}findThreadById(t,n){let e=this.resolveDbPaths();for(let r of e){if(!existsSync(r))continue;let s=w(r);try{let i=eq(_.id,t),l=n?and(i,eq(_.workspace_id,n)):i,u=s.db.select().from(_).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(t,n){let e=this.resolveDbPaths();for(let r of e){if(!existsSync(r))continue;let s=w(r);try{let i=eq(_.id,t),l=n?and(i,eq(_.workspace_id,n)):i;if(s.db.select({id:_.id}).from(_).where(l).limit(1).get())return !0}catch(i){throw new d("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(t,n){let e=this.resolveDbPaths(),r=0,s=0,i=0,l=0,u=0,c=new Set;for(let p of e){if(!existsSync(p))continue;let f=w(p);try{let h=f.db.get(sql`
270
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!existsSync(s))continue;let a=w(s);try{let c=t?eq(p.workspace_id,t):void 0,u=a.db.select().from(p).where(c).orderBy(desc(p.updated_at)).all();for(let l of u)n.has(l.id)||(n.add(l.id),r.push(l));}catch(c){throw new d("DB_ERROR","Failed to find all threads",c)}finally{a.close();}}return r}findThreadsByIdsOrTitles(t,e){if(t.length===0)return [];let n=this.resolveDbPaths(),r=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=or(inArray(p.id,t),inArray(p.title,t)),l=e?and(u,eq(p.workspace_id,e)):u,_=c.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let f of _)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find threads by ids or titles",u)}finally{c.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let a=eq(p.id,t),c=e?and(a,eq(p.workspace_id,e)):a,u=s.db.select().from(p).where(c).limit(1).get()??void 0;if(u)return u}catch(a){throw new d("DB_ERROR","Failed to find thread by id",a)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let a=eq(p.id,t),c=e?and(a,eq(p.workspace_id,e)):a;if(s.db.select({id:p.id}).from(p).where(c).limit(1).get())return !0}catch(a){throw new d("DB_ERROR","Failed to check thread existence",a)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,a=0,c=0,u=0,l=new Set;for(let _ of n){if(!existsSync(_))continue;let f=w(_);try{let m=f.db.get(sql`
258
271
  SELECT
259
272
  count(*) AS cnt,
260
273
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -264,46 +277,46 @@ ${e.join(`
264
277
  FROM tasks child
265
278
  WHERE child.thread_id = ${t}
266
279
  AND ${this.topLevelTaskPredicateSql()}
267
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
268
- `);h&&(r+=h.cnt,s+=h.total_input,i+=h.total_output,l+=h.total_cached,u+=h.total_cost);let x=f.db.all(sql`
280
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
281
+ `);m&&(r+=m.cnt,s+=m.total_input,a+=m.total_output,c+=m.total_cached,u+=m.total_cost);let E=f.db.all(sql`
269
282
  SELECT DISTINCT child.agent_id FROM tasks child
270
283
  WHERE child.thread_id = ${t}
271
284
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
272
285
  AND ${this.topLevelTaskPredicateSql()}
273
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
274
- `);for(let L of x)c.add(L.agent_id);}catch(h){throw new d("DB_ERROR","Failed to aggregate task stats",h)}finally{f.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`
286
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
287
+ `);for(let B of E)l.add(B.agent_id);}catch(m){throw new d("DB_ERROR","Failed to aggregate task stats",m)}finally{f.close();}}return {taskCount:r,inputTokens:s,outputTokens:a,cachedInputTokens:c,costUsd:u,agentIds:Array.from(l)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),s=new Set,a=[];for(let c of r){if(!existsSync(c))continue;let u=w(c);try{let l;n!==void 0?l=u.db.all(sql`
275
288
  SELECT * FROM (
276
289
  SELECT child.*,
277
290
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
278
291
  FROM tasks child
279
292
  WHERE child.thread_id = ${t}
280
293
  AND ${this.topLevelTaskPredicateSql()}
281
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
294
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
282
295
  ) ranked
283
- WHERE rn <= ${e}
296
+ WHERE rn <= ${n}
284
297
  ORDER BY started_at ASC
285
- `):c=u.db.all(sql`
298
+ `):l=u.db.all(sql`
286
299
  SELECT child.* FROM tasks child
287
300
  WHERE child.thread_id = ${t}
288
301
  AND ${this.topLevelTaskPredicateSql()}
289
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
302
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
290
303
  ORDER BY child.started_at ASC
291
- `);for(let p of c)s.has(p.id)||(s.add(p.id),i.push(p));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(e!==void 0&&r.length>1){let l=new Map;for(let u of i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,p)=>(p.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,e));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(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=eq(o.thread_id,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 f of p)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,n,e){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=w(s);try{let l=and(eq(o.id,n),eq(o.thread_id,t)),u=e?and(l,eq(o.workspace_id,e)):l,c=i.db.select().from(o).where(u).limit(1).get();if(!c)continue;let p=i.db.select().from(o).where(eq(o.parent_task_id,c.id)).orderBy(asc(o.started_at)).all();return {task:c,children:p}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasksQuery(t,n){return sql`
304
+ `);for(let _ of l)s.has(_.id)||(s.add(_.id),a.push(_));}catch(l){throw new d("DB_ERROR","Failed to find top-level tasks",l)}finally{u.close();}}if(n!==void 0&&r.length>1){let c=new Map;for(let u of a){let l=u.agent_id??"";c.has(l)||c.set(l,[]),c.get(l).push(u);}a=[];for(let u of c.values())u.sort((l,_)=>(_.started_at??"").localeCompare(l.started_at??"")),a.push(...u.slice(0,n));a.sort((u,l)=>(u.started_at??"").localeCompare(l.started_at??""));}return a}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let a of n){if(!existsSync(a))continue;let c=w(a);try{let u=eq(o.thread_id,t),l=e?and(u,eq(o.workspace_id,e)):u,_=c.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let f of _)r.has(f.id)||(r.add(f.id),s.push(f));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{c.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let a=w(s);try{let c=and(eq(o.id,e),eq(o.thread_id,t)),u=n?and(c,eq(o.workspace_id,n)):c,l=a.db.select().from(o).where(u).limit(1).get();if(!l)continue;let _=a.db.select().from(o).where(eq(o.parent_task_id,l.id)).orderBy(asc(o.started_at)).all();return {task:l,children:_}}catch(c){throw new d("DB_ERROR","Failed to find task by id",c)}finally{a.close();}}}batchFetchTasksQuery(t,e){return sql`
292
305
  SELECT child.id, child.thread_id, child.agent_id, child.status,
293
306
  child.parent_task_id, child.started_at, child.completed_at,
294
307
  child.duration_ms, child.input_tokens, child.output_tokens,
295
308
  child.cost_usd, child.error
296
309
  FROM tasks child INDEXED BY idx_tasks_thread_id
297
- WHERE child.thread_id IN (${sql.join(t.map(e=>sql`${e}`),sql`, `)})
310
+ WHERE child.thread_id IN (${sql.join(t.map(n=>sql`${n}`),sql`, `)})
298
311
  AND ${this.topLevelTaskPredicateSql()}
299
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
312
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
300
313
  ORDER BY child.started_at ASC
301
- `}batchFetchTasks(t,n){let e=new Map;if(t.length===0)return e;let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=w(s);try{let l=i.db.all(this.batchFetchTasksQuery(t,n));for(let u of l){let c=u.thread_id;e.has(c)||e.set(c,[]),e.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return e}explainBatchFetchTasksPlan(t,n){let e=this.resolveDbPaths();for(let r of e){if(!existsSync(r))continue;let s=w(r);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,n)}`).map(l=>l.detail)}finally{s.close();}}return []}updateThreadTitle(t,n,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=eq(_.id,t),i=e?and(s,eq(_.workspace_id,e)):s;if(!r.db.select({id:_.id}).from(_).where(i).limit(1).get())return;r.db.update(_).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(_.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,n){let e=this.openHandle(true);try{let r=n.workspaceId?this.validateWorkspaceId(e,n.workspaceId):null,s=new Date().toISOString();if(e.db.select({id:_.id,message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()){let l={updated_at:s};n.title!==void 0&&(l.title=n.title),n.titleLocked!==void 0&&(l.title_locked=n.titleLocked?1:0),e.db.update(_).set(l).where(eq(_.id,t)).run();}else e.db.insert(_).values({id:t,platform:n.platform,workspace_id:r,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{e.close();}}ensureThread(t,n,e){let r=this.openHandle(true);try{let s=e?this.validateWorkspaceId(r,e):null,i=r.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(eq(_.id,t)).limit(1).get();if(i){s&&!i.workspace_id&&r.db.update(_).set({workspace_id:s}).where(eq(_.id,t)).run();return}let l=new Date().toISOString();r.db.insert(_).values({id:t,platform:n,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,n,e){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:r.db.transaction(l=>{let c=l.select({message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()?.message_count===0;return l.run(sql`
314
+ `}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let a=w(s);try{let c=a.db.all(this.batchFetchTasksQuery(t,e));for(let u of c){let l=u.thread_id;n.has(l)||n.set(l,[]),n.get(l).push(u);}}catch(c){throw new d("DB_ERROR","Failed to batch fetch tasks",c)}finally{a.close();}}return n}explainBatchFetchTasksPlan(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,e)}`).map(c=>c.detail)}finally{s.close();}}return []}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=eq(p.id,t),a=n?and(s,eq(p.workspace_id,n)):s;if(!r.db.select({id:p.id}).from(p).where(a).limit(1).get())return;r.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,s=new Date().toISOString();if(n.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let c={updated_at:s};e.title!==void 0&&(c.title=e.title),e.titleLocked!==void 0&&(c.title_locked=e.titleLocked?1:0),n.db.update(p).set(c).where(eq(p.id,t)).run();}else n.db.insert(p).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let s=n?this.validateWorkspaceId(r,n):null,a=r.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get();if(a){s&&!a.workspace_id&&r.db.update(p).set({workspace_id:s}).where(eq(p.id,t)).run();return}let c=new Date().toISOString();r.db.insert(p).values({id:t,platform:e,workspace_id:s,message_count:0,created_at:c,updated_at:c}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:r.db.transaction(c=>{let l=c.select({message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()?.message_count===0;return c.run(sql`
302
315
  UPDATE threads
303
- SET first_message = COALESCE(first_message, ${n}),
304
- title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
305
- last_message = ${n},
316
+ SET first_message = COALESCE(first_message, ${e}),
317
+ title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
318
+ last_message = ${e},
306
319
  message_count = message_count + 1,
307
320
  updated_at = ${s}
308
321
  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 f of c){let h=f.metadata?JSON.parse(f.metadata):{};typeof h.pinOrder=="number"&&(p===null||h.pinOrder<p)&&(p=h.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 f=p.metadata?JSON.parse(p.metadata):{},h=f.overdrive??{},x=r?.defaultTurns??h.defaultTurns??3,L=r?.updatedBy??"ui",B=new Date().toISOString(),H,N,Y,kt;switch(e){case "enable-count":{let bt=r?.turns??x,Rt=r?.consumeCurrent?Math.max(bt-1,0):bt;H=Rt>0?"count":"off",N=Rt,Y=!0,kt="count";break}case "enable-latch":{H="latch",N=0,Y=!0,kt="latch";break}case "disable":{H="off",N=0,Y=!1;break}default:{let bt=h.state??"off",Rt=typeof h.remaining=="number"?h.remaining:0;if(bt==="count"&&Rt>0){let re=Rt-1;re<=0?(H="off",N=0):(H="count",N=re),Y=!0,kt="count";}else bt==="latch"?(H="latch",N=0,Y=!0,kt="latch"):(H="off",N=0,Y=!1);break}}return f.overdrive={state:H,remaining:N,defaultTurns:x,updatedAt:B,updatedBy:L},c.update(_).set({metadata:JSON.stringify(f),updated_at:B}).where(l).run(),{applied:Y,appliedMode:kt,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 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}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 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}insertToolCall(t){let n=this.openHandle(true);try{n.db.insert(V).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(V).where(eq(V.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:V.tool_name,count:sql`count(*)`}).from(V).where(eq(V.task_id,t)).groupBy(V.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 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}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 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}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(mt).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(mt).orderBy(desc(mt.timestamp)).limit(t).all()}catch(e){throw new d("DB_ERROR","Failed to find recent request logs",e)}finally{n.close();}}};function Ce(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}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}upsert(t){let n=this.openHandle(true);try{let e=Ce(t.bucketStartMs),r=t.accountRef??"default";n.db.insert(v).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:[v.provider,v.account_ref,v.limit_window,v.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:v.provider,bucket_start:v.bucket_start,used_percent:v.used_percent,remaining_percent:v.remaining_percent,resets_at:v.resets_at}).from(v).where(and(eq(v.limit_window,t.window),gte(v.bucket_start,t.fromIso),lte(v.bucket_start,t.toIso))).orderBy(asc(v.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 Zt=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 Or(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}_${Or(8)}`}var ze=500,qe=50,te=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(P,eq(P.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(P).where(inArray(P.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:P.read_at}).from(k).leftJoin(P,and(eq(P.notification_id,k.id),eq(P.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(P,and(eq(P.notification_id,k.id),eq(P.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(P.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(P).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(P,and(eq(P.notification_id,k.id),eq(P.user_id,t.userId))).where(and(eq(k.workspace_id,t.workspaceId),isNull(P.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(P).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,ne=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{ne as AgentSuggestionRepository,T as BaseSqliteRepository,Ke as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,ze as DEFAULT_NOTIFICATION_CAP,qe as DEFAULT_NOTIFICATION_LIST_LIMIT,te as NotificationRepository,d as RepositoryError,Vt as RequestLogRepository,Yt as SpanRepository,Kt as TaskRepository,Jt as ThreadBoxRepository,Gt as ThreadRepository,Xt as ToolCallRepository,Qt as UsageLimitSnapshotRepository,Zt as UsageReportRepository,qt as WorkspaceRepository,Ce as calcBucketStart,w as openDrizzleDb,Fn as pushSchema,ht as runMigrations,O as runMigrationsOnce,o as tasks};
322
+ `),l},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:s}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!s)return null;let a=s.pinned?0:1,c=s.metadata?JSON.parse(s.metadata):{};if(a){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),l=n.db.select({metadata:p.metadata}).from(p).where(u).all(),_=null;for(let f of l){let m=f.metadata?JSON.parse(f.metadata):{};typeof m.pinOrder=="number"&&(_===null||m.pinOrder<_)&&(_=m.pinOrder);}c.pinOrder=_===null?0:_-1;}else delete c.pinOrder;return n.db.update(p).set({pinned:a,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(r).run(),{pinned:!!a}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),a=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!a)continue;let c=a.metadata?JSON.parse(a.metadata):{};c.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(c)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({starred:p.starred}).from(p).where(r).get();if(!s)return null;let a=s.starred?0:1;return n.db.update(p).set({starred:a}).where(r).run(),{starred:!!a}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let a=this.openHandle(true);try{let c=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return a.db.transaction(l=>{let _=l.select({metadata:p.metadata}).from(p).where(c).get();if(!_)return null;let f=_.metadata?JSON.parse(_.metadata):{},m=f.overdrive??{},E=r?.defaultTurns??m.defaultTurns??3,B=r?.updatedBy??"ui",M=new Date().toISOString(),z,A,Z,xt;switch(n){case "enable-count":{let Tt=r?.turns??E,Nt=r?.consumeCurrent?Math.max(Tt-1,0):Tt;z=Nt>0?"count":"off",A=Nt,Z=!0,xt="count";break}case "enable-latch":{z="latch",A=0,Z=!0,xt="latch";break}case "disable":{z="off",A=0,Z=!1;break}default:{let Tt=m.state??"off",Nt=typeof m.remaining=="number"?m.remaining:0;if(Tt==="count"&&Nt>0){let ue=Nt-1;ue<=0?(z="off",A=0):(z="count",A=ue),Z=!0,xt="count";}else Tt==="latch"?(z="latch",A=0,Z=!0,xt="latch"):(z="off",A=0,Z=!1);break}}return f.overdrive={state:z,remaining:A,defaultTurns:E,updatedAt:M,updatedBy:B},l.update(p).set({metadata:JSON.stringify(f),updated_at:M}).where(c).run(),{applied:Z,appliedMode:xt,state:z,remaining:A}},{behavior:"immediate"})}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to resolve overdrive",c)}finally{a.close();}}};var ne=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(ct).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(ct).where(eq(ct.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(ct).where(eq(ct.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var re=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(rt).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(rt).where(eq(rt.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:rt.tool_name,count:sql`count(*)`}).from(rt).where(eq(rt.task_id,t)).groupBy(rt.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var oe=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(J).where(eq(J.thread_id,t)).orderBy(asc(J.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(J).where(and(eq(J.id,e),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{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.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 n=e.db.select().from(J).where(eq(J.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var se=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(Et).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(Et).orderBy(desc(Et.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function qe(i){return new Date(Math.floor(i/3e5)*3e5).toISOString()}var ie=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=qe(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(P).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[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(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider: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 n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,a])=>({provider:s,points:a}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var ae=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(q).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:[q.workspace_id,q.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let n=e.db.select().from(q).where(and(eq(q.workspace_id,t.workspaceId),eq(q.month,t.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{e.close();}}findByMonth(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(q).where(and(eq(q.workspace_id,t),eq(q.month,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{n.close();}}listByWorkspace(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(q).where(eq(q.workspace_id,t)).orderBy(desc(q.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};var Ge="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function jr(i){let t=randomBytes(i*2),e="";for(let n=0;n<t.length&&e.length<i;n++){let r=t[n];r<248&&(e+=Ge[r%62]);}for(;e.length<i;)e+=Ge[randomBytes(1)[0]%62];return e}function Wt(i){return `${i}_${jr(8)}`}var Qe=500,Ze=50,de=class extends D{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??Qe;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}create(t){let e=this.openHandle(true);try{let n=Wt("ntf"),r=new Date().toISOString();return e.db.insert(k).values({id:n,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(e,t.workspaceId),{id:n}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create notification",n)}finally{e.close();}}enforceCap(t,e){let s=(t.db.select({count:sql`count(*)`}).from(k).where(eq(k.workspace_id,e)).get()?.count??0)-this.cap;if(s<=0)return;let c=t.db.select({id:k.id}).from(k).innerJoin(C,eq(C.notification_id,k.id)).where(eq(k.workspace_id,e)).groupBy(k.id).orderBy(asc(k.created_at)).limit(s).all().map(u=>u.id);c.length!==0&&(t.db.delete(C).where(inArray(C.notification_id,c)).run(),t.db.delete(k).where(inArray(k.id,c)).run());}list(t){if(!this.dbExists())return [];let e=t.limit??Ze,n=this.openHandle(false);try{return n.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(e).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{n.close();}}unreadCount(t){if(!this.dbExists())return 0;let e=this.openHandle(false);try{return e.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(n){throw new d("DB_ERROR","Failed to count unread notifications",n)}finally{e.close();}}markRead(t){let e=this.openHandle(true);try{if(!e.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 e.db.insert(C).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark notification read",n)}finally{e.close();}}markAllRead(t){let e=this.openHandle(true);try{let n=e.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(n.length===0)return 0;let r=new Date().toISOString();return e.db.transaction(s=>{for(let a of n)s.insert(C).values({notification_id:a.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),n.length}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark all notifications read",n)}finally{e.close();}}};var nn=50,le=class extends D{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}create(t){let e=this.openHandle(true);try{let n=new Date().toISOString(),r=[],s=t.map(a=>{let c=Wt("sug");return r.push(c),{id:c,workspace_id:a.workspaceId,agent_id:a.agentId,task_id:a.taskId??null,type:a.type,status:a.status??"pending",payload:a.payload,applied_commit_sha:a.appliedCommitSha??null,created_at:n,updated_at:n}});return s.length>0&&e.db.insert(S).values(s).run(),{ids:r}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create agent suggestions",n)}finally{e.close();}}findLatestSet(t,e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=n.db.select({task_id:S.task_id}).from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e))).orderBy(desc(S.created_at)).limit(1).get();if(!r)return [];let s=r.task_id===null?isNull(S.task_id):eq(S.task_id,r.task_id);return n.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),s)).orderBy(asc(S.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{n.close();}}findSetByTaskId(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),eq(S.task_id,n))).orderBy(asc(S.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,e,n){if(!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),eq(S.id,n))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{r.close();}}updateStatus(t,e,n){let r=this.openHandle(true);try{let s={status:e,updated_at:new Date().toISOString()};return n!==void 0&&(s.applied_commit_sha=n),r.db.update(S).set(s).where(eq(S.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,e,n=nn){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e))).orderBy(desc(S.created_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{r.close();}}findDismissed(t,e,n=20){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(S).where(and(eq(S.workspace_id,t),eq(S.agent_id,e),eq(S.status,"dismissed"))).orderBy(desc(S.updated_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{r.close();}}};export{le as AgentSuggestionRepository,D as BaseSqliteRepository,nn as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Qe as DEFAULT_NOTIFICATION_CAP,Ze as DEFAULT_NOTIFICATION_LIST_LIMIT,de as NotificationRepository,d as RepositoryError,se as RequestLogRepository,ne as SpanRepository,te as TaskRepository,oe as ThreadBoxRepository,ee as ThreadRepository,re as ToolCallRepository,ie as UsageLimitSnapshotRepository,ae as UsageReportRepository,Qt as WorkspaceRepository,qe as calcBucketStart,w as openDrizzleDb,er as pushSchema,Rt as runMigrations,O as runMigrationsOnce,o as tasks};