@crewx/sdk 0.8.8-rc.3 → 0.8.8-rc.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
- 'use strict';var Lt=require('fs'),U=require('path'),Kt=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Lt__default=/*#__PURE__*/_interopDefault(Lt);var U__namespace=/*#__PURE__*/_interopNamespace(U);var Kt__default=/*#__PURE__*/_interopDefault(Kt);var Z=(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 R=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:U.join(Kt__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return Lt.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=Z("better-sqlite3"),{drizzle:e}=Z("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 St=new Set,Vt={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 Qt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Zt(a,t){if(t>0||!Qt(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(Vt))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}function te(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(Lt.readFileSync(U__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=U__namespace.default.join(t,`${o.tag}.sql`);if(!Lt.existsSync(l))continue;let u=Lt.readFileSync(l,"utf-8"),p=crypto.createHash("sha256").update(u).digest("hex");if(r.has(p))continue;let f=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],b;for(;(b=f.exec(u))!==null;)m.push({table:b[1],column:b[2]});if(m.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;m.every(({table:L,column:J})=>a.all(`PRAGMA table_info("${L}")`).some(lt=>lt.name===J))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${o.when})`);}}function X(a){let{migrate:t}=Z("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Z("drizzle-orm"),n=[U__namespace.default.join(__dirname,"../migrations"),U__namespace.default.join(__dirname,"migrations"),U__namespace.default.join(__dirname,"../../../../drizzle/migrations"),U__namespace.default.join(process.cwd(),"drizzle/migrations")],r=n.find(p=>Lt.existsSync(U__namespace.default.join(p,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
1
+ 'use strict';var Lt=require('fs'),$=require('path'),Kt=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Lt__default=/*#__PURE__*/_interopDefault(Lt);var $__namespace=/*#__PURE__*/_interopNamespace($);var Kt__default=/*#__PURE__*/_interopDefault(Kt);var Z=(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 R=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:$.join(Kt__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return Lt.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=Z("better-sqlite3"),{drizzle:e}=Z("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:(s,r=[])=>n.prepare(s).run(...r),close:()=>n.close()}}var St=new Set,Vt={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 Qt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Zt(a,t){if(t>0||!Qt(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(s=>s.name));for(let[s,r]of Object.entries(Vt))n.has(s)||a.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}function te(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(Lt.readFileSync($__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=$__namespace.default.join(t,`${o.tag}.sql`);if(!Lt.existsSync(l))continue;let u=Lt.readFileSync(l,"utf-8"),p=crypto.createHash("sha256").update(u).digest("hex");if(s.has(p))continue;let f=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],b;for(;(b=f.exec(u))!==null;)m.push({table:b[1],column:b[2]});if(m.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;m.every(({table:L,column:J})=>a.all(`PRAGMA table_info("${L}")`).some(lt=>lt.name===J))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${o.when})`);}}function X(a){let{migrate:t}=Z("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Z("drizzle-orm"),n=[$__namespace.default.join(__dirname,"../migrations"),$__namespace.default.join(__dirname,"migrations"),$__namespace.default.join(__dirname,"../../../../drizzle/migrations"),$__namespace.default.join(process.cwd(),"drizzle/migrations")],s=n.find(p=>Lt.existsSync($__namespace.default.join(p,"meta/_journal.json")));if(!s)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),Zt(a,o),te(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 p=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${u} migration${u>1?"s":""} applied).`);}}function T(a,t){St.has(t)||(X(a),St.add(t));}var h=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var i=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var c=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>h.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id)}));var H=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>H.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var v=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var P=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>c.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var G=sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));function ut(a){let t=U__namespace.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Bt(a){let t=ut(a);return crypto.createHash("sha256").update(t).digest("hex")}function rt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var ft=class extends R{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?U.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{X(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=rt(U.basename(n)),o=`${rt(U.basename(U.dirname(n)))}-${r}`,l=[r,o];try{let u=p=>t.select({id:h.id}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.slug,p),drizzleOrm.ne(h.id,e))).limit(1).all().length>0;for(let p of l)if(!u(p))return p;for(let p=2;p<1e3;p+=1){let f=`${o}-${p}`;if(!u(f))return f}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let r of e)if(r.slug.includes("/")){let s=rt(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:s,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:o}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:s,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:o,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(h.id,n),drizzleOrm.isNull(h.workspace_path))).run();}registerWorkspace(t){let e=ut(t),n=this.openHandle(true);try{let r=Bt(e),s=U.basename(e),o=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:o,name:s,workspacePath:e}),{id:r,slug:o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?drizzleOrm.eq(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:drizzleOrm.sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(drizzleOrm.desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(drizzleOrm.sql`SELECT t.*,
3
+ `)}`);let r=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;r?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Zt(a,o),r?.cnt&&te(a,s,e),t(a,{migrationsFolder:s});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${u} migration${u>1?"s":""} applied).`);}}function T(a,t){St.has(t)||(X(a),St.add(t));}var h=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var i=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var c=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>h.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id)}));var F=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>F.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var v=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var P=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>c.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var G=sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));function ut(a){let t=$__namespace.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Bt(a){let t=ut(a);return crypto.createHash("sha256").update(t).digest("hex")}function st(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var ft=class extends R{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 s=$.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{X(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=st($.basename(n)),o=`${st($.basename($.dirname(n)))}-${s}`,l=[s,o];try{let u=p=>t.select({id:h.id}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.slug,p),drizzleOrm.ne(h.id,e))).limit(1).all().length>0;for(let p of l)if(!u(p))return p;for(let p=2;p<1e3;p+=1){let f=`${o}-${p}`;if(!u(f))return f}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=st(s.slug.replace(/\//g,"-"));t.db.update(h).set({slug:r,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,s.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:s,name:r,workspacePath:o}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:s,name:r,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:o,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(h.id,n),drizzleOrm.isNull(h.workspace_path))).run();}registerWorkspace(t){let e=ut(t),n=this.openHandle(true);try{let s=Bt(e),r=$.basename(e),o=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:o,name:r,workspacePath:e}),{id:s,slug:o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to register workspace",s)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?drizzleOrm.eq(h.is_active,t.isActive?1:0):void 0,s=e.db.select({count:drizzleOrm.sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(drizzleOrm.desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(s=>s.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 s=n.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(drizzleOrm.sql`SELECT t.*,
4
4
  (SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
5
5
  FROM threads t
6
6
  WHERE t.workspace_id = ${t}
7
7
  ORDER BY t.updated_at DESC
8
- LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?drizzleOrm.and(drizzleOrm.eq(h.slug,t),drizzleOrm.ne(h.id,e)):drizzleOrm.eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.insert(h).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(h).where(drizzleOrm.eq(h.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(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.is_active,1),drizzleOrm.isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;Lt.existsSync(U.join(s,"crewx.yaml"))||Lt.existsSync(U.join(s,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(drizzleOrm.eq(h.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Ht=[h,i,c,H,v,P,G];function Re(){return U__namespace.default.join(Kt__default.default.homedir(),".crewx","crewx.db")}function Ee(a){if(!Lt__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Lt__default.default.copyFileSync(a,e),e}function Ft(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 xe(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 De(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=xe(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Se(a,t){let e=t?.dbPath??Re(),n=t?.force??false,r=t?.dryRun??false,s=r?null:Ee(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Ft(a);if(!r)try{X(a);}catch(m){let b=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!b.includes("duplicate column"))throw m}let l,u;r?(l=Ht.map(b=>sqliteCore.getTableConfig(b).name).filter(b=>!o.has(b)),u=o):(u=Ft(a),l=[...u].filter(m=>!o.has(m)));let p=[],f=[];for(let m of Ht){let b=sqliteCore.getTableConfig(m),D=b.name;if(!u.has(D))continue;let B=a.all(`PRAGMA table_info("${D}")`),L=new Set(B.map(N=>N.name)),J=new Set(b.columns.map(N=>N.name));for(let N of b.columns)if(!L.has(N.name)){if(!r){let lt=De(N);a.run(`ALTER TABLE "${D}" ADD COLUMN ${lt}`);}p.push({table:D,column:N.name});}for(let N of B)J.has(N.name)||f.push(`${D}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:f,backupPath:s}}var gt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(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{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new d("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?drizzleOrm.and(drizzleOrm.eq(h.slug,t),drizzleOrm.ne(h.id,e)):drizzleOrm.eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(h).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(h).where(drizzleOrm.eq(h.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{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.is_active,1),drizzleOrm.isNotNull(h.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;Lt.existsSync($.join(r,"crewx.yaml"))||Lt.existsSync($.join(r,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(drizzleOrm.eq(h.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Ft=[h,i,c,F,v,P,G];function Re(){return $__namespace.default.join(Kt__default.default.homedir(),".crewx","crewx.db")}function Ee(a){if(!Lt__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Lt__default.default.copyFileSync(a,e),e}function Ht(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 xe(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 De(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=xe(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Se(a,t){let e=t?.dbPath??Re(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Ee(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Ht(a);if(!s)try{X(a);}catch(m){let b=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!b.includes("duplicate column"))throw m}let l,u;s?(l=Ft.map(b=>sqliteCore.getTableConfig(b).name).filter(b=>!o.has(b)),u=o):(u=Ht(a),l=[...u].filter(m=>!o.has(m)));let p=[],f=[];for(let m of Ft){let b=sqliteCore.getTableConfig(m),D=b.name;if(!u.has(D))continue;let B=a.all(`PRAGMA table_info("${D}")`),L=new Set(B.map(N=>N.name)),J=new Set(b.columns.map(N=>N.name));for(let N of b.columns)if(!L.has(N.name)){if(!s){let lt=De(N);a.run(`ALTER TABLE "${D}" ADD COLUMN ${lt}`);}p.push({table:D,column:N.name});}for(let N of B)J.has(N.name)||f.push(`${D}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:f,backupPath:r}}var gt=class extends R{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 s=$.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}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{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
- model=COALESCE(?, model) WHERE id=?`,[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]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let s=r.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=s?.logs?JSON.parse(s.logs):[];o.push(e),r.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(drizzleOrm.desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=0;for(let r of e){let s=!1;if(r.pid)try{process.kill(r.pid,0),s=!0;}catch{}s||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,r.id),drizzleOrm.eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Lt.existsSync(r))continue;let s=w(r);try{let o=e?drizzleOrm.eq(i.workspace_id,e):void 0,l=o?drizzleOrm.and(drizzleOrm.eq(i.id,t),o):drizzleOrm.eq(i.id,t),u=s.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let p=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),f=o?drizzleOrm.and(p,o):p;u=s.db.select().from(i).where(f).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=e?drizzleOrm.and(drizzleOrm.eq(i.parent_task_id,t),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.eq(i.parent_task_id,t),p=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.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 child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
10
+ model=COALESCE(?, model) WHERE id=?`,[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]);}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(s=>{let r=s.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(drizzleOrm.desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=0;for(let s of e){let r=!1;if(s.pid)try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,s.id),drizzleOrm.eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Lt.existsSync(s))continue;let r=w(s);try{let o=e?drizzleOrm.eq(i.workspace_id,e):void 0,l=o?drizzleOrm.and(drizzleOrm.eq(i.id,t),o):drizzleOrm.eq(i.id,t),u=r.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let p=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),f=o?drizzleOrm.and(p,o):p;u=r.db.select().from(i).where(f).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=e?drizzleOrm.and(drizzleOrm.eq(i.parent_task_id,t),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.eq(i.parent_task_id,t),p=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let f of p)s.has(f.id)||(s.add(f.id),r.push(f));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
11
11
  SELECT
12
12
  COALESCE(workspace_id, 'unknown') AS workspace_id,
13
13
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -28,7 +28,7 @@ ${n.join(`
28
28
  FROM tasks
29
29
  GROUP BY workspace_id
30
30
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
31
- `)}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(!Lt.existsSync(u))continue;let p=w(u);try{let f=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),m=e?drizzleOrm.and(f,drizzleOrm.eq(i.workspace_id,e)):f,b=p.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 D of b)r.has(D.id)||(r.add(D.id),s+=D.input_tokens??0,o+=D.output_tokens??0,l+=D.cost_usd??0);}catch(f){throw new d("DB_ERROR","Failed to get thread token usage",f)}finally{p.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(!Lt.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),p=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,f=l.db.select().from(i).where(p).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of f)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(drizzleOrm.eq(i.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(drizzleOrm.inArray(i.agent_id,r));let s=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;s&&n.push(drizzleOrm.inArray(i.status,s));let o=t.q??t.search;o&&n.push(drizzleOrm.like(i.prompt,`%${o}%`)),t.from&&n.push(drizzleOrm.gte(i.started_at,t.from)),t.to&&n.push(drizzleOrm.lt(i.started_at,t.to));let l=n.length>0?drizzleOrm.and(...n):void 0,u=e.db.select({count:drizzleOrm.sql`count(*)`}).from(i).where(l).get(),p=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(p).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?drizzleOrm.sql`
31
+ `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),s=new Set,r=0,o=0,l=0;for(let u of n){if(!Lt.existsSync(u))continue;let p=w(u);try{let f=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),m=e?drizzleOrm.and(f,drizzleOrm.eq(i.workspace_id,e)):f,b=p.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 D of b)s.has(D.id)||(s.add(D.id),r+=D.input_tokens??0,o+=D.output_tokens??0,l+=D.cost_usd??0);}catch(f){throw new d("DB_ERROR","Failed to get thread token usage",f)}finally{p.close();}}return {inputTokens:r,outputTokens:o,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),p=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,f=l.db.select().from(i).where(p).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of f)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(drizzleOrm.eq(i.workspace_id,t.workspaceId));let s=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;s&&n.push(drizzleOrm.inArray(i.agent_id,s));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&n.push(drizzleOrm.inArray(i.status,r));let o=t.q??t.search;o&&n.push(drizzleOrm.like(i.prompt,`%${o}%`)),t.from&&n.push(drizzleOrm.gte(i.started_at,t.from)),t.to&&n.push(drizzleOrm.lt(i.started_at,t.to));let l=n.length>0?drizzleOrm.and(...n):void 0,u=e.db.select({count:drizzleOrm.sql`count(*)`}).from(i).where(l).get(),p=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at);return {rows:e.db.select().from(i).where(l).orderBy(p).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 s=this.openHandle(false);try{return s.db.all(n?drizzleOrm.sql`
32
32
  SELECT
33
33
  t.agent_id,
34
34
  t.workspace_id,
@@ -59,7 +59,7 @@ ${n.join(`
59
59
  AND t.started_at < ${e}
60
60
  GROUP BY t.agent_id, t.workspace_id
61
61
  ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
62
- `).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}))}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?drizzleOrm.sql`
62
+ `).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}))}catch(r){throw new d("DB_ERROR","Failed to get agent usage",r)}finally{s.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?drizzleOrm.sql`
63
63
  SELECT
64
64
  date(t.started_at) AS date,
65
65
  t.agent_id,
@@ -88,18 +88,18 @@ ${n.join(`
88
88
  AND t.started_at < ${e}
89
89
  GROUP BY date(t.started_at), t.agent_id
90
90
  ORDER BY date(t.started_at) ASC
91
- `).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}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString(),o=n?drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"),drizzleOrm.eq(i.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"));r.db.update(i).set({status:"failed",error:e,completed_at:s}).where(o).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=e?drizzleOrm.and(drizzleOrm.like(i.prompt,`%${t}%`),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.like(i.prompt,`%${t}%`),p=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.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 prompt hint",u)}finally{l.close();}}return s}};var bt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let s of e){if(!Lt.existsSync(s))continue;let o=w(s);try{let l=t?drizzleOrm.eq(c.workspace_id,t):void 0,u=o.db.select().from(c).where(l).orderBy(drizzleOrm.desc(c.updated_at)).all();for(let p of u)n.has(p.id)||(n.add(p.id),r.push(p));}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(!Lt.existsSync(r))continue;let s=w(r);try{let o=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(c.workspace_id,e)):o,u=s.db.select().from(c).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(!Lt.existsSync(r))continue;let s=w(r);try{let o=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(c.workspace_id,e)):o;if(s.db.select({id:c.id}).from(c).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,p=new Set;for(let f of n){if(!Lt.existsSync(f))continue;let m=w(f);try{let b=drizzleOrm.and(drizzleOrm.eq(i.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(i.parent_task_id),drizzleOrm.eq(i.parent_task_id,""))),D=e?drizzleOrm.and(b,drizzleOrm.eq(i.workspace_id,e)):b,B=m.db.select({cnt:drizzleOrm.sql`count(*)`,total_input:drizzleOrm.sql`COALESCE(SUM(input_tokens), 0)`,total_output:drizzleOrm.sql`COALESCE(SUM(output_tokens), 0)`,total_cached:drizzleOrm.sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:drizzleOrm.sql`COALESCE(SUM(cost_usd), 0)`}).from(i).where(D).get();B&&(r+=B.cnt,s+=B.total_input,o+=B.total_output,l+=B.total_cached,u+=B.total_cost);let L=m.db.all(drizzleOrm.sql`
91
+ `).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}))}catch(r){throw new d("DB_ERROR","Failed to get agent usage trend",r)}finally{s.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new d("DB_ERROR","Failed to find task for stop",s)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString(),o=n?drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"),drizzleOrm.eq(i.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"));s.db.update(i).set({status:"failed",error:e,completed_at:r}).where(o).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to mark task failed",r)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=e?drizzleOrm.and(drizzleOrm.like(i.prompt,`%${t}%`),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.like(i.prompt,`%${t}%`),p=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let f of p)s.has(f.id)||(s.add(f.id),r.push(f));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return r}};var bt=class extends R{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 s=$.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!Lt.existsSync(r))continue;let o=w(r);try{let l=t?drizzleOrm.eq(c.workspace_id,t):void 0,u=o.db.select().from(c).where(l).orderBy(drizzleOrm.desc(c.updated_at)).all();for(let p of u)n.has(p.id)||(n.add(p.id),s.push(p));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{o.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Lt.existsSync(s))continue;let r=w(s);try{let o=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(c.workspace_id,e)):o,u=r.db.select().from(c).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{r.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Lt.existsSync(s))continue;let r=w(s);try{let o=drizzleOrm.eq(c.id,t),l=e?drizzleOrm.and(o,drizzleOrm.eq(c.workspace_id,e)):o;if(r.db.select({id:c.id}).from(c).where(l).limit(1).get())return !0}catch(o){throw new d("DB_ERROR","Failed to check thread existence",o)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,o=0,l=0,u=0,p=new Set;for(let f of n){if(!Lt.existsSync(f))continue;let m=w(f);try{let b=drizzleOrm.and(drizzleOrm.eq(i.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(i.parent_task_id),drizzleOrm.eq(i.parent_task_id,""))),D=e?drizzleOrm.and(b,drizzleOrm.eq(i.workspace_id,e)):b,B=m.db.select({cnt:drizzleOrm.sql`count(*)`,total_input:drizzleOrm.sql`COALESCE(SUM(input_tokens), 0)`,total_output:drizzleOrm.sql`COALESCE(SUM(output_tokens), 0)`,total_cached:drizzleOrm.sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:drizzleOrm.sql`COALESCE(SUM(cost_usd), 0)`}).from(i).where(D).get();B&&(s+=B.cnt,r+=B.total_input,o+=B.total_output,l+=B.total_cached,u+=B.total_cost);let L=m.db.all(drizzleOrm.sql`
92
92
  SELECT DISTINCT agent_id FROM tasks
93
93
  WHERE thread_id = ${t}
94
94
  AND agent_id IS NOT NULL AND agent_id != ''
95
95
  AND (parent_task_id IS NULL OR parent_task_id = '')
96
96
  ${e?drizzleOrm.sql`AND workspace_id = ${e}`:drizzleOrm.sql``}
97
- `);for(let J of L)p.add(J.agent_id);}catch(b){throw new d("DB_ERROR","Failed to aggregate task stats",b)}finally{m.close();}}return {taskCount:r,inputTokens:s,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.and(drizzleOrm.eq(i.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(i.parent_task_id),drizzleOrm.eq(i.parent_task_id,""))),p=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,f=l.db.select().from(i).where(p).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of f)r.has(m.id)||(r.add(m.id),s.push(m));}catch(u){throw new d("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return s}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.eq(i.thread_id,t),p=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,f=l.db.select().from(i).where(p).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of f)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(!Lt.existsSync(s))continue;let o=w(s);try{let l=drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.thread_id,t)),u=n?drizzleOrm.and(l,drizzleOrm.eq(i.workspace_id,n)):l,p=o.db.select().from(i).where(u).limit(1).get();if(!p)continue;let f=o.db.select().from(i).where(drizzleOrm.eq(i.parent_task_id,p.id)).orderBy(drizzleOrm.asc(i.started_at)).all();return {task:p,children:f}}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(!Lt.existsSync(s))continue;let o=w(s);try{let l=drizzleOrm.and(drizzleOrm.inArray(i.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(i.parent_task_id),drizzleOrm.eq(i.parent_task_id,""))),u=e?drizzleOrm.and(l,drizzleOrm.eq(i.workspace_id,e)):l,p=o.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let f of p){let m=f.thread_id;n.has(m)||n.set(m,[]),n.get(m).push(f);}}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=drizzleOrm.eq(c.id,t),o=n?drizzleOrm.and(s,drizzleOrm.eq(c.workspace_id,n)):s;if(!r.db.select({id:c.id}).from(c).where(o).limit(1).get())return;r.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(c.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:c.id,message_count:c.message_count}).from(c).where(drizzleOrm.eq(c.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(c).set(l).where(drizzleOrm.eq(c.id,t)).run();}else n.db.insert(c).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:c.id,platform:c.platform,workspace_id:c.workspace_id}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get();if(o){s&&!o.workspace_id&&r.db.update(c).set({workspace_id:s}).where(drizzleOrm.eq(c.id,t)).run();return}let l=new Date().toISOString();r.db.insert(c).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;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.run(drizzleOrm.sql`
98
- UPDATE threads
99
- SET first_message = COALESCE(first_message, ${e}),
100
- title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
101
- last_message = ${e},
102
- message_count = message_count + 1,
103
- updated_at = ${s}
104
- WHERE id = ${t}
105
- `);}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(c).set({last_message:e,updated_at:s}).where(drizzleOrm.eq(c.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(c).set(r).where(drizzleOrm.eq(c.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),s=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(r).get();if(!s)return null;let o=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(o){let u=e?drizzleOrm.and(drizzleOrm.eq(c.pinned,1),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.pinned,1),p=n.db.select({metadata:c.metadata}).from(c).where(u).all(),f=0;for(let m of p){let b=m.metadata?JSON.parse(m.metadata):{};typeof b.pinOrder=="number"&&b.pinOrder>f&&(f=b.pinOrder);}l.pinOrder=f+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let s=e?drizzleOrm.and(drizzleOrm.eq(c.id,t[r]),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t[r]),o=n.db.select({metadata:c.metadata}).from(c).where(s).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=r+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),s=n.db.select({starred:c.starred}).from(c).where(r).get();if(!s)return null;let o=s.starred?0:1;return n.db.update(c).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 yt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(H).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(H).where(drizzleOrm.eq(H.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(H).where(drizzleOrm.eq(H.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 Rt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(v).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(v).where(drizzleOrm.eq(v.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:v.tool_name,count:drizzleOrm.sql`count(*)`}).from(v).where(drizzleOrm.eq(v.task_id,t)).groupBy(v.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 Et=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:c.id}).from(c).where(drizzleOrm.eq(c.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(P).where(drizzleOrm.eq(P.thread_id,t)).orderBy(drizzleOrm.asc(P.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(P).where(drizzleOrm.and(drizzleOrm.eq(P.id,e),drizzleOrm.eq(P.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(P).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(P).where(drizzleOrm.eq(P.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var xt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=U.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=U.dirname(e);Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(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(G).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(G).orderBy(drizzleOrm.desc(G.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};exports.BaseSqliteRepository=R;exports.RepositoryError=d;exports.RequestLogRepository=xt;exports.SpanRepository=yt;exports.TaskRepository=gt;exports.ThreadBoxRepository=Et;exports.ThreadRepository=bt;exports.ToolCallRepository=Rt;exports.WorkspaceRepository=ft;exports.openDrizzleDb=w;exports.pushSchema=Se;exports.runMigrations=X;exports.runMigrationsOnce=T;
97
+ `);for(let J of L)p.add(J.agent_id);}catch(b){throw new d("DB_ERROR","Failed to aggregate task stats",b)}finally{m.close();}}return {taskCount:s,inputTokens:r,outputTokens:o,cachedInputTokens:l,costUsd:u,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.and(drizzleOrm.eq(i.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(i.parent_task_id),drizzleOrm.eq(i.parent_task_id,""))),p=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,f=l.db.select().from(i).where(p).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of f)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new d("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}return r}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=drizzleOrm.eq(i.thread_id,t),p=e?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,e)):u,f=l.db.select().from(i).where(p).orderBy(drizzleOrm.asc(i.started_at)).all();for(let m of f)s.has(m.id)||(s.add(m.id),r.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return r}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let r of s){if(!Lt.existsSync(r))continue;let o=w(r);try{let l=drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.thread_id,t)),u=n?drizzleOrm.and(l,drizzleOrm.eq(i.workspace_id,n)):l,p=o.db.select().from(i).where(u).limit(1).get();if(!p)continue;let f=o.db.select().from(i).where(drizzleOrm.eq(i.parent_task_id,p.id)).orderBy(drizzleOrm.asc(i.started_at)).all();return {task:p,children:f}}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 s=this.resolveDbPaths();for(let r of s){if(!Lt.existsSync(r))continue;let o=w(r);try{let l=drizzleOrm.and(drizzleOrm.inArray(i.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(i.parent_task_id),drizzleOrm.eq(i.parent_task_id,""))),u=e?drizzleOrm.and(l,drizzleOrm.eq(i.workspace_id,e)):l,p=o.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let f of p){let m=f.thread_id;n.has(m)||n.set(m,[]),n.get(m).push(f);}}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 s=this.openHandle(true);try{let r=drizzleOrm.eq(c.id,t),o=n?drizzleOrm.and(r,drizzleOrm.eq(c.workspace_id,n)):r;if(!s.db.select({id:c.id}).from(c).where(o).limit(1).get())return;s.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(c.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread title",r)}finally{s.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let s=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,r=new Date().toISOString();if(n.db.select({id:c.id,message_count:c.message_count}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get()){let l={updated_at:r};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(c).set(l).where(drizzleOrm.eq(c.id,t)).run();}else n.db.insert(c).values({id:t,platform:e.platform,workspace_id:s,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to upsert thread",s)}finally{n.close();}}ensureThread(t,e,n){let s=this.openHandle(true);try{let r=n?this.validateWorkspaceId(s,n):null,o=s.db.select({id:c.id,platform:c.platform,workspace_id:c.workspace_id}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get();if(o){r&&!o.workspace_id&&s.db.update(c).set({workspace_id:r}).where(drizzleOrm.eq(c.id,t)).run();return}let l=new Date().toISOString();s.db.insert(c).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to ensure thread",r)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let s=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:s.db.transaction(l=>{let p=l.select({message_count:c.message_count}).from(c).where(drizzleOrm.eq(c.id,t)).limit(1).get()?.message_count===0;return l.run(drizzleOrm.sql`
98
+ UPDATE threads
99
+ SET first_message = COALESCE(first_message, ${e}),
100
+ title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
101
+ last_message = ${e},
102
+ message_count = message_count + 1,
103
+ updated_at = ${r}
104
+ WHERE id = ${t}
105
+ `),p},{behavior:"immediate"})}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save user message",r)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.update(c).set({last_message:e,updated_at:r}).where(drizzleOrm.eq(c.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save assistant message",r)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(c).set(s).where(drizzleOrm.eq(c.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread",s)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let s=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),r=n.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(s).get();if(!r)return null;let o=r.pinned?0:1,l=r.metadata?JSON.parse(r.metadata):{};if(o){let u=e?drizzleOrm.and(drizzleOrm.eq(c.pinned,1),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.pinned,1),p=n.db.select({metadata:c.metadata}).from(c).where(u).all(),f=0;for(let m of p){let b=m.metadata?JSON.parse(m.metadata):{};typeof b.pinOrder=="number"&&b.pinOrder>f&&(f=b.pinOrder);}l.pinOrder=f+1;}else delete l.pinOrder;return n.db.update(c).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(s).run(),{pinned:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle pin",s)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let s=0;s<t.length;s++){let r=e?drizzleOrm.and(drizzleOrm.eq(c.id,t[s]),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t[s]),o=n.db.select({metadata:c.metadata}).from(c).where(r).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=s+1,n.db.update(c).set({metadata:JSON.stringify(l)}).where(r).run();}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to reorder pins",s)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let s=e?drizzleOrm.and(drizzleOrm.eq(c.id,t),drizzleOrm.eq(c.workspace_id,e)):drizzleOrm.eq(c.id,t),r=n.db.select({starred:c.starred}).from(c).where(s).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(c).set({starred:o}).where(s).run(),{starred:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}};var yt=class extends R{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 s=$.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(F).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(F).where(drizzleOrm.eq(F.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(F).where(drizzleOrm.eq(F.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 Rt=class extends R{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 s=$.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(v).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(v).where(drizzleOrm.eq(v.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:v.tool_name,count:drizzleOrm.sql`count(*)`}).from(v).where(drizzleOrm.eq(v.task_id,t)).groupBy(v.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 Et=class extends R{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 s=$.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:c.id}).from(c).where(drizzleOrm.eq(c.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(P).where(drizzleOrm.eq(P.thread_id,t)).orderBy(drizzleOrm.asc(P.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(P).where(drizzleOrm.and(drizzleOrm.eq(P.id,e),drizzleOrm.eq(P.thread_id,t))).limit(1).get()??void 0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(P).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(P).where(drizzleOrm.eq(P.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var xt=class extends R{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 s=$.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let r of t)s.insert(G).values({id:crypto.randomUUID(),path:r.path,method:r.method,status_code:r.statusCode,duration_ms:r.durationMs,ip:r.ip??null,request_headers:r.requestHeaders??null,response_headers:r.responseHeaders??null,request_body:r.requestBody??null,response_body:r.responseBody??null,query:r.query??null,user_id:r.userId??null,project_id:r.projectId??null,partition_key:r.partitionKey??"default",timestamp:n,metadata:r.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(G).orderBy(drizzleOrm.desc(G.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};exports.BaseSqliteRepository=R;exports.RepositoryError=d;exports.RequestLogRepository=xt;exports.SpanRepository=yt;exports.TaskRepository=gt;exports.ThreadBoxRepository=Et;exports.ThreadRepository=bt;exports.ToolCallRepository=Rt;exports.WorkspaceRepository=ft;exports.openDrizzleDb=w;exports.pushSchema=Se;exports.runMigrations=X;exports.runMigrationsOnce=T;
@@ -41,7 +41,9 @@ export declare class ThreadRepository extends BaseSqliteRepository {
41
41
  saveUserMessage(threadId: string, text: string, opts?: {
42
42
  platform?: string;
43
43
  model?: string;
44
- }): void;
44
+ }): {
45
+ firstMessage: boolean;
46
+ };
45
47
  saveAssistantMessage(threadId: string, text: string, opts?: {
46
48
  platform?: string;
47
49
  model?: string;
@@ -0,0 +1,197 @@
1
+ export declare const chromexAuditLog: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
2
+ name: "chromex_audit_log";
3
+ schema: undefined;
4
+ columns: {
5
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
6
+ name: "id";
7
+ tableName: "chromex_audit_log";
8
+ dataType: "number";
9
+ columnType: "SQLiteInteger";
10
+ data: number;
11
+ driverParam: number;
12
+ notNull: true;
13
+ hasDefault: true;
14
+ isPrimaryKey: true;
15
+ isAutoincrement: false;
16
+ hasRuntimeDefault: false;
17
+ enumValues: undefined;
18
+ baseColumn: never;
19
+ identity: undefined;
20
+ generated: undefined;
21
+ }, {}, {}>;
22
+ timestamp: import("drizzle-orm/sqlite-core").SQLiteColumn<{
23
+ name: "timestamp";
24
+ tableName: "chromex_audit_log";
25
+ dataType: "string";
26
+ columnType: "SQLiteText";
27
+ data: string;
28
+ driverParam: string;
29
+ notNull: true;
30
+ hasDefault: true;
31
+ isPrimaryKey: false;
32
+ isAutoincrement: false;
33
+ hasRuntimeDefault: false;
34
+ enumValues: [string, ...string[]];
35
+ baseColumn: never;
36
+ identity: undefined;
37
+ generated: undefined;
38
+ }, {}, {
39
+ length: number | undefined;
40
+ }>;
41
+ agent_id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
42
+ name: "agent_id";
43
+ tableName: "chromex_audit_log";
44
+ dataType: "string";
45
+ columnType: "SQLiteText";
46
+ data: string;
47
+ driverParam: string;
48
+ notNull: true;
49
+ hasDefault: false;
50
+ isPrimaryKey: false;
51
+ isAutoincrement: false;
52
+ hasRuntimeDefault: false;
53
+ enumValues: [string, ...string[]];
54
+ baseColumn: never;
55
+ identity: undefined;
56
+ generated: undefined;
57
+ }, {}, {
58
+ length: number | undefined;
59
+ }>;
60
+ action: import("drizzle-orm/sqlite-core").SQLiteColumn<{
61
+ name: "action";
62
+ tableName: "chromex_audit_log";
63
+ dataType: "string";
64
+ columnType: "SQLiteText";
65
+ data: string;
66
+ driverParam: string;
67
+ notNull: true;
68
+ hasDefault: false;
69
+ isPrimaryKey: false;
70
+ isAutoincrement: false;
71
+ hasRuntimeDefault: false;
72
+ enumValues: [string, ...string[]];
73
+ baseColumn: never;
74
+ identity: undefined;
75
+ generated: undefined;
76
+ }, {}, {
77
+ length: number | undefined;
78
+ }>;
79
+ jti: import("drizzle-orm/sqlite-core").SQLiteColumn<{
80
+ name: "jti";
81
+ tableName: "chromex_audit_log";
82
+ dataType: "string";
83
+ columnType: "SQLiteText";
84
+ data: string;
85
+ driverParam: string;
86
+ notNull: false;
87
+ hasDefault: false;
88
+ isPrimaryKey: false;
89
+ isAutoincrement: false;
90
+ hasRuntimeDefault: false;
91
+ enumValues: [string, ...string[]];
92
+ baseColumn: never;
93
+ identity: undefined;
94
+ generated: undefined;
95
+ }, {}, {
96
+ length: number | undefined;
97
+ }>;
98
+ scope: import("drizzle-orm/sqlite-core").SQLiteColumn<{
99
+ name: "scope";
100
+ tableName: "chromex_audit_log";
101
+ dataType: "string";
102
+ columnType: "SQLiteText";
103
+ data: string;
104
+ driverParam: string;
105
+ notNull: false;
106
+ hasDefault: false;
107
+ isPrimaryKey: false;
108
+ isAutoincrement: false;
109
+ hasRuntimeDefault: false;
110
+ enumValues: [string, ...string[]];
111
+ baseColumn: never;
112
+ identity: undefined;
113
+ generated: undefined;
114
+ }, {}, {
115
+ length: number | undefined;
116
+ }>;
117
+ tab_url: import("drizzle-orm/sqlite-core").SQLiteColumn<{
118
+ name: "tab_url";
119
+ tableName: "chromex_audit_log";
120
+ dataType: "string";
121
+ columnType: "SQLiteText";
122
+ data: string;
123
+ driverParam: string;
124
+ notNull: false;
125
+ hasDefault: false;
126
+ isPrimaryKey: false;
127
+ isAutoincrement: false;
128
+ hasRuntimeDefault: false;
129
+ enumValues: [string, ...string[]];
130
+ baseColumn: never;
131
+ identity: undefined;
132
+ generated: undefined;
133
+ }, {}, {
134
+ length: number | undefined;
135
+ }>;
136
+ tool_name: import("drizzle-orm/sqlite-core").SQLiteColumn<{
137
+ name: "tool_name";
138
+ tableName: "chromex_audit_log";
139
+ dataType: "string";
140
+ columnType: "SQLiteText";
141
+ data: string;
142
+ driverParam: string;
143
+ notNull: false;
144
+ hasDefault: false;
145
+ isPrimaryKey: false;
146
+ isAutoincrement: false;
147
+ hasRuntimeDefault: false;
148
+ enumValues: [string, ...string[]];
149
+ baseColumn: never;
150
+ identity: undefined;
151
+ generated: undefined;
152
+ }, {}, {
153
+ length: number | undefined;
154
+ }>;
155
+ result: import("drizzle-orm/sqlite-core").SQLiteColumn<{
156
+ name: "result";
157
+ tableName: "chromex_audit_log";
158
+ dataType: "string";
159
+ columnType: "SQLiteText";
160
+ data: string;
161
+ driverParam: string;
162
+ notNull: false;
163
+ hasDefault: false;
164
+ isPrimaryKey: false;
165
+ isAutoincrement: false;
166
+ hasRuntimeDefault: false;
167
+ enumValues: [string, ...string[]];
168
+ baseColumn: never;
169
+ identity: undefined;
170
+ generated: undefined;
171
+ }, {}, {
172
+ length: number | undefined;
173
+ }>;
174
+ detail: import("drizzle-orm/sqlite-core").SQLiteColumn<{
175
+ name: "detail";
176
+ tableName: "chromex_audit_log";
177
+ dataType: "string";
178
+ columnType: "SQLiteText";
179
+ data: string;
180
+ driverParam: string;
181
+ notNull: false;
182
+ hasDefault: false;
183
+ isPrimaryKey: false;
184
+ isAutoincrement: false;
185
+ hasRuntimeDefault: false;
186
+ enumValues: [string, ...string[]];
187
+ baseColumn: never;
188
+ identity: undefined;
189
+ generated: undefined;
190
+ }, {}, {
191
+ length: number | undefined;
192
+ }>;
193
+ };
194
+ dialect: "sqlite";
195
+ }>;
196
+ export type ChromexAuditLog = typeof chromexAuditLog.$inferSelect;
197
+ export type NewChromexAuditLog = typeof chromexAuditLog.$inferInsert;
@@ -1275,6 +1275,11 @@ export declare const CrewxProjectConfigSchema: z.ZodObject<{
1275
1275
  documents: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1276
1276
  }, z.ZodUnknown, "strip">>;
1277
1277
  export type CrewxProjectConfig = z.infer<typeof CrewxProjectConfigSchema>;
1278
+ export interface TraceContext {
1279
+ parentTaskId: string | null;
1280
+ rootTraceId: string;
1281
+ callerAgentId: string | null;
1282
+ }
1278
1283
  export interface CrewxOptions {
1279
1284
  workspaceRoot?: string;
1280
1285
  platform?: Platform;
@@ -1296,14 +1301,12 @@ export interface QueryOptions {
1296
1301
  context?: string;
1297
1302
  metadata?: Record<string, unknown>;
1298
1303
  threadId?: string;
1304
+ taskId?: string;
1299
1305
  platform?: Platform;
1300
1306
  messages?: import('../conversation/types').TemplateMessage[];
1301
1307
  vars?: Record<string, unknown>;
1302
1308
  cwd?: string;
1303
- images?: Array<{
1304
- filePath: string;
1305
- mimeType: string;
1306
- }>;
1309
+ trace?: TraceContext;
1307
1310
  }
1308
1311
  export interface QueryResult {
1309
1312
  ok: boolean;
@@ -1334,14 +1337,12 @@ export interface ExecuteOptions {
1334
1337
  context?: string;
1335
1338
  metadata?: Record<string, unknown>;
1336
1339
  threadId?: string;
1340
+ taskId?: string;
1337
1341
  platform?: Platform;
1338
1342
  messages?: import('../conversation/types').TemplateMessage[];
1339
1343
  vars?: Record<string, unknown>;
1340
1344
  cwd?: string;
1341
- images?: Array<{
1342
- filePath: string;
1343
- mimeType: string;
1344
- }>;
1345
+ trace?: TraceContext;
1345
1346
  }
1346
1347
  export interface ExecuteResult {
1347
1348
  ok: boolean;
@@ -1355,5 +1356,6 @@ export interface ExecuteResult {
1355
1356
  provider: string;
1356
1357
  model?: string;
1357
1358
  durationMs: number;
1359
+ taskId?: string;
1358
1360
  };
1359
1361
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewx/sdk",
3
- "version": "0.8.8-rc.3",
3
+ "version": "0.8.8-rc.30",
4
4
  "license": "UNLICENSED",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"
@@ -83,7 +83,7 @@
83
83
  "@ai-sdk/anthropic": "1.0.8",
84
84
  "@ai-sdk/google": "1.0.10",
85
85
  "@ai-sdk/openai": "1.0.11",
86
- "better-sqlite3": "12.0.0"
86
+ "better-sqlite3": ">=12.0.0"
87
87
  },
88
88
  "peerDependenciesMeta": {
89
89
  "@agentclientprotocol/claude-agent-acp": {
@@ -83,16 +83,22 @@ layouts:
83
83
 
84
84
  {{#if agent.optionsByMode.query}}
85
85
  <cli_options mode="query">
86
- {{#each agent.optionsByMode.query}}
87
- <item>{{#if @key}}provider="{{@key}}" {{/if}}{{{this}}}</item>
86
+ {{#each agent.optionsByMode.query.named}}
87
+ <item>provider="{{@key}}" {{{this}}}</item>
88
+ {{/each}}
89
+ {{#each agent.optionsByMode.query.rawArgs}}
90
+ <item>{{{this}}}</item>
88
91
  {{/each}}
89
92
  </cli_options>
90
93
  {{/if}}
91
94
 
92
95
  {{#if agent.optionsByMode.execute}}
93
96
  <cli_options mode="execute">
94
- {{#each agent.optionsByMode.execute}}
95
- <item>{{#if @key}}provider="{{@key}}" {{/if}}{{{this}}}</item>
97
+ {{#each agent.optionsByMode.execute.named}}
98
+ <item>provider="{{@key}}" {{{this}}}</item>
99
+ {{/each}}
100
+ {{#each agent.optionsByMode.execute.rawArgs}}
101
+ <item>{{{this}}}</item>
96
102
  {{/each}}
97
103
  </cli_options>
98
104
  {{/if}}