@crewx/sdk 0.9.0-rc.3 → 0.9.0-rc.31

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 (56) hide show
  1. package/dist/config/canonicalize-agent-options.d.ts +16 -0
  2. package/dist/config/models.generated.d.ts +22 -0
  3. package/dist/config/models.remote.d.ts +4 -0
  4. package/dist/config/overdrive.d.ts +24 -0
  5. package/dist/config/pricing.d.ts +8 -8
  6. package/dist/config/pricing.generated.d.ts +2 -0
  7. package/dist/config/pricing.remote.d.ts +4 -0
  8. package/dist/config/pricing.types.d.ts +5 -0
  9. package/dist/config/timeout.config.d.ts +3 -0
  10. package/dist/esm/index.js +123 -81
  11. package/dist/esm/plugins/index.js +119 -72
  12. package/dist/esm/repository/index.js +107 -60
  13. package/dist/esm/testing/index.js +1 -1
  14. package/dist/facade/Crewx.d.ts +5 -0
  15. package/dist/index.browser.d.ts +1 -1
  16. package/dist/index.browser.js +2 -2
  17. package/dist/index.d.ts +11 -4
  18. package/dist/index.js +124 -82
  19. package/dist/migrations/0008_careful_black_bird.sql +17 -0
  20. package/dist/migrations/0009_hot_dark_phoenix.sql +1 -0
  21. package/dist/migrations/0010_analyze_stats.sql +6 -0
  22. package/dist/migrations/0011_far_black_tarantula.sql +1 -0
  23. package/dist/migrations/0012_blue_turbo.sql +23 -0
  24. package/dist/migrations/meta/0008_snapshot.json +1327 -0
  25. package/dist/migrations/meta/0009_snapshot.json +1335 -0
  26. package/dist/migrations/meta/0010_snapshot.json +1335 -0
  27. package/dist/migrations/meta/0011_snapshot.json +1342 -0
  28. package/dist/migrations/meta/0012_snapshot.json +1494 -0
  29. package/dist/migrations/meta/_journal.json +35 -0
  30. package/dist/plugins/index.js +119 -72
  31. package/dist/provider/acp/adapters/claude.d.ts +0 -4
  32. package/dist/provider/acp/connection.d.ts +4 -0
  33. package/dist/provider/acp/meta.d.ts +4 -0
  34. package/dist/provider/bridge.d.ts +13 -1
  35. package/dist/provider/cli/adapter.types.d.ts +1 -0
  36. package/dist/provider/cli/adapters/claude.d.ts +0 -1
  37. package/dist/provider/cli/adapters/cli-knob.util.d.ts +2 -0
  38. package/dist/provider/cli/meta.d.ts +10 -2
  39. package/dist/provider/idle-watchdog.d.ts +19 -0
  40. package/dist/provider/models.d.ts +23 -0
  41. package/dist/provider/order.d.ts +1 -0
  42. package/dist/repository/index.d.ts +5 -1
  43. package/dist/repository/index.js +107 -60
  44. package/dist/repository/notification.repository.d.ts +58 -0
  45. package/dist/repository/task.repository.d.ts +34 -0
  46. package/dist/repository/thread.repository.d.ts +16 -2
  47. package/dist/repository/usage-report.repository.d.ts +27 -0
  48. package/dist/schema/index.d.ts +2 -0
  49. package/dist/schema/notifications.d.ts +303 -0
  50. package/dist/schema/usage-reports.d.ts +252 -0
  51. package/dist/testing/index.d.ts +2 -0
  52. package/dist/testing/index.js +1 -1
  53. package/dist/types/index.d.ts +7 -0
  54. package/dist/utils/id.d.ts +1 -1
  55. package/package.json +3 -2
  56. package/templates/agents/default.yaml +34 -0
@@ -1,14 +1,14 @@
1
- import*as H from'path';import H__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import jt,{existsSync,mkdirSync,readFileSync}from'fs';import ce from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt as lt$1,lte}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,getTableConfig}from'drizzle-orm/sqlite-core';var st=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var ie=()=>fileURLToPath(import.meta.url),ae=()=>H__default.dirname(ie()),b=ae();var T=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(ce.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function w(a){let t=st("better-sqlite3"),{drizzle:e}=st("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(r,s=[])=>n.prepare(r).run(...s),close:()=>n.close()}}var vt=new Set,ue={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function mt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function pe(a,t){if(t>0||!mt(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,s]of Object.entries(ue))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var _e={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function he(a,t,e){if(!mt(a,"__drizzle_migrations")||!mt(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=_e[o.tag];if(!l)continue;let u=H__default.join(t,`${o.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),h=createHash("sha256").update(c).digest("hex");if(r.has(h))continue;let m=a.all("PRAGMA table_info(tasks)"),g=new Set(m.map(y=>y.name));for(let[y,j]of Object.entries(l))g.has(y)||(a.run(`ALTER TABLE tasks ADD COLUMN ${y} ${j}`),g.add(y));}}function fe(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=H__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],g;for(;(g=h.exec(u))!==null;)m.push({table:g[1],column:g[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(W=>W.trim()).filter(Boolean).every(W=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(W)))continue;m.every(({table:W,column:ht})=>a.all(`PRAGMA table_info("${W}")`).some(ft=>ft.name===ht))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function Z(a){let{migrate:t}=st("drizzle-orm/better-sqlite3/migrator"),{sql:e}=st("drizzle-orm"),n=[H__default.join(b,"../migrations"),H__default.join(b,"migrations"),H__default.join(b,"../../../../drizzle/migrations"),H__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(H__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
1
+ import*as X from'path';import X__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import ie,{existsSync,mkdirSync,readFileSync}from'fs';import ze from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,lt as lt$1,or,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 wt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var Be=()=>fileURLToPath(import.meta.url),Ue=()=>X__default.dirname(Be()),R=Ue();var x=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,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function k(a){let t=wt("better-sqlite3"),{drizzle:e}=wt("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),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 Yt=new Set,Fe={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 At(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function qe(a,t){if(t>0||!At(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,s]of Object.entries(Fe))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var je={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function We(a,t,e){if(!At(a,"__drizzle_migrations")||!At(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),s=JSON.parse(readFileSync(X__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=je[i.tag];if(!l)continue;let u=X__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(S=>S.name));for(let[S,P]of Object.entries(l))h.has(S)||(a.run(`ALTER TABLE tasks ADD COLUMN ${S} ${P}`),h.add(S));}}function Ke(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),s=JSON.parse(readFileSync(X__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let l=X__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(L=>L.trim()).filter(Boolean).every(L=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(L)))continue;f.every(({table:L,column:U})=>a.all(`PRAGMA table_info("${L}")`).some(K=>K.name===U))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function dt(a){let{migrate:t}=wt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=wt("drizzle-orm"),n=[X__default.join(R,"../migrations"),X__default.join(R,"migrations"),X__default.join(R,"../../../../drizzle/migrations"),X__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(X__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
3
- `)}`);let s=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;s?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),pe(a,o),s?.cnt&&(fe(a,r,e),he(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function D(a,t){vt.has(t)||(Z(a),vt.add(t));}var _=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var i=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>_.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id)}));var M=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>M.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var B=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var L=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var tt=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var x=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));function kt(a){let t=H.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Mt(a){let t=kt(a);return createHash("sha256").update(t).digest("hex")}function lt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Rt=class extends T{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{Z(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=lt(basename(n)),o=`${lt(basename(dirname(n)))}-${r}`,l=[r,o];try{let u=c=>t.select({id:_.id}).from(_).where(and(eq(_.slug,c),ne(_.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let h=`${o}-${c}`;if(!u(h))return h}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,slug:_.slug}).from(_).all(),n=0;for(let r of e)if(r.slug.includes("/")){let s=lt(r.slug.replace(/\//g,"-"));t.db.update(_).set({slug:s,updated_at:new Date().toISOString()}).where(eq(_.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:o}=e,l=new Date().toISOString();t.insert(_).values({id:n,slug:r,name:s,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(_).set({workspace_path:o,updated_at:l}).where(and(eq(_.id,n),isNull(_.workspace_path))).run();}registerWorkspace(t){let e=kt(t),n=this.openHandle(true);try{let r=Mt(e),s=basename(e),o=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:o,name:s,workspacePath:e}),{id:r,slug:o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(_.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(_).where(n).get();return {rows:e.db.select().from(_).where(n).orderBy(desc(_.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(eq(_.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
3
+ `)}`);let s=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),qe(a,i),s?.cnt&&(Ke(a,r,e),We(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function O(a,t){Yt.has(t)||(dt(a),Yt.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 Q=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(()=>Q.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 Y=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 q=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 lt=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 H=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 g=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},a=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(a.workspace_id,sql`${a.created_at} DESC`)})),C=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},a=>({pk:primaryKey({columns:[a.notification_id,a.user_id]})}));function vt(a){let t=X.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function re(a){let t=vt(a);return createHash("sha256").update(t).digest("hex")}function St(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Lt=class extends x{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{dt(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=St(basename(n)),i=`${St(basename(dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:m.id}).from(m).where(and(eq(m.slug,c),ne(m.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let 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 e=t.db.select({id:m.id,slug:m.slug}).from(m).all(),n=0;for(let r of e)if(r.slug.includes("/")){let s=St(r.slug.replace(/\//g,"-"));t.db.update(m).set({slug:s,updated_at:new Date().toISOString()}).where(eq(m.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:i}=e,l=new Date().toISOString();t.insert(m).values({id:n,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,n),isNull(m.workspace_path))).run();}registerWorkspace(t){let e=vt(t),n=this.openHandle(true);try{let r=re(e),s=basename(e),i=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:i,name:s,workspacePath:e}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(m.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(m).where(n).get();return {rows:e.db.select().from(m).where(n).orderBy(desc(m.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(m).where(eq(m.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
4
4
  (SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
5
5
  FROM threads t
6
6
  WHERE t.workspace_id = ${t}
7
7
  ORDER BY t.updated_at DESC
8
- LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?and(eq(_.slug,t),ne(_.id,e)):eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.insert(_).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:o,updated_at:o}).run();let l=s.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(and(eq(_.is_active,1),isNotNull(_.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(_.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Kt=[_,i,p,M,B,L,tt];function He(){return H__default.join(ce.homedir(),".crewx","crewx.db")}function Ue(a){if(!jt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return jt.copyFileSync(a,e),e}function Gt(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Me(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function qe(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Me(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Fe(a,t){let e=t?.dbPath??He(),n=t?.force??false,r=t?.dryRun??false,s=r?null:Ue(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Gt(a);if(!r)try{Z(a);}catch(m){let g=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw m}let l,u;r?(l=Kt.map(g=>getTableConfig(g).name).filter(g=>!o.has(g)),u=o):(u=Gt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Kt){let g=getTableConfig(m),y=g.name;if(!u.has(y))continue;let j=a.all(`PRAGMA table_info("${y}")`),W=new Set(j.map($=>$.name)),ht=new Set(g.columns.map($=>$.name));for(let $ of g.columns)if(!W.has($.name)){if(!r){let ft=qe($);a.run(`ALTER TABLE "${y}" ADD COLUMN ${ft}`);}c.push({table:y,column:$.name});}for(let $ of j)ht.has($.name)||h.push(`${y}.${$.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:s}}var J="2026-05-09",Xe="0.8.9-rc.13",V=10,Q=parseInt(Xe.split("rc.")[1]),Tt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(m).where(eq(m.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(m.slug,t),ne(m.id,e)):eq(m.slug,t);return !!n.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{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(m).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=s.db.select().from(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,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);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 e=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(),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(m).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(m.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(m).where(eq(m.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var de=[m,o,_,Q,Y,q,lt];function Sn(){return X__default.join(ze.homedir(),".crewx","crewx.db")}function xn(a){if(!ie.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return ie.copyFileSync(a,e),e}function le(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Tn(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 Dn(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Tn(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Nn(a,t){let e=t?.dbPath??Sn(),n=t?.force??false,r=t?.dryRun??false,s=r?null:xn(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=le(a);if(!r)try{dt(a);}catch(f){let h=f instanceof Error?`${f.message} ${f.cause?.message??""}`:"";if(!n||!h.includes("duplicate column"))throw f}let l,u;r?(l=de.map(h=>getTableConfig(h).name).filter(h=>!i.has(h)),u=i):(u=le(a),l=[...u].filter(f=>!i.has(f)));let c=[],p=[];for(let f of de){let h=getTableConfig(f),S=h.name;if(!u.has(S))continue;let P=a.all(`PRAGMA table_info("${S}")`),L=new Set(P.map(T=>T.name)),U=new Set(h.columns.map(T=>T.name));for(let T of h.columns)if(!L.has(T.name)){if(!r){let K=Dn(T);a.run(`ALTER TABLE "${S}" ADD COLUMN ${K}`);}c.push({table:S,column:T.name});}for(let T of P)U.has(T.name)||p.push(`${S}.${T.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:p,backupPath:s}}function ce(a){let t=a.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var nt="2026-05-09",In="0.8.9-rc.13",rt=10,ot=parseInt(In.split("rc.")[1]),Ln=new Set(["workflow","mcp"]),pe=600*1e3,Ut=class extends x{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{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
9
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
10
10
  model=COALESCE(?, model)
11
- WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let s=r.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=s?.logs?JSON.parse(s.logs):[];o.push(e),r.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,t),eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(eq(i.status,"running")).all(),n=0;for(let r of e){if(!r.pid)continue;let s=!1;try{process.kill(r.pid,0),s=!0;}catch{}s||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,r.id),eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let o=e?eq(i.workspace_id,e):void 0,l=o?and(eq(i.id,t),o):eq(i.id,t),u=s.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),h=o?and(c,o):c;u=s.db.select().from(i).where(h).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=e?and(eq(i.parent_task_id,t),eq(i.workspace_id,e)):eq(i.parent_task_id,t),c=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
11
+ WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let s=r.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(e),r.update(o).set({logs:JSON.stringify(i)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(desc(o.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid,platform:o.platform,run_epoch:o.run_epoch}).from(o).where(eq(o.status,"running")).all(),n=Date.now(),r=new Set,s=0;for(let i of e){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,i.id),eq(o.status,"running"))).run(),s++);continue}if(Ln.has(i.platform??"cli"))continue;let l=`${i.id}:${i.run_epoch??0}`;r.add(l);let u=this.pidNullObservedSince.get(l);if(u===void 0){this.pidNullObservedSince.set(l,n);continue}n-u>=pe&&(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=pe){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$1(o.started_at,n))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=k(r);try{let i=e?eq(o.workspace_id,e):void 0,l=i?and(eq(o.id,t),i):eq(o.id,t),u=s.db.select().from(o).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),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,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),c=l.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let 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 e=this.openHandle(false);try{return e.db.all(t?sql`
12
12
  SELECT
13
13
  COALESCE(workspace_id, 'unknown') AS workspace_id,
14
14
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -29,7 +29,7 @@ ${n.join(`
29
29
  FROM tasks
30
30
  GROUP BY workspace_id
31
31
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
32
- `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,s=0,o=0,l=0;for(let u of n){if(!existsSync(u))continue;let c=w(u);try{let h=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),m=e?and(h,eq(i.workspace_id,e)):h,g=c.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(m).all();for(let y of g)r.has(y.id)||(r.add(y.id),s+=y.input_tokens??0,o+=y.output_tokens??0,l+=y.cost_usd??0);}catch(h){throw new d("DB_ERROR","Failed to get thread token usage",h)}finally{c.close();}}return {inputTokens:s,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),c=e?and(u,eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(i.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(i.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(inArray(i.status,s));let o=t.q??t.search;o&&n.push(like(i.prompt,`%${o}%`)),t.from&&n.push(gte(i.started_at,t.from)),t.to&&n.push(lt$1(i.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(i).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?asc(i.started_at):desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
32
+ `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,s=0,i=0,l=0;for(let u of n){if(!existsSync(u))continue;let c=k(u);try{let p=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),f=e?and(p,eq(o.workspace_id,e)):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 S of h)r.has(S.id)||(r.add(S.id),s+=S.input_tokens??0,i+=S.output_tokens??0,l+=S.cost_usd??0);}catch(p){throw new d("DB_ERROR","Failed to get thread token usage",p)}finally{c.close();}}return {inputTokens:s,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),c=e?and(u,eq(o.workspace_id,e)):u,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 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}batchFetchWorkflowCards(t,e){let n=new Map;if(t.length===0)return n;let r=new Set(t),s=new Map,i=e?eq(o.workspace_id,e):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),n.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=k(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 P of f)l(P.thread_id,P);let h=and(isNull(o.thread_id),like(o.metadata,'%"kind":"workflow_card"%')),S=c.db.select({id:o.id,command:o.command,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(i?and(h,i):h).all();for(let P of S){let L=this.extractThreadIdFromCommand(P.command);!L||!r.has(L)||l(L,P);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{c.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 i=t.q??t.search;i&&n.push(like(o.prompt,`%${i}%`)),t.from&&n.push(gte(o.started_at,t.from)),t.to&&n.push(lt$1(o.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(o).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
33
33
  SELECT
34
34
  t.agent_id,
35
35
  t.workspace_id,
@@ -37,11 +37,11 @@ ${n.join(`
37
37
  COALESCE(SUM(
38
38
  COALESCE(t.input_tokens, 0)
39
39
  + CASE
40
- WHEN t.started_at >= ${J}
40
+ WHEN t.started_at >= ${nt}
41
41
  AND (
42
42
  t.crewx_version IS NULL
43
43
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
44
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
44
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${rt}) AS INTEGER) < ${ot})
45
45
  )
46
46
  THEN COALESCE(t.cached_input_tokens, 0)
47
47
  ELSE 0
@@ -60,11 +60,11 @@ ${n.join(`
60
60
  COALESCE(SUM(
61
61
  COALESCE(t.input_tokens, 0)
62
62
  + CASE
63
- WHEN t.started_at >= ${J}
63
+ WHEN t.started_at >= ${nt}
64
64
  AND (
65
65
  t.crewx_version IS NULL
66
66
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
67
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
67
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${rt}) AS INTEGER) < ${ot})
68
68
  )
69
69
  THEN COALESCE(t.cached_input_tokens, 0)
70
70
  ELSE 0
@@ -80,11 +80,11 @@ ${n.join(`
80
80
  COALESCE(SUM(
81
81
  COALESCE(t.input_tokens, 0)
82
82
  + CASE
83
- WHEN t.started_at >= ${J}
83
+ WHEN t.started_at >= ${nt}
84
84
  AND (
85
85
  t.crewx_version IS NULL
86
86
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
87
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
87
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${rt}) AS INTEGER) < ${ot})
88
88
  )
89
89
  THEN COALESCE(t.cached_input_tokens, 0)
90
90
  ELSE 0
@@ -102,11 +102,11 @@ ${n.join(`
102
102
  COALESCE(SUM(
103
103
  COALESCE(t.input_tokens, 0)
104
104
  + CASE
105
- WHEN t.started_at >= ${J}
105
+ WHEN t.started_at >= ${nt}
106
106
  AND (
107
107
  t.crewx_version IS NULL
108
108
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
109
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
109
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${rt}) AS INTEGER) < ${ot})
110
110
  )
111
111
  THEN COALESCE(t.cached_input_tokens, 0)
112
112
  ELSE 0
@@ -114,18 +114,18 @@ ${n.join(`
114
114
  ), 0)
115
115
  + COALESCE(SUM(t.output_tokens), 0)
116
116
  ) DESC
117
- `).map(o=>({agentId:o.agent_id,workspaceId:o.workspace_id??null,totalTasks:o.total_tasks,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage",s)}finally{r.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
117
+ `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(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
118
  SELECT
119
119
  date(t.started_at) AS date,
120
120
  t.agent_id,
121
121
  COALESCE(SUM(
122
122
  COALESCE(t.input_tokens, 0)
123
123
  + CASE
124
- WHEN t.started_at >= ${J}
124
+ WHEN t.started_at >= ${nt}
125
125
  AND (
126
126
  t.crewx_version IS NULL
127
127
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
128
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
128
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${rt}) AS INTEGER) < ${ot})
129
129
  )
130
130
  THEN COALESCE(t.cached_input_tokens, 0)
131
131
  ELSE 0
@@ -148,11 +148,11 @@ ${n.join(`
148
148
  COALESCE(SUM(
149
149
  COALESCE(t.input_tokens, 0)
150
150
  + CASE
151
- WHEN t.started_at >= ${J}
151
+ WHEN t.started_at >= ${nt}
152
152
  AND (
153
153
  t.crewx_version IS NULL
154
154
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
155
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${V}) AS INTEGER) < ${Q})
155
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${rt}) AS INTEGER) < ${ot})
156
156
  )
157
157
  THEN COALESCE(t.cached_input_tokens, 0)
158
158
  ELSE 0
@@ -167,51 +167,94 @@ ${n.join(`
167
167
  AND t.started_at < ${e}
168
168
  GROUP BY date(t.started_at), t.agent_id
169
169
  ORDER BY date(t.started_at) ASC
170
- `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(and(eq(i.id,t),eq(i.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),o=n?and(eq(i.id,t),eq(i.status,"running"),eq(i.workspace_id,n)):and(eq(i.id,t),eq(i.status,"running"));r.db.update(i).set({status:"failed",error:e,completed_at:s}).where(o).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=e?and(like(i.prompt,`%${t}%`),eq(i.workspace_id,e)):like(i.prompt,`%${t}%`),c=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of c)r.has(h.id)||(r.add(h.id),s.push(h));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return s}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=sql`
170
+ `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(and(eq(o.id,t),eq(o.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),i=n?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,n)):and(eq(o.id,t),eq(o.status,"running"));r.db.update(o).set({status:"failed",error:e,completed_at:s}).where(i).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),c=l.db.select().from(o).where(u).orderBy(asc(o.started_at)).all();for(let 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,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=sql`
171
171
  CASE
172
- WHEN ${i.model} LIKE 'claude-%' OR ${i.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
173
- WHEN ${i.model} LIKE 'gpt-%' OR ${i.model} LIKE 'codex-%' THEN 'codex'
174
- WHEN ${i.model} LIKE 'gemini-%' THEN 'gemini'
175
- WHEN ${i.model} LIKE 'zai-%' OR ${i.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
176
- WHEN ${i.model} LIKE 'minimax/%' THEN 'minimax'
177
- WHEN ${i.model} LIKE 'qwen%' THEN 'qwen'
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
178
  ELSE 'unknown'
179
179
  END
180
- `,o=sql`
181
- COALESCE(${i.input_tokens}, 0)
180
+ `,i=sql`
181
+ COALESCE(${o.input_tokens}, 0)
182
182
  + CASE
183
- WHEN ${i.started_at} >= ${J}
183
+ WHEN ${o.started_at} >= ${nt}
184
184
  AND (
185
- ${i.crewx_version} IS NULL
186
- OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
187
- OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${V}) AS INTEGER) < ${Q})
185
+ ${o.crewx_version} IS NULL
186
+ OR (${o.crewx_version} LIKE '0.8.%' AND ${o.crewx_version} NOT LIKE '0.8.9%')
187
+ OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${rt}) AS INTEGER) < ${ot})
188
188
  )
189
- THEN COALESCE(${i.cached_input_tokens}, 0)
189
+ THEN COALESCE(${o.cached_input_tokens}, 0)
190
190
  ELSE 0
191
191
  END
192
- `,l=n?sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${t} AND ${i.started_at} < ${e} AND ${i.workspace_id} = ${n}`:sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${t} AND ${i.started_at} < ${e}`;return r.db.all(sql`
192
+ `,l=n?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e} AND ${o.workspace_id} = ${n}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e}`;return r.db.all(sql`
193
193
  SELECT
194
194
  ${s} AS provider,
195
195
  COUNT(*) AS total_tasks,
196
- COALESCE(SUM(${o}), 0) AS input_tokens,
197
- COALESCE(SUM(${i.output_tokens}), 0) AS output_tokens,
198
- COALESCE(SUM(${i.cached_input_tokens}), 0) AS cached_input_tokens,
199
- COALESCE(SUM(${i.cost_usd}), 0) AS cost_usd,
200
- COALESCE(SUM(${i.duration_ms}), 0) AS active_duration_ms,
201
- MAX(${i.completed_at}) AS last_active_at
202
- FROM ${i}
196
+ COALESCE(SUM(${i}), 0) AS input_tokens,
197
+ COALESCE(SUM(${o.output_tokens}), 0) AS output_tokens,
198
+ COALESCE(SUM(${o.cached_input_tokens}), 0) AS cached_input_tokens,
199
+ COALESCE(SUM(${o.cost_usd}), 0) AS cost_usd,
200
+ COALESCE(SUM(${o.duration_ms}), 0) AS active_duration_ms,
201
+ MAX(${o.completed_at}) AS last_active_at
202
+ FROM ${o}
203
203
  ${l}
204
204
  GROUP BY provider
205
- ORDER BY (COALESCE(SUM(${o}), 0) + COALESCE(SUM(${i.output_tokens}), 0)) DESC
206
- `).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}};var xt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:_.id}).from(_).where(eq(_.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
207
- ${t}.parent_task_id IS NULL
208
- OR ${t}.parent_task_id = ''
209
- OR NOT EXISTS (
210
- SELECT 1 FROM tasks parent
211
- WHERE parent.id = ${t}.parent_task_id
212
- AND parent.thread_id = ${t}.thread_id
213
- )
214
- )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!existsSync(s))continue;let o=w(s);try{let l=t?eq(p.workspace_id,t):void 0,u=o.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let c of u)n.has(c.id)||(n.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let o=eq(p.id,t),l=e?and(o,eq(p.workspace_id,e)):o,u=s.db.select().from(p).where(l).limit(1).get()??void 0;if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find thread by id",o)}finally{s.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=w(r);try{let o=eq(p.id,t),l=e?and(o,eq(p.workspace_id,e)):o;if(s.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(o){throw new d("DB_ERROR","Failed to check thread existence",o)}finally{s.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,s=0,o=0,l=0,u=0,c=new Set;for(let h of n){if(!existsSync(h))continue;let m=w(h);try{let g=m.db.get(sql`
205
+ ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${o.output_tokens}), 0)) DESC
206
+ `).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}getModelUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=sql`
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`
217
+ COALESCE(${o.input_tokens}, 0)
218
+ + CASE
219
+ WHEN ${o.started_at} >= ${nt}
220
+ AND (
221
+ ${o.crewx_version} IS NULL
222
+ OR (${o.crewx_version} LIKE '0.8.%' AND ${o.crewx_version} NOT LIKE '0.8.9%')
223
+ OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${rt}) AS INTEGER) < ${ot})
224
+ )
225
+ THEN COALESCE(${o.cached_input_tokens}, 0)
226
+ ELSE 0
227
+ END
228
+ `,l=n?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e} AND ${o.workspace_id} = ${n}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e}`,u=r.db.all(sql`
229
+ SELECT
230
+ ${o.model} AS model,
231
+ ${s} AS provider,
232
+ COUNT(*) AS total_tasks,
233
+ COALESCE(SUM(${i}), 0) AS input_tokens,
234
+ COALESCE(SUM(${o.output_tokens}), 0) AS output_tokens,
235
+ COALESCE(SUM(${o.cached_input_tokens}), 0) AS cached_input_tokens,
236
+ COALESCE(SUM(${o.cost_usd}), 0) AS cost_usd,
237
+ COALESCE(SUM(${o.duration_ms}), 0) AS active_duration_ms,
238
+ MAX(${o.completed_at}) AS last_active_at
239
+ FROM ${o}
240
+ ${l}
241
+ GROUP BY ${o.model}
242
+ `),c=new Map;for(let p of u){let f=ce(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,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
+ SELECT
244
+ ${o.thread_id} AS thread_id,
245
+ ${o.agent_id} AS agent_id,
246
+ ${o.started_at} AS started_at,
247
+ ${o.status} AS status,
248
+ ${o.error} AS error,
249
+ ${o.exit_code} AS exit_code
250
+ FROM ${o}
251
+ ${s}
252
+ ORDER BY ${o.started_at} ASC
253
+ `).map(l=>({threadId:l.thread_id,agentId:l.agent_id,startedAt:l.started_at,status:l.status,error:l.error,exitCode:l.exit_code}))}catch(s){throw new d("DB_ERROR","Failed to get tasks for report",s)}finally{r.close();}}};var Ht=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:m.id}).from(m).where(eq(m.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
254
+ SELECT 1 FROM tasks parent
255
+ WHERE parent.id = ${t}.parent_task_id
256
+ AND parent.thread_id = ${t}.thread_id
257
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!existsSync(s))continue;let i=k(s);try{let l=t?eq(_.workspace_id,t):void 0,u=i.db.select().from(_).where(l).orderBy(desc(_.updated_at)).all();for(let c of u)n.has(c.id)||(n.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadsByIdsOrTitles(t,e){if(t.length===0)return [];let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=or(inArray(_.id,t),inArray(_.title,t)),c=e?and(u,eq(_.workspace_id,e)):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,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=k(r);try{let i=eq(_.id,t),l=e?and(i,eq(_.workspace_id,e)):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,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=k(r);try{let i=eq(_.id,t),l=e?and(i,eq(_.workspace_id,e)):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,e){let n=this.resolveDbPaths(),r=0,s=0,i=0,l=0,u=0,c=new Set;for(let p of n){if(!existsSync(p))continue;let f=k(p);try{let h=f.db.get(sql`
215
258
  SELECT
216
259
  count(*) AS cnt,
217
260
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -222,13 +265,13 @@ ${n.join(`
222
265
  WHERE child.thread_id = ${t}
223
266
  AND ${this.topLevelTaskPredicateSql()}
224
267
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
225
- `);g&&(r+=g.cnt,s+=g.total_input,o+=g.total_output,l+=g.total_cached,u+=g.total_cost);let y=m.db.all(sql`
268
+ `);h&&(r+=h.cnt,s+=h.total_input,i+=h.total_output,l+=h.total_cached,u+=h.total_cost);let S=f.db.all(sql`
226
269
  SELECT DISTINCT child.agent_id FROM tasks child
227
270
  WHERE child.thread_id = ${t}
228
271
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
229
272
  AND ${this.topLevelTaskPredicateSql()}
230
273
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
231
- `);for(let j of y)c.add(j.agent_id);}catch(g){throw new d("DB_ERROR","Failed to aggregate task stats",g)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let l of r){if(!existsSync(l))continue;let u=w(l);try{let c;n!==void 0?c=u.db.all(sql`
274
+ `);for(let P of S)c.add(P.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,e,n){let r=this.resolveDbPaths(),s=new Set,i=[];for(let l of r){if(!existsSync(l))continue;let u=k(l);try{let c;n!==void 0?c=u.db.all(sql`
232
275
  SELECT * FROM (
233
276
  SELECT child.*,
234
277
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -245,13 +288,17 @@ ${n.join(`
245
288
  AND ${this.topLevelTaskPredicateSql()}
246
289
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
247
290
  ORDER BY child.started_at ASC
248
- `);for(let h of c)s.has(h.id)||(s.add(h.id),o.push(h));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&r.length>1){let l=new Map;for(let u of o){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}o=[];for(let u of l.values())u.sort((c,h)=>(h.started_at??"").localeCompare(c.started_at??"")),o.push(...u.slice(0,n));o.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return o}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=eq(i.thread_id,t),c=e?and(u,eq(i.workspace_id,e)):u,h=l.db.select().from(i).where(c).orderBy(asc(i.started_at)).all();for(let m of h)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return s}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=w(s);try{let l=and(eq(i.id,e),eq(i.thread_id,t)),u=n?and(l,eq(i.workspace_id,n)):l,c=o.db.select().from(i).where(u).limit(1).get();if(!c)continue;let h=o.db.select().from(i).where(eq(i.parent_task_id,c.id)).orderBy(asc(i.started_at)).all();return {task:c,children:h}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{o.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let o=w(s);try{let l=o.db.all(sql`
249
- SELECT child.* FROM tasks child
250
- WHERE child.thread_id IN (${sql.join(t.map(u=>sql`${u}`),sql`, `)})
251
- AND ${this.topLevelTaskPredicateSql()}
252
- ${e?sql`AND child.workspace_id = ${e}`:sql``}
253
- ORDER BY child.started_at ASC
254
- `);for(let u of l){let c=u.thread_id;n.has(c)||n.set(c,[]),n.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{o.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=eq(p.id,t),o=n?and(s,eq(p.workspace_id,n)):s;if(!r.db.select({id:p.id}).from(p).where(o).limit(1).get())return;r.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,s=new Date().toISOString();if(n.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let l={updated_at:s};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(p).set(l).where(eq(p.id,t)).run();}else n.db.insert(p).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let s=n?this.validateWorkspaceId(r,n):null,o=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(o){s&&!o.workspace_id&&r.db.update(p).set({workspace_id:s}).where(eq(p.id,t)).run();return}let l=new Date().toISOString();r.db.insert(p).values({id:t,platform:e,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:r.db.transaction(l=>{let c=l.select({message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()?.message_count===0;return l.run(sql`
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(n!==void 0&&r.length>1){let l=new Map;for(let u of i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,p)=>(p.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,n));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let l=k(i);try{let u=eq(o.thread_id,t),c=e?and(u,eq(o.workspace_id,e)):u,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,e,n){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=k(s);try{let l=and(eq(o.id,e),eq(o.thread_id,t)),u=n?and(l,eq(o.workspace_id,n)):l,c=i.db.select().from(o).where(u).limit(1).get();if(!c)continue;let 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,e){return sql`
292
+ SELECT child.id, child.thread_id, child.agent_id, child.status,
293
+ child.parent_task_id, child.started_at, child.completed_at,
294
+ child.duration_ms, child.input_tokens, child.output_tokens,
295
+ child.cost_usd, child.error
296
+ FROM tasks child INDEXED BY idx_tasks_thread_id
297
+ WHERE child.thread_id IN (${sql.join(t.map(n=>sql`${n}`),sql`, `)})
298
+ AND ${this.topLevelTaskPredicateSql()}
299
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
300
+ ORDER BY child.started_at ASC
301
+ `}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=k(s);try{let l=i.db.all(this.batchFetchTasksQuery(t,e));for(let u of l){let c=u.thread_id;n.has(c)||n.set(c,[]),n.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}explainBatchFetchTasksPlan(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=k(r);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,e)}`).map(l=>l.detail)}finally{s.close();}}return []}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=eq(_.id,t),i=n?and(s,eq(_.workspace_id,n)):s;if(!r.db.select({id:_.id}).from(_).where(i).limit(1).get())return;r.db.update(_).set({title:e,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,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:_.id,message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()){let l={updated_at:s};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(_).set(l).where(eq(_.id,t)).run();}else n.db.insert(_).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let s=n?this.validateWorkspaceId(r,n):null,i=r.db.select({id:_.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:e,workspace_id:s,message_count:0,created_at:l,updated_at:l}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:r.db.transaction(l=>{let c=l.select({message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()?.message_count===0;return l.run(sql`
255
302
  UPDATE threads
256
303
  SET first_message = COALESCE(first_message, ${e}),
257
304
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -259,4 +306,4 @@ ${n.join(`
259
306
  message_count = message_count + 1,
260
307
  updated_at = ${s}
261
308
  WHERE id = ${t}
262
- `),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:s}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!s)return null;let o=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(o){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),h=0;for(let m of c){let g=m.metadata?JSON.parse(m.metadata):{};typeof g.pinOrder=="number"&&g.pinOrder>h&&(h=g.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),o=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({starred:p.starred}).from(p).where(r).get();if(!s)return null;let o=s.starred?0:1;return n.db.update(p).set({starred:o}).where(r).run(),{starred:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}};var Dt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(M).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(M).where(eq(M.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(M).where(eq(M.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var At=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(B).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(B).where(eq(B.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:B.tool_name,count:sql`count(*)`}).from(B).where(eq(B.task_id,t)).groupBy(B.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var Ot=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(L).where(eq(L.thread_id,t)).orderBy(asc(L.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(L).where(and(eq(L.id,e),eq(L.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(L).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(L).where(eq(L.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Nt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(tt).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(tt).orderBy(desc(tt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function re(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Ct=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=re(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(x).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[x.provider,x.account_ref,x.limit_window,x.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:x.provider,bucket_start:x.bucket_start,used_percent:x.used_percent,remaining_percent:x.remaining_percent,resets_at:x.resets_at}).from(x).where(and(eq(x.limit_window,t.window),gte(x.bucket_start,t.fromIso),lte(x.bucket_start,t.toIso))).orderBy(asc(x.bucket_start)).all(),r=new Map;for(let s of n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,o])=>({provider:s,points:o}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};export{T as BaseSqliteRepository,d as RepositoryError,Nt as RequestLogRepository,Dt as SpanRepository,Tt as TaskRepository,Ot as ThreadBoxRepository,xt as ThreadRepository,At as ToolCallRepository,Ct as UsageLimitSnapshotRepository,Rt as WorkspaceRepository,re as calcBucketStart,w as openDrizzleDb,Fe as pushSchema,Z as runMigrations,D as runMigrationsOnce,i as tasks};
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,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(_).set({last_message:e,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,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(_).set(r).where(eq(_.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(_.id,t),eq(_.workspace_id,e)):eq(_.id,t),s=n.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=e?and(eq(_.pinned,1),eq(_.workspace_id,e)):eq(_.pinned,1),c=n.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 n.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{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?and(eq(_.id,t[r]),eq(_.workspace_id,e)):eq(_.id,t[r]),i=n.db.select({metadata:_.metadata}).from(_).where(s).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.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{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(_.id,t),eq(_.workspace_id,e)):eq(_.id,t),s=n.db.select({starred:_.starred}).from(_).where(r).get();if(!s)return null;let i=s.starred?0:1;return n.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{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let l=e?and(eq(_.id,t),eq(_.workspace_id,e)):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??{},S=r?.defaultTurns??h.defaultTurns??3,P=r?.updatedBy??"ui",L=new Date().toISOString(),U,T,K,ut;switch(n){case "enable-count":{let pt=r?.turns??S,_t=r?.consumeCurrent?Math.max(pt-1,0):pt;U=_t>0?"count":"off",T=_t,K=!0,ut="count";break}case "enable-latch":{U="latch",T=0,K=!0,ut="latch";break}case "disable":{U="off",T=0,K=!1;break}default:{let pt=h.state??"off",_t=typeof h.remaining=="number"?h.remaining:0;if(pt==="count"&&_t>0){let Gt=_t-1;Gt<=0?(U="off",T=0):(U="count",T=Gt),K=!0,ut="count";}else pt==="latch"?(U="latch",T=0,K=!0,ut="latch"):(U="off",T=0,K=!1);break}}return f.overdrive={state:U,remaining:T,defaultTurns:S,updatedAt:L,updatedBy:P},c.update(_).set({metadata:JSON.stringify(f),updated_at:L}).where(l).run(),{applied:K,appliedMode:ut,state:U,remaining:T}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Mt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(Q).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(Q).where(eq(Q.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find 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(Q).where(eq(Q.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 zt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(Y).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(Y).where(eq(Y.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:Y.tool_name,count:sql`count(*)`}).from(Y).where(eq(Y.task_id,t)).groupBy(Y.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 Ft=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:_.id}).from(_).where(eq(_.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(q).where(eq(q.thread_id,t)).orderBy(asc(q.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(q).where(and(eq(q.id,e),eq(q.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(q).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(q).where(eq(q.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 qt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{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(lt).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(lt).orderBy(desc(lt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function ye(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var jt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=ye(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(v).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:[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(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: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 n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,i])=>({provider:s,points:i}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var Wt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(H).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:[H.workspace_id,H.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(H).where(and(eq(H.workspace_id,t.workspaceId),eq(H.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(H).where(and(eq(H.workspace_id,t),eq(H.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(H).where(eq(H.workspace_id,t)).orderBy(desc(H.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};var De="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function hr(a){let t=randomBytes(a*2),e="";for(let n=0;n<t.length&&e.length<a;n++){let r=t[n];r<248&&(e+=De[r%62]);}for(;e.length<a;)e+=De[randomBytes(1)[0]%62];return e}function Ne(a){return `${a}_${hr(8)}`}var Pe=500,Ie=50,Kt=class extends x{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??Pe;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}create(t){let e=this.openHandle(true);try{let n=Ne("ntf"),r=new Date().toISOString();return e.db.insert(g).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(g).where(eq(g.workspace_id,e)).get()?.count??0)-this.cap;if(s<=0)return;let l=t.db.select({id:g.id}).from(g).innerJoin(C,eq(C.notification_id,g.id)).where(eq(g.workspace_id,e)).groupBy(g.id).orderBy(asc(g.created_at)).limit(s).all().map(u=>u.id);l.length!==0&&(t.db.delete(C).where(inArray(C.notification_id,l)).run(),t.db.delete(g).where(inArray(g.id,l)).run());}list(t){if(!this.dbExists())return [];let e=t.limit??Ie,n=this.openHandle(false);try{return n.db.select({id:g.id,workspace_id:g.workspace_id,agent_id:g.agent_id,task_id:g.task_id,thread_id:g.thread_id,source:g.source,level:g.level,title:g.title,body:g.body,target_user_id:g.target_user_id,created_at:g.created_at,metadata:g.metadata,read_at:C.read_at}).from(g).leftJoin(C,and(eq(C.notification_id,g.id),eq(C.user_id,t.userId))).where(eq(g.workspace_id,t.workspaceId)).orderBy(desc(g.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(g).leftJoin(C,and(eq(C.notification_id,g.id),eq(C.user_id,t.userId))).where(and(eq(g.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:g.id}).from(g).where(and(eq(g.id,t.notificationId),eq(g.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:g.id}).from(g).leftJoin(C,and(eq(C.notification_id,g.id),eq(C.user_id,t.userId))).where(and(eq(g.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 i of n)s.insert(C).values({notification_id:i.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();}}};export{x as BaseSqliteRepository,Pe as DEFAULT_NOTIFICATION_CAP,Ie as DEFAULT_NOTIFICATION_LIST_LIMIT,Kt as NotificationRepository,d as RepositoryError,qt as RequestLogRepository,Mt as SpanRepository,Ut as TaskRepository,Ft as ThreadBoxRepository,Ht as ThreadRepository,zt as ToolCallRepository,jt as UsageLimitSnapshotRepository,Wt as UsageReportRepository,Lt as WorkspaceRepository,ye as calcBucketStart,k as openDrizzleDb,Nn as pushSchema,dt as runMigrations,O as runMigrationsOnce,o as tasks};
@@ -1 +1 @@
1
- function y(){let e=[];return {events:e,async log(t,r){e.push({event:t,payload:r});}}}function R(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,r){e.debug.push({msg:t,meta:r});},info(t,r){e.info.push({msg:t,meta:r});},warn(t,r){e.warn.push({msg:t,meta:r});},error(t,r){e.error.push({msg:t,meta:r});}}}function E(){let e=200,t,r,n={},o={status(s){return e=s,o},set(s,i){return n[s]=i,o},send(s){return r=s,o},json(s){return t=s,o},end(){return o},getStatusCode:()=>e,getJsonBody:()=>t,getSentBody:()=>r,getHeaders:()=>({...n})};return o}function k(){let e=[];return {routes:e,registerRoute(r,n,o){e.push({path:r,handler:n,opts:o});},async simulate(r,n,o=Buffer.alloc(0),s={},i={},p={}){let d=e.find(m=>m.path===n);if(!d)return {status:404,body:{error:"Not found"},headers:{}};let f={method:r,url:n,headers:s,body:o,params:i,query:p},u=E();return await d.handler(f,u),{status:u.getStatusCode(),body:u.getJsonBody()??u.getSentBody(),headers:u.getHeaders()}}}}function b(e){let t=new Map,r=n=>n.startsWith(`${e}::`)?n:`${e}::${n}`;return {async get(n){let o=t.get(r(n));return o?o.value:void 0},async set(n,o){t.set(r(n),{value:o});},async delete(n){return t.delete(r(n))},async list(n){let o=n?r(n):`${e}::`,s=[];for(let i of t.keys())i.startsWith(o)&&s.push(i.slice(e.length+2));return s}}}function l(e){return b(e)}function M(){let e=new Map;return {blobs:e,async put(t,r,n){return e.set(t,{data:r,contentType:n}),t},async get(t){let r=e.get(t);return r?r.data:void 0},async delete(t){return e.delete(t)}}}function P(e){let t=e.instanceId??"mock-instance",r=y(),n=R(),o=k(),s=l(t),i=M(),p=[],d=[],f=[],u={run:async()=>({output:""}),...e.agentRunner},m=new AbortController,x=async a=>(p.push(a),{accepted:true}),S=async a=>(d.push(a),{accepted:true}),w=async(a,h)=>{f.push({messageId:a,patch:h});},A=async a=>({userId:a,displayName:a}),v=async()=>{},C=async()=>({messageId:"mock-proactive",sentAt:Date.now()});return {instanceId:t,installationId:e.installationId,config:e.config,capabilities:new Set(e.capabilities??[]),log:n,agentRunner:u,db:s,storage:i,audit:r,abortSignal:e.abortSignal??m.signal,httpRouter:o,router:o,inbound:x,emitEvent:S,updateMessage:w,resolveUser:A,respondSync:v,proactive:C,inboundCalls:p,emittedEvents:d,sentMessages:f}}export{y as createMockAudit,P as createMockContext,R as createMockLogger,k as createMockRouter,M as createMockStorage,l as createMockStore};
1
+ function f(){let e=[];return {events:e,async log(t,r){e.push({event:t,payload:r});}}}function h(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,r){e.debug.push({msg:t,meta:r});},info(t,r){e.info.push({msg:t,meta:r});},warn(t,r){e.warn.push({msg:t,meta:r});},error(t,r){e.error.push({msg:t,meta:r});}}}function A(){let e=200,t,r,n={},o={status(i){return e=i,o},set(i,s){return n[i]=s,o},send(i){return r=i,o},json(i){return t=i,o},end(){return o},getStatusCode:()=>e,getJsonBody:()=>t,getSentBody:()=>r,getHeaders:()=>({...n})};return o}function y(){let e=[];return {routes:e,registerRoute(r,n,o){e.push({path:r,handler:n,opts:o});},async simulate(r,n,o=Buffer.alloc(0),i={},s={},p={}){let g=e.find(m=>m.path===n);if(!g)return {status:404,body:{error:"Not found"},headers:{}};let l={method:r,url:n,headers:i,body:o,params:s,query:p},c=A();return await g.handler(l,c),{status:c.getStatusCode(),body:c.getJsonBody()??c.getSentBody(),headers:c.getHeaders()}}}}function R(e){let t=new Map,r=n=>n.startsWith(`${e}::`)?n:`${e}::${n}`;return {async get(n){let o=t.get(r(n));return o?o.value:void 0},async set(n,o){t.set(r(n),{value:o});},async delete(n){return t.delete(r(n))},async list(n){let o=n?r(n):`${e}::`,i=[];for(let s of t.keys())s.startsWith(o)&&i.push(s.slice(e.length+2));return i}}}function x(e){return R(e)}function M(){let e=new Map;return {blobs:e,async put(t,r,n){return e.set(t,{data:r,contentType:n}),t},async get(t){let r=e.get(t);return r?r.data:void 0},async delete(t){return e.delete(t)}}}function S(e){let t=e.instanceId??"mock-instance",r=f(),n=h(),o=y(),i=x(t),s=M(),p=[],g=[],l=[],c={run:async()=>({output:""}),...e.agentRunner},m=new AbortController,v=async u=>(p.push(u),{accepted:true}),C=async u=>(g.push(u),{accepted:true}),k=async(u,w)=>{l.push({messageId:u,patch:w});},E=async u=>({userId:u,displayName:u}),b=async()=>{},O=async()=>({messageId:"mock-proactive",sentAt:Date.now()});return {instanceId:t,installationId:e.installationId,config:e.config,capabilities:new Set(e.capabilities??[]),log:n,agentRunner:c,db:i,storage:s,audit:r,abortSignal:e.abortSignal??m.signal,httpRouter:o,router:o,inbound:v,emitEvent:C,updateMessage:k,resolveUser:E,respondSync:b,proactive:O,inboundCalls:p,emittedEvents:g,sentMessages:l}}function T(){}var P={claude:{models:[{id:"claude-fable-5",name:"Claude Fable 5"},{id:"claude-sonnet-5",name:"Claude Sonnet 5"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8 (Extended)"},{id:"claude-opus-4-8",name:"Claude Opus 4.8"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7 (Extended)"},{id:"claude-opus-4-7",name:"Claude Opus 4.7"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6 (Extended)"},{id:"claude-opus-4-6",name:"Claude Opus 4.6"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6 (Extended)"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5"}],modes:[{id:"default",name:"Default"},{id:"acceptEdits",name:"Accept Edits"},{id:"plan",name:"Plan"},{id:"auto",name:"Auto"},{id:"dontAsk",name:"Don't Ask"},{id:"bypassPermissions",name:"Bypass Permissions"}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-opus-4-6":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}}},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna"},{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark"}],modes:[{id:"agent",name:"Agent"},{id:"read-only",name:"Read Only"},{id:"plan",name:"Plan"},{id:"agent-full-access",name:"Agent Full Access"},{id:"yolo",name:"YOLO"}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","low","medium","high","xhigh"],defaultEffort:"high"}}},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro"}],modes:[{id:"interactive",name:"Interactive"},{id:"plan",name:"Plan"},{id:"autopilot",name:"Autopilot"}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{}},antigravity:{models:[{id:"Gemini 3.5 Flash (Medium)",name:"Gemini 3.5 Flash (Medium)"},{id:"Gemini 3.5 Flash (High)",name:"Gemini 3.5 Flash (High)"},{id:"Gemini 3.5 Flash (Low)",name:"Gemini 3.5 Flash (Low)"},{id:"Gemini 3.1 Pro (Low)",name:"Gemini 3.1 Pro (Low)"},{id:"Gemini 3.1 Pro (High)",name:"Gemini 3.1 Pro (High)"},{id:"Claude Sonnet 4.6 (Thinking)",name:"Claude Sonnet 4.6 (Thinking)"},{id:"Claude Opus 4.6 (Thinking)",name:"Claude Opus 4.6 (Thinking)"},{id:"GPT-OSS 120B (Medium)",name:"GPT-OSS 120B (Medium)"}],modes:[],effort:[],modelOverrides:{}}};Object.fromEntries(Object.entries(P).map(([e,t])=>[e,t.models]));function B(){}export{f as createMockAudit,S as createMockContext,h as createMockLogger,y as createMockRouter,M as createMockStorage,x as createMockStore,B as resetModelsOverride,T as resetPricingOverride};