@crewx/sdk 0.8.6-rc.6 → 0.8.6-rc.8

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,4 +1,4 @@
1
- 'use strict';var fs=require('fs'),tt=require('path'),At=require('os'),crypto=require('crypto'),drizzleOrm=require('drizzle-orm'),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 tt__namespace=/*#__PURE__*/_interopNamespace(tt);var At__default=/*#__PURE__*/_interopDefault(At);var H=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var A=class{detach(t){}};function at(d){let t=e=>String(e).padStart(2,"0");return `${d.getFullYear()}${t(d.getMonth()+1)}${t(d.getDate())}T${t(d.getHours())}${t(d.getMinutes())}${t(d.getSeconds())}`}var Z=class extends A{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=tt.join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{fs.existsSync(this.logsDir)||fs.mkdirSync(this.logsDir,{recursive:!0});let s=at(e.timestamp),n=tt.join(this.logsDir,`${s}_${e.traceId}.log`);this.logFiles.set(e.traceId,n);let r=`=== TASK LOG: ${e.traceId} ===
1
+ 'use strict';var fs=require('fs'),H=require('path'),At=require('os'),crypto=require('crypto'),drizzleOrm=require('drizzle-orm'),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 H__namespace=/*#__PURE__*/_interopNamespace(H);var At__default=/*#__PURE__*/_interopDefault(At);var j=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var A=class{detach(t){}};function at(d){let t=e=>String(e).padStart(2,"0");return `${d.getFullYear()}${t(d.getMonth()+1)}${t(d.getDate())}T${t(d.getHours())}${t(d.getMinutes())}${t(d.getSeconds())}`}var tt=class extends A{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=H.join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{fs.existsSync(this.logsDir)||fs.mkdirSync(this.logsDir,{recursive:!0});let s=at(e.timestamp),n=H.join(this.logsDir,`${s}_${e.traceId}.log`);this.logFiles.set(e.traceId,n);let r=`=== TASK LOG: ${e.traceId} ===
2
2
  CrewX Version: ${this.version}
3
3
  Mode: ${e.mode}
4
4
  Agent: ${e.agentRef}
@@ -8,9 +8,9 @@ Message: ${e.message}
8
8
  `;fs.writeFileSync(n,r,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toISOString();fs.appendFileSync(s,`[${n}] STDOUT: ${e.output}
9
9
  `,"utf8");}catch{}}),t.on("task:end",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toLocaleString(),r=e.error?`failed: ${e.error.message}`:"completed successfully",i=`[${n}] INFO: Task ${r} in ${e.durationMs}ms
10
10
  [${n}] INFO: Process closed with exit code: ${e.error?1:0}
11
- `;fs.appendFileSync(s,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Tt(d){let t=tt__namespace.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function ut(d){let t=Tt(d);return crypto.createHash("sha256").update(t).digest("hex")}var F=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:tt.join(At__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 fs.existsSync(t??this.resolveDbPath())}};function w(d){let t=H("better-sqlite3"),{drizzle:e}=H("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),{db:e(s),runRaw:(n,r=[])=>s.prepare(n).run(...r),close:()=>s.close()}}var pt=new Set;function vt(d){let{migrate:t}=H("drizzle-orm/better-sqlite3/migrator"),{sql:e}=H("drizzle-orm"),s=[tt__namespace.default.join(__dirname,"../migrations"),tt__namespace.default.join(__dirname,"migrations")],n=s.find(p=>fs.existsSync(tt__namespace.default.join(p,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
11
+ `;fs.appendFileSync(s,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Tt(d){let t=H__namespace.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function ut(d){let t=Tt(d);return crypto.createHash("sha256").update(t).digest("hex")}var F=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:H.join(At__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 fs.existsSync(t??this.resolveDbPath())}};function w(d){let t=j("better-sqlite3"),{drizzle:e}=j("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),{db:e(s),runRaw:(n,r=[])=>s.prepare(n).run(...r),close:()=>s.close()}}var pt=new Set;function vt(d){let{migrate:t}=j("drizzle-orm/better-sqlite3/migrator"),{sql:e}=j("drizzle-orm"),s=[H__namespace.default.join(__dirname,"../migrations"),H__namespace.default.join(__dirname,"migrations"),H__namespace.default.join(__dirname,"../../../../drizzle/migrations"),H__namespace.default.join(process.cwd(),"drizzle/migrations")],n=s.find(p=>fs.existsSync(H__namespace.default.join(p,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
12
12
  ${s.join(`
13
- `)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),t(d,{migrationsFolder:n});let a=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(a>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${a} migration${a>1?"s":""} applied).`);}}function W(d,t){pt.has(t)||(vt(d),pt.add(t));}var c=class extends Error{code;cause;constructor(t,e,s){super(e),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var B=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 o=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"),workspace_name:sqliteCore.text("workspace_name"),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_name:sqliteCore.text("project_name"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(d.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var u=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>B.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)},d=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(d.workspace_id)}));var Ft=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Ft.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")},d=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.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()},d=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>u.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()},d=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(d.thread_id,d.seq)}));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")},d=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(d.partition_key)}));var X=class extends F{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=tt.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=tt.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new c("NOT_FOUND","Database not found");let s=w(e);if(t)try{W(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,workspace_name:t.workspaceName??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(s){throw s instanceof c?s:new c("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
13
+ `)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),t(d,{migrationsFolder:n});let a=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(a>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${a} migration${a>1?"s":""} applied).`);}}function W(d,t){pt.has(t)||(vt(d),pt.add(t));}var c=class extends Error{code;cause;constructor(t,e,s){super(e),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var B=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 o=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"),workspace_name:sqliteCore.text("workspace_name"),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_name:sqliteCore.text("project_name"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(d.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var u=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>B.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)},d=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(d.workspace_id)}));var Ft=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Ft.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")},d=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.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()},d=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>u.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()},d=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(d.thread_id,d.seq)}));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")},d=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(d.partition_key)}));var J=class extends F{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=H.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=H.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new c("NOT_FOUND","Database not found");let s=w(e);if(t)try{W(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,workspace_name:t.workspaceName??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(s){throw s instanceof c?s:new c("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
14
14
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
15
15
  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(s){throw s instanceof c?s:new c("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),n.update(o).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof c?n:new c("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.started_at)).all()}catch(e){throw new c("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(drizzleOrm.desc(o.started_at)).limit(100).all()}catch(e){throw new c("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new c("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to kill task",s)}finally{e.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=w(n);try{let i=e?drizzleOrm.eq(o.workspace_id,e):void 0,l=i?drizzleOrm.and(drizzleOrm.eq(o.id,t),i):drizzleOrm.eq(o.id,t),a=r.db.select().from(o).where(l).limit(1).get()??void 0;if(!a){let p=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),_=i?drizzleOrm.and(p,i):p;a=r.db.select().from(o).where(_).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??void 0;}if(a)return a}catch(i){throw new c("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!fs.existsSync(i))continue;let l=w(i);try{let a=e?drizzleOrm.and(drizzleOrm.eq(o.parent_task_id,t),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.eq(o.parent_task_id,t),p=l.db.select().from(o).where(a).orderBy(drizzleOrm.asc(o.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(a){throw new c("DB_ERROR","Failed to find child tasks",a)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
16
16
  SELECT
@@ -97,7 +97,7 @@ ${s.join(`
97
97
  AND t.started_at < ${e}
98
98
  GROUP BY date(t.started_at), t.agent_id
99
99
  ORDER BY date(t.started_at) ASC
100
- `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new c("DB_ERROR","Failed to get agent usage trend",r)}finally{n.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new c("DB_ERROR","Failed to find task for stop",n)}finally{s.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString(),i=s?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,s)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));n.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!fs.existsSync(i))continue;let l=w(i);try{let a=e?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.like(o.prompt,`%${t}%`),p=l.db.select().from(o).where(a).orderBy(drizzleOrm.asc(o.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(a){throw new c("DB_ERROR","Failed to find tasks by prompt hint",a)}finally{l.close();}}return r}};var ot=class extends A{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=tt.join(t?.dbRoot??At.homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new X({dbPath:this.dbPath}),s=process.cwd(),n=fs.existsSync(tt.join(s,"crewx.yaml"))||fs.existsSync(tt.join(s,"crewx.yml")),r=n?ut(s):null,i=n?tt.basename(s):null,l=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let p=process.env.CREWX_CALLER_AGENT_ID||null,_=process.env.CREWX_PARENT_TASK_ID||null,g=process.env.CREWX_TRACE_ID||a.traceId,D=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});e.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:l,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??r,workspaceName:a.workspaceName??i,callerAgentId:p,parentTaskId:_,traceId:g,metadata:D,threadId:a.threadId??null});}catch{}}),t.on("task:output",a=>{try{e.appendLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch{}}),t.on("task:end",a=>{try{e.finishTask({id:a.traceId,status:a.error?"failed":"success",result:a.result??null,error:a.error?JSON.stringify(a.error):null,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var V=class extends F{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=tt.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=tt.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new c("NOT_FOUND","Database not found");let s=w(e);if(t)try{W(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:B.id}).from(B).where(drizzleOrm.eq(B.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!fs.existsSync(r))continue;let i=w(r);try{let l=t?drizzleOrm.or(drizzleOrm.eq(u.workspace_id,t),drizzleOrm.isNull(u.workspace_id)):void 0,a=i.db.select().from(u).where(l).orderBy(drizzleOrm.desc(u.updated_at)).all();for(let p of a)s.has(p.id)||(s.add(p.id),n.push(p));}catch(l){throw new c("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=w(n);try{let i=drizzleOrm.eq(u.id,t),l=e?drizzleOrm.and(i,drizzleOrm.or(drizzleOrm.eq(u.workspace_id,e),drizzleOrm.isNull(u.workspace_id))):i,a=r.db.select().from(u).where(l).limit(1).get()??void 0;if(a)return a}catch(i){throw new c("DB_ERROR","Failed to find thread by id",i)}finally{r.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=w(n);try{let i=drizzleOrm.eq(u.id,t),l=e?drizzleOrm.and(i,drizzleOrm.or(drizzleOrm.eq(u.workspace_id,e),drizzleOrm.isNull(u.workspace_id))):i;if(r.db.select({id:u.id}).from(u).where(l).limit(1).get())return !0}catch(i){throw new c("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),n=0,r=0,i=0,l=0,a=0,p=new Set;for(let _ of s){if(!fs.existsSync(_))continue;let g=w(_);try{let D=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),v=e?drizzleOrm.and(D,drizzleOrm.eq(o.workspace_id,e)):D,$=g.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(o).where(v).get();$&&(n+=$.cnt,r+=$.total_input,i+=$.total_output,l+=$.total_cached,a+=$.total_cost);let bt=g.db.all(drizzleOrm.sql`
100
+ `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new c("DB_ERROR","Failed to get agent usage trend",r)}finally{n.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new c("DB_ERROR","Failed to find task for stop",n)}finally{s.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString(),i=s?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,s)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));n.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!fs.existsSync(i))continue;let l=w(i);try{let a=e?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.like(o.prompt,`%${t}%`),p=l.db.select().from(o).where(a).orderBy(drizzleOrm.asc(o.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(a){throw new c("DB_ERROR","Failed to find tasks by prompt hint",a)}finally{l.close();}}return r}};var ot=class extends A{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=H.join(t?.dbRoot??At.homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new J({dbPath:this.dbPath}),s=process.cwd(),n=fs.existsSync(H.join(s,"crewx.yaml"))||fs.existsSync(H.join(s,"crewx.yml")),r=n?ut(s):null,i=n?H.basename(s):null,l=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let p=process.env.CREWX_CALLER_AGENT_ID||null,_=process.env.CREWX_PARENT_TASK_ID||null,g=process.env.CREWX_TRACE_ID||a.traceId,D=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});e.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:l,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??r,workspaceName:a.workspaceName??i,callerAgentId:p,parentTaskId:_,traceId:g,metadata:D,threadId:a.threadId??null});}catch{}}),t.on("task:output",a=>{try{e.appendLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch{}}),t.on("task:end",a=>{try{e.finishTask({id:a.traceId,status:a.error?"failed":"success",result:a.result??null,error:a.error?JSON.stringify(a.error):null,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var Q=class extends F{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=H.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=H.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new c("NOT_FOUND","Database not found");let s=w(e);if(t)try{W(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:B.id}).from(B).where(drizzleOrm.eq(B.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!fs.existsSync(r))continue;let i=w(r);try{let l=t?drizzleOrm.or(drizzleOrm.eq(u.workspace_id,t),drizzleOrm.isNull(u.workspace_id)):void 0,a=i.db.select().from(u).where(l).orderBy(drizzleOrm.desc(u.updated_at)).all();for(let p of a)s.has(p.id)||(s.add(p.id),n.push(p));}catch(l){throw new c("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=w(n);try{let i=drizzleOrm.eq(u.id,t),l=e?drizzleOrm.and(i,drizzleOrm.or(drizzleOrm.eq(u.workspace_id,e),drizzleOrm.isNull(u.workspace_id))):i,a=r.db.select().from(u).where(l).limit(1).get()??void 0;if(a)return a}catch(i){throw new c("DB_ERROR","Failed to find thread by id",i)}finally{r.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=w(n);try{let i=drizzleOrm.eq(u.id,t),l=e?drizzleOrm.and(i,drizzleOrm.or(drizzleOrm.eq(u.workspace_id,e),drizzleOrm.isNull(u.workspace_id))):i;if(r.db.select({id:u.id}).from(u).where(l).limit(1).get())return !0}catch(i){throw new c("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),n=0,r=0,i=0,l=0,a=0,p=new Set;for(let _ of s){if(!fs.existsSync(_))continue;let g=w(_);try{let D=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),v=e?drizzleOrm.and(D,drizzleOrm.eq(o.workspace_id,e)):D,$=g.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(o).where(v).get();$&&(n+=$.cnt,r+=$.total_input,i+=$.total_output,l+=$.total_cached,a+=$.total_cost);let bt=g.db.all(drizzleOrm.sql`
101
101
  SELECT DISTINCT agent_id FROM tasks
102
102
  WHERE thread_id = ${t}
103
103
  AND agent_id IS NOT NULL AND agent_id != ''
@@ -114,4 +114,4 @@ ${s.join(`
114
114
  `);}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to save user message",r)}finally{n.close();}}saveAssistantMessage(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString();n.db.update(u).set({last_message:e,updated_at:r}).where(drizzleOrm.eq(u.id,t)).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to save assistant message",r)}finally{n.close();}}updateThread(t,e){if(!this.dbExists())return;let s=this.openHandle(true);try{let n={updated_at:new Date().toISOString()};e.title!==void 0&&(n.title=e.title,n.title_locked=1),e.titleLocked!==void 0&&(n.title_locked=e.titleLocked?1:0),s.db.update(u).set(n).where(drizzleOrm.eq(u.id,t)).run();}catch(n){throw n instanceof c?n:new c("DB_ERROR","Failed to update thread",n)}finally{s.close();}}};function ie(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
115
115
  `).filter(n=>!(n.startsWith("Loaded ")&&n.includes("layouts from")||n.includes("[dotenv@")||n.includes("[Nest]")&&n.includes("DEBUG")||n.startsWith("Registered custom layout:")||n.startsWith("Updated custom layout:"))).join(`
116
116
  `).trim()}function ae(d){if(!d)return "";let t=d;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
117
- `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=ie(t);}return t}var Q=class{dbPath;constructor(t){this.dbPath=t??tt.join(At.homedir(),".crewx","crewx.db");}getThreadRepo(){return new V({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let n=this.getThreadRepo(),r=n.findThreadById(t);if(r){if(r.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${r.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return}n.ensureThread(t,e,s);}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),i=n.findTopLevelTasks(t),l=new Set(["done","completed","success"]);i=i.filter(_=>(!_.status||l.has(_.status))&&(!e?.currentTraceId||_.trace_id!==e.currentTraceId)),i=i.slice(0,s);let a=r?.platform??"cli",p=this.rowsToMessages(i);return {threadId:t,platform:a,messages:p,metadata:{title:r?.title??void 0,firstMessage:r?.first_message??void 0,lastMessage:r?.last_message??void 0,messageCount:r?.message_count??0,updatedAt:r?.updated_at?new Date(r.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,n){this.getThreadRepo().saveUserMessage(t,e);}async saveAssistantMessage(t,e,s,n){this.getThreadRepo().saveAssistantMessage(t,e);}close(){}rowsToMessages(t){let e=[];for(let s of t){s.prompt&&e.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime()});let n=ae(s.result);n&&e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime()});}return e}};var it=class extends A{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new Q(t?.dbPath);}get conversationProvider(){return this._provider}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{await this._provider.ensureThread(e.threadId,s,e.workspaceId),await this._provider.saveUserMessage(e.threadId,e.message??"");}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let n=e.agentRef?.replace(/^@/,"")??"";try{await this._provider.saveAssistantMessage(s,e.result,n);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=it;exports.FileLoggerPlugin=Z;exports.SqliteTracingPlugin=ot;
117
+ `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=ie(t);}return t}var Z=class{dbPath;constructor(t){this.dbPath=t??H.join(At.homedir(),".crewx","crewx.db");}getThreadRepo(){return new Q({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let n=this.getThreadRepo(),r=n.findThreadById(t);if(r){if(r.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${r.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return}n.ensureThread(t,e,s);}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),i=n.findTopLevelTasks(t),l=new Set(["done","completed","success"]);i=i.filter(_=>(!_.status||l.has(_.status))&&(!e?.currentTraceId||_.trace_id!==e.currentTraceId)),i=i.slice(0,s);let a=r?.platform??"cli",p=this.rowsToMessages(i);return {threadId:t,platform:a,messages:p,metadata:{title:r?.title??void 0,firstMessage:r?.first_message??void 0,lastMessage:r?.last_message??void 0,messageCount:r?.message_count??0,updatedAt:r?.updated_at?new Date(r.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,n){this.getThreadRepo().saveUserMessage(t,e);}async saveAssistantMessage(t,e,s,n){this.getThreadRepo().saveAssistantMessage(t,e);}close(){}rowsToMessages(t){let e=[];for(let s of t){s.prompt&&e.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime()});let n=ae(s.result);n&&e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime()});}return e}};var it=class extends A{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new Z(t?.dbPath);}get conversationProvider(){return this._provider}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{await this._provider.ensureThread(e.threadId,s,e.workspaceId),await this._provider.saveUserMessage(e.threadId,e.message??"");}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let n=e.agentRef?.replace(/^@/,"")??"";try{await this._provider.saveAssistantMessage(s,e.result,n);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=it;exports.FileLoggerPlugin=tt;exports.SqliteTracingPlugin=ot;
@@ -1,11 +1,11 @@
1
- 'use strict';var Bt=require('fs'),lt=require('path'),Gt=require('os'),drizzleOrm=require('drizzle-orm'),sqliteCore=require('drizzle-orm/sqlite-core'),crypto=require('crypto');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 Bt__default=/*#__PURE__*/_interopDefault(Bt);var lt__namespace=/*#__PURE__*/_interopNamespace(lt);var Gt__default=/*#__PURE__*/_interopDefault(Gt);var J=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var y=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:lt.join(Gt__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 Bt.existsSync(t??this.resolveDbPath())}};var a=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 m(d){let t=J("better-sqlite3"),{drizzle:e}=J("drizzle-orm/better-sqlite3"),n=new t(d);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 Et=new Set;function Y(d){let{migrate:t}=J("drizzle-orm/better-sqlite3/migrator"),{sql:e}=J("drizzle-orm"),n=[lt__namespace.default.join(__dirname,"../migrations"),lt__namespace.default.join(__dirname,"migrations")],s=n.find(_=>Bt.existsSync(lt__namespace.default.join(_,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
1
+ 'use strict';var Bt=require('fs'),V=require('path'),Gt=require('os'),drizzleOrm=require('drizzle-orm'),sqliteCore=require('drizzle-orm/sqlite-core'),crypto=require('crypto');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 Bt__default=/*#__PURE__*/_interopDefault(Bt);var V__namespace=/*#__PURE__*/_interopNamespace(V);var Gt__default=/*#__PURE__*/_interopDefault(Gt);var Z=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var y=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:V.join(Gt__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 Bt.existsSync(t??this.resolveDbPath())}};var a=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 m(d){let t=Z("better-sqlite3"),{drizzle:e}=Z("drizzle-orm/better-sqlite3"),n=new t(d);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 Et=new Set;function Y(d){let{migrate:t}=Z("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Z("drizzle-orm"),n=[V__namespace.default.join(__dirname,"../migrations"),V__namespace.default.join(__dirname,"migrations"),V__namespace.default.join(__dirname,"../../../../drizzle/migrations"),V__namespace.default.join(process.cwd(),"drizzle/migrations")],s=n.find(_=>Bt.existsSync(V__namespace.default.join(_,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
3
- `)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),t(d,{migrationsFolder:s});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let _=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${_} (${c} migration${c>1?"s":""} applied).`);}}function D(d,t){Et.has(t)||(Y(d),Et.add(t));}var u=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 o=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"),workspace_name:sqliteCore.text("workspace_name"),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_name:sqliteCore.text("project_name"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(d.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>u.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)},d=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(d.workspace_id)}));var q=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>q.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")},d=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(d.parent_span_id)}));var B=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.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()},d=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(d.timestamp)}));var P=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.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()},d=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(d.thread_id,d.seq)}));var K=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")},d=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(d.partition_key)}));function ut(d){let t=lt__namespace.resolve(d);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 Pt(d){let t=ut(d);return crypto.createHash("sha256").update(t).digest("hex")}function et(d){return d.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var ht=class extends y{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?lt.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=lt.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{Y(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=et(lt.basename(n)),i=`${et(lt.basename(lt.dirname(n)))}-${s}`,l=[s,i];try{let c=_=>t.select({id:u.id}).from(u).where(drizzleOrm.and(drizzleOrm.eq(u.slug,_),drizzleOrm.ne(u.id,e))).limit(1).all().length>0;for(let _ of l)if(!c(_))return _;for(let _=2;_<1e3;_+=1){let h=`${i}-${_}`;if(!c(h))return h}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:u.id,slug:u.slug}).from(u).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=et(s.slug.replace(/\//g,"-"));t.db.update(u).set({slug:r,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(u.id,s.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:s,name:r,workspacePath:i}=e,l=new Date().toISOString();t.insert(u).values({id:n,slug:s,name:r,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(u).set({workspace_path:i,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(u.id,n),drizzleOrm.isNull(u.workspace_path))).run();}registerWorkspace(t){let e=ut(t),n=this.openHandle(true);try{let s=Pt(e),r=lt.basename(e),i=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:i,name:r,workspacePath:e}),{id:s,slug:i}}catch(s){throw s instanceof a?s:new a("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(u.is_active,t.isActive?1:0):void 0,s=e.db.select({count:drizzleOrm.sql`count(*)`}).from(u).where(n).get();return {rows:e.db.select().from(u).where(n).orderBy(drizzleOrm.desc(u.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new a("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(u).where(drizzleOrm.eq(u.id,t)).limit(1).get()??void 0}catch(n){throw new a("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 a("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.*,
3
+ `)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),t(d,{migrationsFolder:s});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let _=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${_} (${c} migration${c>1?"s":""} applied).`);}}function D(d,t){Et.has(t)||(Y(d),Et.add(t));}var u=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 o=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"),workspace_name:sqliteCore.text("workspace_name"),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_name:sqliteCore.text("project_name"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(d.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>u.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)},d=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(d.workspace_id)}));var q=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>q.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")},d=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(d.parent_span_id)}));var B=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.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()},d=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(d.timestamp)}));var P=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.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()},d=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(d.thread_id,d.seq)}));var K=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")},d=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(d.partition_key)}));function ut(d){let t=V__namespace.resolve(d);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 Pt(d){let t=ut(d);return crypto.createHash("sha256").update(t).digest("hex")}function nt(d){return d.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var ht=class extends y{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?V.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=V.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{Y(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=nt(V.basename(n)),i=`${nt(V.basename(V.dirname(n)))}-${s}`,l=[s,i];try{let c=_=>t.select({id:u.id}).from(u).where(drizzleOrm.and(drizzleOrm.eq(u.slug,_),drizzleOrm.ne(u.id,e))).limit(1).all().length>0;for(let _ of l)if(!c(_))return _;for(let _=2;_<1e3;_+=1){let h=`${i}-${_}`;if(!c(h))return h}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:u.id,slug:u.slug}).from(u).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=nt(s.slug.replace(/\//g,"-"));t.db.update(u).set({slug:r,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(u.id,s.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new a("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:s,name:r,workspacePath:i}=e,l=new Date().toISOString();t.insert(u).values({id:n,slug:s,name:r,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(u).set({workspace_path:i,updated_at:l}).where(drizzleOrm.and(drizzleOrm.eq(u.id,n),drizzleOrm.isNull(u.workspace_path))).run();}registerWorkspace(t){let e=ut(t),n=this.openHandle(true);try{let s=Pt(e),r=V.basename(e),i=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:i,name:r,workspacePath:e}),{id:s,slug:i}}catch(s){throw s instanceof a?s:new a("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(u.is_active,t.isActive?1:0):void 0,s=e.db.select({count:drizzleOrm.sql`count(*)`}).from(u).where(n).get();return {rows:e.db.select().from(u).where(n).orderBy(drizzleOrm.desc(u.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new a("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(u).where(drizzleOrm.eq(u.id,t)).limit(1).get()??void 0}catch(n){throw new a("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 a("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:s?.count??0}}catch(s){throw new a("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(u).where(drizzleOrm.eq(u.slug,t)).limit(1).get()??void 0}catch(n){throw new a("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(u.slug,t),drizzleOrm.ne(u.id,e)):drizzleOrm.eq(u.slug,t);return !!n.db.select({id:u.id}).from(u).where(s).limit(1).get()}catch(s){throw new a("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let i=new Date().toISOString();r.db.insert(u).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:i,updated_at:i}).run();let l=r.db.select().from(u).where(drizzleOrm.eq(u.id,t)).limit(1).get();if(!l)throw new a("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof a?i:new a("DB_ERROR","Failed to insert workspace",i)}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(u).where(drizzleOrm.eq(u.id,t)).limit(1).get();if(!r)throw new a("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof a?r:new a("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:u.id,workspace_path:u.workspace_path}).from(u).where(drizzleOrm.and(drizzleOrm.eq(u.is_active,1),drizzleOrm.isNotNull(u.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;Bt.existsSync(lt.join(r,"crewx.yaml"))||Bt.existsSync(lt.join(r,"crewx.yml"))||(t.db.update(u).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(u.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new a("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(u).where(drizzleOrm.eq(u.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Lt=[u,o,p,q,B,P,K];function me(){return lt__namespace.default.join(Gt__default.default.homedir(),".crewx","crewx.db")}function we(d){if(!Bt__default.default.existsSync(d))return null;let t=Math.floor(Date.now()/1e3),e=`${d}.bak-${t}`;return Bt__default.default.copyFileSync(d,e),e}function zt(d){let t=d.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function ge(d){return d==null||typeof d=="object"&&"queryChunks"in d?null:typeof d=="number"?String(d):typeof d=="boolean"?d?"1":"0":typeof d=="string"?`'${d.replace(/'/g,"''")}'`:String(d)}function ke(d){let t=d.getSQLType(),e=`"${d.name}" ${t}`,n=ge(d.default);return n!==null&&(e+=` DEFAULT ${n}`),d.notNull&&(e+=" NOT NULL"),e}function be(d,t){let e=t?.dbPath??me(),n=t?.force??false,s=t?.dryRun??false,r=s?null:we(e);if(n&&!s)try{d.run("DELETE FROM __drizzle_migrations");}catch{}let i=zt(d);s||Y(d);let l,c;s?(l=Lt.map(R=>sqliteCore.getTableConfig(R).name).filter(R=>!i.has(R)),c=i):(c=zt(d),l=[...c].filter(k=>!i.has(k)));let _=[],h=[];for(let k of Lt){let R=sqliteCore.getTableConfig(k),S=R.name;if(!c.has(S))continue;let L=d.all(`PRAGMA table_info("${S}")`),at=new Set(L.map(N=>N.name)),dt=new Set(R.columns.map(N=>N.name));for(let N of R.columns)if(!at.has(N.name)){if(!s){let jt=ke(N);d.run(`ALTER TABLE "${S}" ADD COLUMN ${jt}`);}_.push({table:S,column:N.name});}for(let N of L)dt.has(N.name)||h.push(`${S}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:_,warnings:h,backupPath:r}}var wt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=lt.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=lt.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,workspace_name:t.workspaceName??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 a?n:new a("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 a("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(u).where(drizzleOrm.eq(u.slug,t)).limit(1).get()??void 0}catch(n){throw new a("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(u.slug,t),drizzleOrm.ne(u.id,e)):drizzleOrm.eq(u.slug,t);return !!n.db.select({id:u.id}).from(u).where(s).limit(1).get()}catch(s){throw new a("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let i=new Date().toISOString();r.db.insert(u).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:i,updated_at:i}).run();let l=r.db.select().from(u).where(drizzleOrm.eq(u.id,t)).limit(1).get();if(!l)throw new a("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof a?i:new a("DB_ERROR","Failed to insert workspace",i)}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(u).where(drizzleOrm.eq(u.id,t)).limit(1).get();if(!r)throw new a("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof a?r:new a("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:u.id,workspace_path:u.workspace_path}).from(u).where(drizzleOrm.and(drizzleOrm.eq(u.is_active,1),drizzleOrm.isNotNull(u.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;Bt.existsSync(V.join(r,"crewx.yaml"))||Bt.existsSync(V.join(r,"crewx.yml"))||(t.db.update(u).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(u.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new a("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(u).where(drizzleOrm.eq(u.id,t)).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var zt=[u,o,p,q,B,P,K];function me(){return V__namespace.default.join(Gt__default.default.homedir(),".crewx","crewx.db")}function we(d){if(!Bt__default.default.existsSync(d))return null;let t=Math.floor(Date.now()/1e3),e=`${d}.bak-${t}`;return Bt__default.default.copyFileSync(d,e),e}function Lt(d){let t=d.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function ge(d){return d==null||typeof d=="object"&&"queryChunks"in d?null:typeof d=="number"?String(d):typeof d=="boolean"?d?"1":"0":typeof d=="string"?`'${d.replace(/'/g,"''")}'`:String(d)}function ke(d){let t=d.getSQLType(),e=`"${d.name}" ${t}`,n=ge(d.default);return n!==null&&(e+=` DEFAULT ${n}`),d.notNull&&(e+=" NOT NULL"),e}function be(d,t){let e=t?.dbPath??me(),n=t?.force??false,s=t?.dryRun??false,r=s?null:we(e);if(n&&!s)try{d.run("DELETE FROM __drizzle_migrations");}catch{}let i=Lt(d);s||Y(d);let l,c;s?(l=zt.map(R=>sqliteCore.getTableConfig(R).name).filter(R=>!i.has(R)),c=i):(c=Lt(d),l=[...c].filter(k=>!i.has(k)));let _=[],h=[];for(let k of zt){let R=sqliteCore.getTableConfig(k),S=R.name;if(!c.has(S))continue;let z=d.all(`PRAGMA table_info("${S}")`),dt=new Set(z.map(N=>N.name)),lt=new Set(R.columns.map(N=>N.name));for(let N of R.columns)if(!dt.has(N.name)){if(!s){let jt=ke(N);d.run(`ALTER TABLE "${S}" ADD COLUMN ${jt}`);}_.push({table:S,column:N.name});}for(let N of z)lt.has(N.name)||h.push(`${S}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:_,warnings:h,backupPath:r}}var wt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=V.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=V.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,workspace_name:t.workspaceName??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 a?n:new a("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
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 a?n:new a("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:o.logs}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),s.update(o).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof a?s:new a("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(o).where(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.started_at)).all()}catch(e){throw new a("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(drizzleOrm.desc(o.started_at)).limit(100).all()}catch(e){throw new a("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to kill task",n)}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Bt.existsSync(s))continue;let r=m(s);try{let i=e?drizzleOrm.eq(o.workspace_id,e):void 0,l=i?drizzleOrm.and(drizzleOrm.eq(o.id,t),i):drizzleOrm.eq(o.id,t),c=r.db.select().from(o).where(l).limit(1).get()??void 0;if(!c){let _=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),h=i?drizzleOrm.and(_,i):_;c=r.db.select().from(o).where(h).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new a("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=m(i);try{let c=e?drizzleOrm.and(drizzleOrm.eq(o.parent_task_id,t),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.eq(o.parent_task_id,t),_=l.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let h of _)s.has(h.id)||(s.add(h.id),r.push(h));}catch(c){throw new a("DB_ERROR","Failed to find child tasks",c)}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
@@ -92,13 +92,13 @@ ${n.join(`
92
92
  AND t.started_at < ${e}
93
93
  GROUP BY date(t.started_at), t.agent_id
94
94
  ORDER BY date(t.started_at) ASC
95
- `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new a("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(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new a("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(),i=n?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));s.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to mark task failed",r)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=m(i);try{let c=e?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.like(o.prompt,`%${t}%`),_=l.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let h of _)s.has(h.id)||(s.add(h.id),r.push(h));}catch(c){throw new a("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{l.close();}}return r}};var gt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=lt.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=lt.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:u.id}).from(u).where(drizzleOrm.eq(u.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!Bt.existsSync(r))continue;let i=m(r);try{let l=t?drizzleOrm.or(drizzleOrm.eq(p.workspace_id,t),drizzleOrm.isNull(p.workspace_id)):void 0,c=i.db.select().from(p).where(l).orderBy(drizzleOrm.desc(p.updated_at)).all();for(let _ of c)n.has(_.id)||(n.add(_.id),s.push(_));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Bt.existsSync(s))continue;let r=m(s);try{let i=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(i,drizzleOrm.or(drizzleOrm.eq(p.workspace_id,e),drizzleOrm.isNull(p.workspace_id))):i,c=r.db.select().from(p).where(l).limit(1).get()??void 0;if(c)return c}catch(i){throw new a("DB_ERROR","Failed to find thread by id",i)}finally{r.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Bt.existsSync(s))continue;let r=m(s);try{let i=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(i,drizzleOrm.or(drizzleOrm.eq(p.workspace_id,e),drizzleOrm.isNull(p.workspace_id))):i;if(r.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(i){throw new a("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,i=0,l=0,c=0,_=new Set;for(let h of n){if(!Bt.existsSync(h))continue;let k=m(h);try{let R=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),S=e?drizzleOrm.and(R,drizzleOrm.eq(o.workspace_id,e)):R,L=k.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(o).where(S).get();L&&(s+=L.cnt,r+=L.total_input,i+=L.total_output,l+=L.total_cached,c+=L.total_cost);let at=k.db.all(drizzleOrm.sql`
95
+ `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new a("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(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new a("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(),i=n?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));s.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to mark task failed",r)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=m(i);try{let c=e?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.like(o.prompt,`%${t}%`),_=l.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let h of _)s.has(h.id)||(s.add(h.id),r.push(h));}catch(c){throw new a("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{l.close();}}return r}};var gt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=V.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=V.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:u.id}).from(u).where(drizzleOrm.eq(u.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!Bt.existsSync(r))continue;let i=m(r);try{let l=t?drizzleOrm.or(drizzleOrm.eq(p.workspace_id,t),drizzleOrm.isNull(p.workspace_id)):void 0,c=i.db.select().from(p).where(l).orderBy(drizzleOrm.desc(p.updated_at)).all();for(let _ of c)n.has(_.id)||(n.add(_.id),s.push(_));}catch(l){throw new a("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Bt.existsSync(s))continue;let r=m(s);try{let i=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(i,drizzleOrm.or(drizzleOrm.eq(p.workspace_id,e),drizzleOrm.isNull(p.workspace_id))):i,c=r.db.select().from(p).where(l).limit(1).get()??void 0;if(c)return c}catch(i){throw new a("DB_ERROR","Failed to find thread by id",i)}finally{r.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Bt.existsSync(s))continue;let r=m(s);try{let i=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(i,drizzleOrm.or(drizzleOrm.eq(p.workspace_id,e),drizzleOrm.isNull(p.workspace_id))):i;if(r.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(i){throw new a("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,i=0,l=0,c=0,_=new Set;for(let h of n){if(!Bt.existsSync(h))continue;let k=m(h);try{let R=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),S=e?drizzleOrm.and(R,drizzleOrm.eq(o.workspace_id,e)):R,z=k.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(o).where(S).get();z&&(s+=z.cnt,r+=z.total_input,i+=z.total_output,l+=z.total_cached,c+=z.total_cost);let dt=k.db.all(drizzleOrm.sql`
96
96
  SELECT DISTINCT agent_id FROM tasks
97
97
  WHERE thread_id = ${t}
98
98
  AND agent_id IS NOT NULL AND agent_id != ''
99
99
  AND (parent_task_id IS NULL OR parent_task_id = '')
100
100
  ${e?drizzleOrm.sql`AND workspace_id = ${e}`:drizzleOrm.sql``}
101
- `);for(let dt of at)_.add(dt.agent_id);}catch(R){throw new a("DB_ERROR","Failed to aggregate task stats",R)}finally{k.close();}}return {taskCount:s,inputTokens:r,outputTokens:i,cachedInputTokens:l,costUsd:c,agentIds:Array.from(_)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=m(i);try{let c=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),_=e?drizzleOrm.and(c,drizzleOrm.eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(drizzleOrm.asc(o.started_at)).all();for(let k of h)s.has(k.id)||(s.add(k.id),r.push(k));}catch(c){throw new a("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}return r}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=m(i);try{let c=drizzleOrm.eq(o.thread_id,t),_=e?drizzleOrm.and(c,drizzleOrm.eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(drizzleOrm.asc(o.started_at)).all();for(let k of h)s.has(k.id)||(s.add(k.id),r.push(k));}catch(c){throw new a("DB_ERROR","Failed to find all tasks for thread",c)}finally{l.close();}}return r}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let r of s){if(!Bt.existsSync(r))continue;let i=m(r);try{let l=drizzleOrm.and(drizzleOrm.eq(o.id,e),drizzleOrm.eq(o.thread_id,t)),c=n?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,n)):l,_=i.db.select().from(o).where(c).limit(1).get();if(!_)continue;let h=i.db.select().from(o).where(drizzleOrm.eq(o.parent_task_id,_.id)).orderBy(drizzleOrm.asc(o.started_at)).all();return {task:_,children:h}}catch(l){throw new a("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let s=this.resolveDbPaths();for(let r of s){if(!Bt.existsSync(r))continue;let i=m(r);try{let l=drizzleOrm.and(drizzleOrm.inArray(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),c=e?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,e)):l,_=i.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let h of _){let k=h.thread_id;n.has(k)||n.set(k,[]),n.get(k).push(h);}}catch(l){throw new a("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=drizzleOrm.eq(p.id,t),i=n?drizzleOrm.and(r,drizzleOrm.or(drizzleOrm.eq(p.workspace_id,n),drizzleOrm.isNull(p.workspace_id))):r;if(!s.db.select({id:p.id}).from(p).where(i).limit(1).get())return;s.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(p.id,t)).run();}catch(r){throw r instanceof a?r:new a("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:p.id,message_count:p.message_count}).from(p).where(drizzleOrm.eq(p.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(p).set(l).where(drizzleOrm.eq(p.id,t)).run();}else n.db.insert(p).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 a?s:new a("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,i=s.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get();if(i){r&&!i.workspace_id&&s.db.update(p).set({workspace_id:r}).where(drizzleOrm.eq(p.id,t)).run();return}let l=new Date().toISOString();s.db.insert(p).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to ensure thread",r)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.run(drizzleOrm.sql`
101
+ `);for(let lt of dt)_.add(lt.agent_id);}catch(R){throw new a("DB_ERROR","Failed to aggregate task stats",R)}finally{k.close();}}return {taskCount:s,inputTokens:r,outputTokens:i,cachedInputTokens:l,costUsd:c,agentIds:Array.from(_)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=m(i);try{let c=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),_=e?drizzleOrm.and(c,drizzleOrm.eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(drizzleOrm.asc(o.started_at)).all();for(let k of h)s.has(k.id)||(s.add(k.id),r.push(k));}catch(c){throw new a("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}return r}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!Bt.existsSync(i))continue;let l=m(i);try{let c=drizzleOrm.eq(o.thread_id,t),_=e?drizzleOrm.and(c,drizzleOrm.eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(drizzleOrm.asc(o.started_at)).all();for(let k of h)s.has(k.id)||(s.add(k.id),r.push(k));}catch(c){throw new a("DB_ERROR","Failed to find all tasks for thread",c)}finally{l.close();}}return r}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let r of s){if(!Bt.existsSync(r))continue;let i=m(r);try{let l=drizzleOrm.and(drizzleOrm.eq(o.id,e),drizzleOrm.eq(o.thread_id,t)),c=n?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,n)):l,_=i.db.select().from(o).where(c).limit(1).get();if(!_)continue;let h=i.db.select().from(o).where(drizzleOrm.eq(o.parent_task_id,_.id)).orderBy(drizzleOrm.asc(o.started_at)).all();return {task:_,children:h}}catch(l){throw new a("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let s=this.resolveDbPaths();for(let r of s){if(!Bt.existsSync(r))continue;let i=m(r);try{let l=drizzleOrm.and(drizzleOrm.inArray(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),c=e?drizzleOrm.and(l,drizzleOrm.eq(o.workspace_id,e)):l,_=i.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let h of _){let k=h.thread_id;n.has(k)||n.set(k,[]),n.get(k).push(h);}}catch(l){throw new a("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=drizzleOrm.eq(p.id,t),i=n?drizzleOrm.and(r,drizzleOrm.or(drizzleOrm.eq(p.workspace_id,n),drizzleOrm.isNull(p.workspace_id))):r;if(!s.db.select({id:p.id}).from(p).where(i).limit(1).get())return;s.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(p.id,t)).run();}catch(r){throw r instanceof a?r:new a("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:p.id,message_count:p.message_count}).from(p).where(drizzleOrm.eq(p.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(p).set(l).where(drizzleOrm.eq(p.id,t)).run();}else n.db.insert(p).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 a?s:new a("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,i=s.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get();if(i){r&&!i.workspace_id&&s.db.update(p).set({workspace_id:r}).where(drizzleOrm.eq(p.id,t)).run();return}let l=new Date().toISOString();s.db.insert(p).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof a?r:new a("DB_ERROR","Failed to ensure thread",r)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.run(drizzleOrm.sql`
102
102
  UPDATE threads
103
103
  SET first_message = COALESCE(first_message, ${e}),
104
104
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -106,4 +106,4 @@ ${n.join(`
106
106
  message_count = message_count + 1,
107
107
  updated_at = ${r}
108
108
  WHERE id = ${t}
109
- `);}catch(r){throw r instanceof a?r:new a("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(p).set({last_message:e,updated_at:r}).where(drizzleOrm.eq(p.id,t)).run();}catch(r){throw r instanceof a?r:new a("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(p).set(s).where(drizzleOrm.eq(p.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread",s)}finally{n.close();}}};var kt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=lt.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=lt.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(q).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(q).where(drizzleOrm.eq(q.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(q).where(drizzleOrm.eq(q.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var bt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=lt.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=lt.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(B).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(B).where(drizzleOrm.eq(B.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:B.tool_name,count:drizzleOrm.sql`count(*)`}).from(B).where(drizzleOrm.eq(B.task_id,t)).groupBy(B.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new a("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var yt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=lt.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=lt.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get())throw new a("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 a?n:new a("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 a?s:new a("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 a("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 a("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Rt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=lt.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=lt.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(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(K).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 a?n:new a("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(K).orderBy(drizzleOrm.desc(K.timestamp)).limit(t).all()}catch(n){throw new a("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};exports.BaseSqliteRepository=y;exports.RepositoryError=a;exports.RequestLogRepository=Rt;exports.SpanRepository=kt;exports.TaskRepository=wt;exports.ThreadBoxRepository=yt;exports.ThreadRepository=gt;exports.ToolCallRepository=bt;exports.WorkspaceRepository=ht;exports.openDrizzleDb=m;exports.pushSchema=be;exports.runMigrations=Y;exports.runMigrationsOnce=D;
109
+ `);}catch(r){throw r instanceof a?r:new a("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(p).set({last_message:e,updated_at:r}).where(drizzleOrm.eq(p.id,t)).run();}catch(r){throw r instanceof a?r:new a("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(p).set(s).where(drizzleOrm.eq(p.id,t)).run();}catch(s){throw s instanceof a?s:new a("DB_ERROR","Failed to update thread",s)}finally{n.close();}}};var kt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=V.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=V.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(q).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(q).where(drizzleOrm.eq(q.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(q).where(drizzleOrm.eq(q.id,t)).limit(1).get()??void 0}catch(n){throw new a("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var bt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=V.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=V.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(B).values(t).run();}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(B).where(drizzleOrm.eq(B.task_id,t)).all()}catch(n){throw new a("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:B.tool_name,count:drizzleOrm.sql`count(*)`}).from(B).where(drizzleOrm.eq(B.task_id,t)).groupBy(B.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new a("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var yt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=V.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=V.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get())throw new a("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 a?n:new a("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 a?s:new a("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 a("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 a("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof a?n:new a("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Rt=class extends y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=V.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=V.dirname(e);Bt.existsSync(s)||Bt.mkdirSync(s,{recursive:true});}else if(!Bt.existsSync(e))throw new a("NOT_FOUND","Database not found");let n=m(e);if(t)try{D(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(K).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 a?n:new a("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(K).orderBy(drizzleOrm.desc(K.timestamp)).limit(t).all()}catch(n){throw new a("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};exports.BaseSqliteRepository=y;exports.RepositoryError=a;exports.RequestLogRepository=Rt;exports.SpanRepository=kt;exports.TaskRepository=wt;exports.ThreadBoxRepository=yt;exports.ThreadRepository=gt;exports.ToolCallRepository=bt;exports.WorkspaceRepository=ht;exports.openDrizzleDb=m;exports.pushSchema=be;exports.runMigrations=Y;exports.runMigrationsOnce=D;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewx/sdk",
3
- "version": "0.8.6-rc.6",
3
+ "version": "0.8.6-rc.8",
4
4
  "license": "UNLICENSED",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"
@@ -114,7 +114,7 @@
114
114
  "drizzle-kit": "0.31.10",
115
115
  "tsup": "8.5.1",
116
116
  "typescript": "5.9.3",
117
- "vitest": "3.1.1"
117
+ "vitest": "3.2.4"
118
118
  },
119
119
  "scripts": {
120
120
  "build:cjs": "npx tsup --config tsup.cjs.js",