@crewx/sdk 0.8.9-rc.9 → 0.9.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/activity-log/builder.d.ts +23 -0
  2. package/dist/config/pricing.d.ts +9 -0
  3. package/dist/conversation/sqlite-provider.d.ts +1 -0
  4. package/dist/esm/index.js +168 -45
  5. package/dist/esm/plugins/index.js +154 -27
  6. package/dist/esm/repository/index.js +150 -24
  7. package/dist/facade/Crewx.d.ts +1 -0
  8. package/dist/index.browser.d.ts +1 -0
  9. package/dist/index.browser.js +2 -2
  10. package/dist/index.d.ts +3 -1
  11. package/dist/index.js +168 -45
  12. package/dist/migrations/0006_add_task_run_epoch.sql +1 -0
  13. package/dist/migrations/meta/_journal.json +7 -0
  14. package/dist/plugins/index.js +154 -27
  15. package/dist/provider/acp/adapters/index.d.ts +0 -1
  16. package/dist/provider/acp/index.d.ts +1 -1
  17. package/dist/provider/acp/meta.d.ts +3 -0
  18. package/dist/provider/bridge.browser.d.ts +1 -10
  19. package/dist/provider/bridge.d.ts +2 -10
  20. package/dist/provider/cli/adapter.types.d.ts +23 -2
  21. package/dist/provider/cli/adapters/claude.d.ts +1 -0
  22. package/dist/provider/cli/adapters/cli-knob.util.d.ts +7 -0
  23. package/dist/provider/cli/adapters/gemini.d.ts +4 -2
  24. package/dist/provider/cli/adapters/index.d.ts +0 -1
  25. package/dist/provider/cli/index.d.ts +1 -1
  26. package/dist/provider/cli/meta.d.ts +4 -0
  27. package/dist/provider/errors.d.ts +20 -0
  28. package/dist/provider/order.d.ts +3 -0
  29. package/dist/repository/index.d.ts +2 -1
  30. package/dist/repository/index.js +150 -24
  31. package/dist/repository/task.repository.d.ts +15 -0
  32. package/dist/repository/thread.repository.d.ts +1 -1
  33. package/dist/schema/tasks.d.ts +17 -0
  34. package/dist/types/index.d.ts +2 -0
  35. package/package.json +4 -4
  36. package/templates/agents/default.yaml +8 -4
@@ -1,4 +1,4 @@
1
- import*as A from'path';import A__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import It,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,or,isNull,like,asc,inArray,gte,lt as lt$1}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique}from'drizzle-orm/sqlite-core';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 Dt=()=>fileURLToPath(import.meta.url),Ot=()=>A__default.dirname(Dt()),g=Ot();var P=class{detach(t){}};function ct(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 et=class extends P{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let s=ct(e.timestamp),n=join(this.logsDir,`${s}_${e.traceId}.log`);this.logFiles.set(e.traceId,n);let r=`=== TASK LOG: ${e.traceId} ===
1
+ import*as N from'path';import N__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import Ft,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,or,isNull,like,asc,inArray,gte,lt}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique}from'drizzle-orm/sqlite-core';var G=(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 Nt=()=>fileURLToPath(import.meta.url),vt=()=>N__default.dirname(Nt()),g=vt();var L=class{detach(t){}};function _t(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 rt=class extends L{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let s=_t(e.timestamp),n=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}
@@ -6,13 +6,14 @@ Started: ${e.timestamp.toLocaleString()}
6
6
  Message: ${e.message}
7
7
 
8
8
  `;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();appendFileSync(s,`[${n}] STDOUT: ${e.output}
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",o=`[${n}] INFO: Task ${r} in ${e.durationMs}ms
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
- `;appendFileSync(s,o,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Lt(d){let t=A.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 ht(d){let t=Lt(d);return createHash("sha256").update(t).digest("hex")}var U=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(It.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};function y(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 mt=new Set,Ut={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function st(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Ft(d,t){if(t>0||!st(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),s=new Set(e.map(n=>n.name));for(let[n,r]of Object.entries(Ut))s.has(n)||d.run(`ALTER TABLE tasks ADD COLUMN ${n} ${r}`);}var Bt={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function zt(d,t,e){if(!st(d,"__drizzle_migrations")||!st(d,"tasks"))return;let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(o=>o.hash)),r=JSON.parse(readFileSync(A__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let i=Bt[o.tag];if(!i)continue;let l=A__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let p=readFileSync(l,"utf-8"),_=createHash("sha256").update(p).digest("hex");if(n.has(_))continue;let k=d.all("PRAGMA table_info(tasks)"),w=new Set(k.map(S=>S.name));for(let[S,H]of Object.entries(i))w.has(S)||(d.run(`ALTER TABLE tasks ADD COLUMN ${S} ${H}`),w.add(S));}}function qt(d,t,e){let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(o=>o.hash)),r=JSON.parse(readFileSync(A__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let i=A__default.join(t,`${o.tag}.sql`);if(!existsSync(i))continue;let l=readFileSync(i,"utf-8"),p=createHash("sha256").update(l).digest("hex");if(n.has(p))continue;let _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,k=[],w;for(;(w=_.exec(l))!==null;)k.push({table:w[1],column:w[2]});if(k.length===0||!l.split(/-->\s*statement-breakpoint/).map(q=>q.trim()).filter(Boolean).every(q=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(q)))continue;k.every(({table:q,column:St})=>d.all(`PRAGMA table_info("${q}")`).some(Rt=>Rt.name===St))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${o.when})`);}}function Ht(d){let{migrate:t}=j("drizzle-orm/better-sqlite3/migrator"),{sql:e}=j("drizzle-orm"),s=[A__default.join(g,"../migrations"),A__default.join(g,"migrations"),A__default.join(g,"../../../../drizzle/migrations"),A__default.join(process.cwd(),"drizzle/migrations")],n=s.find(p=>existsSync(A__default.join(p,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
11
+ `;appendFileSync(s,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Mt(d){let t=N.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 gt(d){let t=Mt(d);return createHash("sha256").update(t).digest("hex")}var z=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ft.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};function T(d){let t=G("better-sqlite3"),{drizzle:e}=G("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 kt=new Set,Ht={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function ot(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function zt(d,t){if(t>0||!ot(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),s=new Set(e.map(n=>n.name));for(let[n,r]of Object.entries(Ht))s.has(n)||d.run(`ALTER TABLE tasks ADD COLUMN ${n} ${r}`);}var qt={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Wt(d,t,e){if(!ot(d,"__drizzle_migrations")||!ot(d,"tasks"))return;let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(i=>i.hash)),r=JSON.parse(readFileSync(N__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let a=qt[i.tag];if(!a)continue;let l=N__default.join(t,`${i.tag}.sql`);if(!existsSync(l))continue;let c=readFileSync(l,"utf-8"),_=createHash("sha256").update(c).digest("hex");if(n.has(_))continue;let k=d.all("PRAGMA table_info(tasks)"),w=new Set(k.map(R=>R.name));for(let[R,K]of Object.entries(a))w.has(R)||(d.run(`ALTER TABLE tasks ADD COLUMN ${R} ${K}`),w.add(R));}}function jt(d,t,e){let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(i=>i.hash)),r=JSON.parse(readFileSync(N__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let a=N__default.join(t,`${i.tag}.sql`);if(!existsSync(a))continue;let l=readFileSync(a,"utf-8"),c=createHash("sha256").update(l).digest("hex");if(n.has(c))continue;let _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,k=[],w;for(;(w=_.exec(l))!==null;)k.push({table:w[1],column:w[2]});if(k.length===0||!l.split(/-->\s*statement-breakpoint/).map(j=>j.trim()).filter(Boolean).every(j=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(j)))continue;k.every(({table:j,column:At})=>d.all(`PRAGMA table_info("${j}")`).some(Ct=>Ct.name===At))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function Kt(d){let{migrate:t}=G("drizzle-orm/better-sqlite3/migrator"),{sql:e}=G("drizzle-orm"),s=[N__default.join(g,"../migrations"),N__default.join(g,"migrations"),N__default.join(g,"../../../../drizzle/migrations"),N__default.join(process.cwd(),"drizzle/migrations")],n=s.find(c=>existsSync(N__default.join(c,"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'`),o=0;r?.cnt&&(o=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ft(d,o),r?.cnt&&(qt(d,n,e),zt(d,n,e)),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(l>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${l} migration${l>1?"s":""} applied).`);}}function X(d,t){mt.has(t)||(Ht(d),mt.add(t));}var u=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 F=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var a=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var c=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>F.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var Vt=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Vt.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>c.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));var Q=class extends U{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new u("NOT_FOUND","Database not found");let s=y(e);if(t)try{X(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(a).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(s){throw s instanceof u?s:new u("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),zt(d,i),r?.cnt&&(jt(d,n,e),Wt(d,n,e)),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function Y(d,t){kt.has(t)||(Kt(d),kt.add(t));}var p=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 q=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var u=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>q.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var te=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>te.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>u.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));var B="2026-05-09",pe="0.8.9-rc.13",F=10,H=parseInt(pe.split("rc.")[1]),et=class extends z{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new p("NOT_FOUND","Database not found");let s=T(e);if(t)try{Y(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,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 p?s:new p("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let s=t.runEpoch??null;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
- 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 u?s:new u("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:a.logs}).from(a).where(eq(a.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),n.update(a).set({logs:JSON.stringify(o)}).where(eq(a.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof u?n:new u("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(a).where(eq(a.status,"running")).orderBy(desc(a.started_at)).all()}catch(e){throw new u("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(a).orderBy(desc(a.started_at)).limit(100).all()}catch(e){throw new u("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(a).where(eq(a.id,t)).limit(1).get()??void 0}catch(s){throw new u("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:a.id,status:a.status,pid:a.pid}).from(a).where(eq(a.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(a).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(a.id,t),eq(a.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:a.id,pid:a.pid}).from(a).where(eq(a.status,"running")).all(),s=0;for(let n of e){if(!n.pid)continue;let r=!1;try{process.kill(n.pid,0),r=!0;}catch{}r||(t.db.update(a).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(a.id,n.id),eq(a.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=y(n);try{let o=e?eq(a.workspace_id,e):void 0,i=o?and(eq(a.id,t),o):eq(a.id,t),l=r.db.select().from(a).where(i).limit(1).get()??void 0;if(!l){let p=or(eq(a.thread_id,t),and(isNull(a.thread_id),like(a.command,`%--thread=${t}%`))),_=o?and(p,o):p;l=r.db.select().from(a).where(_).orderBy(desc(a.started_at)).limit(1).get()??void 0;}if(l)return l}catch(o){throw new u("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let l=e?and(eq(a.parent_task_id,t),eq(a.workspace_id,e)):eq(a.parent_task_id,t),p=i.db.select().from(a).where(l).orderBy(asc(a.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(l){throw new u("DB_ERROR","Failed to find child tasks",l)}finally{i.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
15
+ model=COALESCE(?, model)
16
+ WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,s]);}catch(s){throw s instanceof p?s:new p("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(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(eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof p?n:new p("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(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new p("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(desc(o.started_at)).limit(100).all()}catch(e){throw new p("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new p("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(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(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(eq(o.status,"running")).all(),s=0;for(let n of e){if(!n.pid)continue;let r=!1;try{process.kill(n.pid,0),r=!0;}catch{}r||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,n.id),eq(o.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=T(n);try{let i=e?eq(o.workspace_id,e):void 0,a=i?and(eq(o.id,t),i):eq(o.id,t),l=r.db.select().from(o).where(a).limit(1).get()??void 0;if(!l){let c=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),_=i?and(c,i):c;l=r.db.select().from(o).where(_).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(l)return l}catch(i){throw new p("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(!existsSync(i))continue;let a=T(i);try{let l=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),c=a.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let _ of c)n.has(_.id)||(n.add(_.id),r.push(_));}catch(l){throw new p("DB_ERROR","Failed to find child tasks",l)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
16
17
  SELECT
17
18
  COALESCE(workspace_id, 'unknown') AS workspace_id,
18
19
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -33,12 +34,24 @@ ${s.join(`
33
34
  FROM tasks
34
35
  GROUP BY workspace_id
35
36
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
36
- `)}catch(s){throw new u("DB_ERROR","Failed to get workspace usage summary",s)}finally{e.close();}}getThreadTokenUsage(t,e){let s=this.resolveDbPaths(),n=new Set,r=0,o=0,i=0;for(let l of s){if(!existsSync(l))continue;let p=y(l);try{let _=or(eq(a.thread_id,t),and(isNull(a.thread_id),like(a.command,`%--thread=${t}%`))),k=e?and(_,eq(a.workspace_id,e)):_,w=p.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(k).all();for(let S of w)n.has(S.id)||(n.add(S.id),r+=S.input_tokens??0,o+=S.output_tokens??0,i+=S.cost_usd??0);}catch(_){throw new u("DB_ERROR","Failed to get thread token usage",_)}finally{p.close();}}return {inputTokens:r,outputTokens:o,costUsd:i}}findTasksByThread(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let l=or(eq(a.thread_id,t),and(isNull(a.thread_id),like(a.command,`%--thread=${t}%`))),p=e?and(l,eq(a.workspace_id,e)):l,_=i.db.select().from(a).where(p).orderBy(asc(a.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(l){throw new u("DB_ERROR","Failed to find tasks by thread",l)}finally{i.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(a.workspace_id,t.workspaceId));let n=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;n&&s.push(inArray(a.agent_id,n));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&s.push(inArray(a.status,r));let o=t.q??t.search;o&&s.push(like(a.prompt,`%${o}%`)),t.from&&s.push(gte(a.started_at,t.from)),t.to&&s.push(lt$1(a.started_at,t.to));let i=s.length>0?and(...s):void 0,l=e.db.select({count:sql`count(*)`}).from(a).where(i).get(),p=(t.sortDir??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at);return {rows:e.db.select().from(a).where(i).orderBy(p).limit(t.limit).offset(t.offset).all(),total:l?.count??0}}catch(s){throw new u("DB_ERROR","Failed to find all tasks",s)}finally{e.close();}}getAgentUsage(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
37
+ `)}catch(s){throw new p("DB_ERROR","Failed to get workspace usage summary",s)}finally{e.close();}}getThreadTokenUsage(t,e){let s=this.resolveDbPaths(),n=new Set,r=0,i=0,a=0;for(let l of s){if(!existsSync(l))continue;let c=T(l);try{let _=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),k=e?and(_,eq(o.workspace_id,e)):_,w=c.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(k).all();for(let R of w)n.has(R.id)||(n.add(R.id),r+=R.input_tokens??0,i+=R.output_tokens??0,a+=R.cost_usd??0);}catch(_){throw new p("DB_ERROR","Failed to get thread token usage",_)}finally{c.close();}}return {inputTokens:r,outputTokens:i,costUsd:a}}findTasksByThread(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let a=T(i);try{let l=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),c=e?and(l,eq(o.workspace_id,e)):l,_=a.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(l){throw new p("DB_ERROR","Failed to find tasks by thread",l)}finally{a.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(o.workspace_id,t.workspaceId));let n=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;n&&s.push(inArray(o.agent_id,n));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&s.push(inArray(o.status,r));let i=t.q??t.search;i&&s.push(like(o.prompt,`%${i}%`)),t.from&&s.push(gte(o.started_at,t.from)),t.to&&s.push(lt(o.started_at,t.to));let a=s.length>0?and(...s):void 0,l=e.db.select({count:sql`count(*)`}).from(o).where(a).get(),c=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(a).orderBy(c).limit(t.limit).offset(t.offset).all(),total:l?.count??0}}catch(s){throw new p("DB_ERROR","Failed to find all tasks",s)}finally{e.close();}}getAgentUsage(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
37
38
  SELECT
38
39
  t.agent_id,
39
40
  t.workspace_id,
40
41
  COUNT(*) AS total_tasks,
41
- COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
42
+ COALESCE(SUM(
43
+ COALESCE(t.input_tokens, 0)
44
+ + CASE
45
+ WHEN t.started_at >= ${B}
46
+ AND (
47
+ t.crewx_version IS NULL
48
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
49
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${F}) AS INTEGER) < ${H})
50
+ )
51
+ THEN COALESCE(t.cached_input_tokens, 0)
52
+ ELSE 0
53
+ END
54
+ ), 0) AS input_tokens,
42
55
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
43
56
  COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
44
57
  COALESCE(SUM(t.cost_usd), 0) AS cost_usd
@@ -48,13 +61,40 @@ ${s.join(`
48
61
  AND t.started_at < ${e}
49
62
  AND t.workspace_id = ${s}
50
63
  GROUP BY t.agent_id, t.workspace_id
51
- ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
64
+ ORDER BY (
65
+ COALESCE(SUM(
66
+ COALESCE(t.input_tokens, 0)
67
+ + CASE
68
+ WHEN t.started_at >= ${B}
69
+ AND (
70
+ t.crewx_version IS NULL
71
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
72
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${F}) AS INTEGER) < ${H})
73
+ )
74
+ THEN COALESCE(t.cached_input_tokens, 0)
75
+ ELSE 0
76
+ END
77
+ ), 0)
78
+ + COALESCE(SUM(t.output_tokens), 0)
79
+ ) DESC
52
80
  `:sql`
53
81
  SELECT
54
82
  t.agent_id,
55
83
  t.workspace_id,
56
84
  COUNT(*) AS total_tasks,
57
- COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
85
+ COALESCE(SUM(
86
+ COALESCE(t.input_tokens, 0)
87
+ + CASE
88
+ WHEN t.started_at >= ${B}
89
+ AND (
90
+ t.crewx_version IS NULL
91
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
92
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${F}) AS INTEGER) < ${H})
93
+ )
94
+ THEN COALESCE(t.cached_input_tokens, 0)
95
+ ELSE 0
96
+ END
97
+ ), 0) AS input_tokens,
58
98
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
59
99
  COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
60
100
  COALESCE(SUM(t.cost_usd), 0) AS cost_usd
@@ -63,12 +103,39 @@ ${s.join(`
63
103
  AND t.started_at >= ${t}
64
104
  AND t.started_at < ${e}
65
105
  GROUP BY t.agent_id, t.workspace_id
66
- ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
67
- `).map(o=>({agentId:o.agent_id,workspaceId:o.workspace_id??null,totalTasks:o.total_tasks,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new u("DB_ERROR","Failed to get agent usage",r)}finally{n.close();}}getAgentUsageTrendRaw(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
106
+ ORDER BY (
107
+ COALESCE(SUM(
108
+ COALESCE(t.input_tokens, 0)
109
+ + CASE
110
+ WHEN t.started_at >= ${B}
111
+ AND (
112
+ t.crewx_version IS NULL
113
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
114
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${F}) AS INTEGER) < ${H})
115
+ )
116
+ THEN COALESCE(t.cached_input_tokens, 0)
117
+ ELSE 0
118
+ END
119
+ ), 0)
120
+ + COALESCE(SUM(t.output_tokens), 0)
121
+ ) DESC
122
+ `).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(r){throw new p("DB_ERROR","Failed to get agent usage",r)}finally{n.close();}}getAgentUsageTrendRaw(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
68
123
  SELECT
69
124
  date(t.started_at) AS date,
70
125
  t.agent_id,
71
- COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
126
+ COALESCE(SUM(
127
+ COALESCE(t.input_tokens, 0)
128
+ + CASE
129
+ WHEN t.started_at >= ${B}
130
+ AND (
131
+ t.crewx_version IS NULL
132
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
133
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${F}) AS INTEGER) < ${H})
134
+ )
135
+ THEN COALESCE(t.cached_input_tokens, 0)
136
+ ELSE 0
137
+ END
138
+ ), 0) AS input_tokens,
72
139
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
73
140
  COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
74
141
  COALESCE(SUM(t.cost_usd), 0) AS cost_usd
@@ -83,7 +150,19 @@ ${s.join(`
83
150
  SELECT
84
151
  date(t.started_at) AS date,
85
152
  t.agent_id,
86
- COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
153
+ COALESCE(SUM(
154
+ COALESCE(t.input_tokens, 0)
155
+ + CASE
156
+ WHEN t.started_at >= ${B}
157
+ AND (
158
+ t.crewx_version IS NULL
159
+ OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
160
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${F}) AS INTEGER) < ${H})
161
+ )
162
+ THEN COALESCE(t.cached_input_tokens, 0)
163
+ ELSE 0
164
+ END
165
+ ), 0) AS input_tokens,
87
166
  COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
88
167
  COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
89
168
  COALESCE(SUM(t.cost_usd), 0) AS cost_usd
@@ -93,7 +172,43 @@ ${s.join(`
93
172
  AND t.started_at < ${e}
94
173
  GROUP BY date(t.started_at), t.agent_id
95
174
  ORDER BY date(t.started_at) ASC
96
- `).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd}))}catch(r){throw new u("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(a).where(and(eq(a.id,t),eq(a.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new u("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(),o=s?and(eq(a.id,t),eq(a.status,"running"),eq(a.workspace_id,s)):and(eq(a.id,t),eq(a.status,"running"));n.db.update(a).set({status:"failed",error:e,completed_at:r}).where(o).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let l=e?and(like(a.prompt,`%${t}%`),eq(a.workspace_id,e)):like(a.prompt,`%${t}%`),p=i.db.select().from(a).where(l).orderBy(asc(a.started_at)).all();for(let _ of p)n.has(_.id)||(n.add(_.id),r.push(_));}catch(l){throw new u("DB_ERROR","Failed to find tasks by prompt hint",l)}finally{i.close();}}return r}};var dt=class extends P{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new Q({dbPath:this.dbPath}),s=process.cwd(),r=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?ht(s):null,o=process.argv.join(" ");this.unsubs.push(t.on("task:start",i=>{try{let l=i.callerAgentId??null,p=i.parentTaskId??null,_=i.rootTraceId??i.traceId,k=i.metadata?JSON.stringify(i.metadata):JSON.stringify({provider:i.provider??"cli/claude"});e.startTask({id:i.traceId,agentId:i.agentRef.replace(/^@/,""),prompt:i.message,mode:i.mode,status:"running",pid:i.pid??null,startedAt:i.timestamp.toISOString(),crewxVersion:this.version,platform:i.platform??"cli",model:i.model??null,renderedPrompt:i.renderedPrompt??null,command:o,codingAgentCommand:i.codingAgentCommand??null,workspaceId:i.workspaceId??r,callerAgentId:l,parentTaskId:p,traceId:_,metadata:k,threadId:i.threadId??null});}catch{}}),t.on("task:output",i=>{try{e.appendLog(i.traceId,{timestamp:i.timestamp.toISOString(),level:i.level??"stdout",message:i.output});}catch{}}),t.on("task:end",i=>{try{e.finishTask({id:i.traceId,status:i.error?"failed":"success",result:i.result??null,error:i.error?JSON.stringify(i.error):null,completedAt:i.timestamp.toISOString(),durationMs:i.durationMs,exitCode:i.exitCode??null,inputTokens:i.inputTokens??0,outputTokens:i.outputTokens??0,cachedInputTokens:i.cachedInputTokens??0,costUsd:i.costUsd??0,model:i.model??null});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var Z=class extends U{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new u("NOT_FOUND","Database not found");let s=y(e);if(t)try{X(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:F.id}).from(F).where(eq(F.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
175
+ `).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(r){throw new p("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(and(eq(o.id,t),eq(o.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new p("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?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,s)):and(eq(o.id,t),eq(o.status,"running"));n.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof p?r:new p("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(!existsSync(i))continue;let a=T(i);try{let l=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),c=a.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let _ of c)n.has(_.id)||(n.add(_.id),r.push(_));}catch(l){throw new p("DB_ERROR","Failed to find tasks by prompt hint",l)}finally{a.close();}}return r}getProviderUsage(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=sql`
176
+ CASE
177
+ WHEN ${o.model} LIKE 'claude-%' OR ${o.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
178
+ WHEN ${o.model} LIKE 'gpt-%' OR ${o.model} LIKE 'codex-%' THEN 'codex'
179
+ WHEN ${o.model} LIKE 'gemini-%' THEN 'gemini'
180
+ WHEN ${o.model} LIKE 'zai-%' OR ${o.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
181
+ WHEN ${o.model} LIKE 'minimax/%' THEN 'minimax'
182
+ WHEN ${o.model} LIKE 'qwen%' THEN 'qwen'
183
+ ELSE 'unknown'
184
+ END
185
+ `,i=sql`
186
+ COALESCE(${o.input_tokens}, 0)
187
+ + CASE
188
+ WHEN ${o.started_at} >= ${B}
189
+ AND (
190
+ ${o.crewx_version} IS NULL
191
+ OR (${o.crewx_version} LIKE '0.8.%' AND ${o.crewx_version} NOT LIKE '0.8.9%')
192
+ OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${F}) AS INTEGER) < ${H})
193
+ )
194
+ THEN COALESCE(${o.cached_input_tokens}, 0)
195
+ ELSE 0
196
+ END
197
+ `,a=s?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e} AND ${o.workspace_id} = ${s}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${t} AND ${o.started_at} < ${e}`;return n.db.all(sql`
198
+ SELECT
199
+ ${r} AS provider,
200
+ COUNT(*) AS total_tasks,
201
+ COALESCE(SUM(${i}), 0) AS input_tokens,
202
+ COALESCE(SUM(${o.output_tokens}), 0) AS output_tokens,
203
+ COALESCE(SUM(${o.cached_input_tokens}), 0) AS cached_input_tokens,
204
+ COALESCE(SUM(${o.cost_usd}), 0) AS cost_usd,
205
+ COALESCE(SUM(${o.duration_ms}), 0) AS active_duration_ms,
206
+ MAX(${o.completed_at}) AS last_active_at
207
+ FROM ${o}
208
+ ${a}
209
+ GROUP BY provider
210
+ ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${o.output_tokens}), 0)) DESC
211
+ `).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(r){throw new p("DB_ERROR","Failed to get provider usage",r)}finally{n.close();}}};var ut=class extends L{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new et({dbPath:this.dbPath}),s=process.cwd(),r=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?gt(s):null,i=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let l=a.callerAgentId??null,c=a.parentTaskId??null,_=a.rootTraceId??a.traceId,k=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:i,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??r,callerAgentId:l,parentTaskId:c,traceId:_,metadata:k,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{let l=typeof a.metadata?.runEpoch=="number"?a.metadata.runEpoch:null;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,runEpoch:l});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var st=class extends z{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new p("NOT_FOUND","Database not found");let s=T(e);if(t)try{Y(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:q.id}).from(q).where(eq(q.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
97
212
  ${t}.parent_task_id IS NULL
98
213
  OR ${t}.parent_task_id = ''
99
214
  OR NOT EXISTS (
@@ -101,7 +216,7 @@ ${s.join(`
101
216
  WHERE parent.id = ${t}.parent_task_id
102
217
  AND parent.thread_id = ${t}.thread_id
103
218
  )
104
- )`)}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!existsSync(r))continue;let o=y(r);try{let i=t?eq(c.workspace_id,t):void 0,l=o.db.select().from(c).where(i).orderBy(desc(c.updated_at)).all();for(let p of l)s.has(p.id)||(s.add(p.id),n.push(p));}catch(i){throw new u("DB_ERROR","Failed to find all threads",i)}finally{o.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=y(n);try{let o=eq(c.id,t),i=e?and(o,eq(c.workspace_id,e)):o,l=r.db.select().from(c).where(i).limit(1).get()??void 0;if(l)return l}catch(o){throw new u("DB_ERROR","Failed to find thread by id",o)}finally{r.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=y(n);try{let o=eq(c.id,t),i=e?and(o,eq(c.workspace_id,e)):o;if(r.db.select({id:c.id}).from(c).where(i).limit(1).get())return !0}catch(o){throw new u("DB_ERROR","Failed to check thread existence",o)}finally{r.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),n=0,r=0,o=0,i=0,l=0,p=new Set;for(let _ of s){if(!existsSync(_))continue;let k=y(_);try{let w=k.db.get(sql`
219
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!existsSync(r))continue;let i=T(r);try{let a=t?eq(u.workspace_id,t):void 0,l=i.db.select().from(u).where(a).orderBy(desc(u.updated_at)).all();for(let c of l)s.has(c.id)||(s.add(c.id),n.push(c));}catch(a){throw new p("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=T(n);try{let i=eq(u.id,t),a=e?and(i,eq(u.workspace_id,e)):i,l=r.db.select().from(u).where(a).limit(1).get()??void 0;if(l)return l}catch(i){throw new p("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(!existsSync(n))continue;let r=T(n);try{let i=eq(u.id,t),a=e?and(i,eq(u.workspace_id,e)):i;if(r.db.select({id:u.id}).from(u).where(a).limit(1).get())return !0}catch(i){throw new p("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,a=0,l=0,c=new Set;for(let _ of s){if(!existsSync(_))continue;let k=T(_);try{let w=k.db.get(sql`
105
220
  SELECT
106
221
  count(*) AS cnt,
107
222
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -112,25 +227,36 @@ ${s.join(`
112
227
  WHERE child.thread_id = ${t}
113
228
  AND ${this.topLevelTaskPredicateSql()}
114
229
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
115
- `);w&&(n+=w.cnt,r+=w.total_input,o+=w.total_output,i+=w.total_cached,l+=w.total_cost);let S=k.db.all(sql`
230
+ `);w&&(n+=w.cnt,r+=w.total_input,i+=w.total_output,a+=w.total_cached,l+=w.total_cost);let R=k.db.all(sql`
116
231
  SELECT DISTINCT child.agent_id FROM tasks child
117
232
  WHERE child.thread_id = ${t}
118
233
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
119
234
  AND ${this.topLevelTaskPredicateSql()}
120
235
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
121
- `);for(let H of S)p.add(H.agent_id);}catch(w){throw new u("DB_ERROR","Failed to aggregate task stats",w)}finally{k.close();}}return {taskCount:n,inputTokens:r,outputTokens:o,cachedInputTokens:i,costUsd:l,agentIds:Array.from(p)}}findTopLevelTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let l=i.db.all(sql`
122
- SELECT child.* FROM tasks child
123
- WHERE child.thread_id = ${t}
124
- AND ${this.topLevelTaskPredicateSql()}
125
- ${e?sql`AND child.workspace_id = ${e}`:sql``}
126
- ORDER BY child.started_at ASC
127
- `);for(let p of l)n.has(p.id)||(n.add(p.id),r.push(p));}catch(l){throw new u("DB_ERROR","Failed to find top-level tasks",l)}finally{i.close();}}return r}findAllTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let i=y(o);try{let l=eq(a.thread_id,t),p=e?and(l,eq(a.workspace_id,e)):l,_=i.db.select().from(a).where(p).orderBy(asc(a.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(l){throw new u("DB_ERROR","Failed to find all tasks for thread",l)}finally{i.close();}}return r}findTaskById(t,e,s){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=and(eq(a.id,e),eq(a.thread_id,t)),l=s?and(i,eq(a.workspace_id,s)):i,p=o.db.select().from(a).where(l).limit(1).get();if(!p)continue;let _=o.db.select().from(a).where(eq(a.parent_task_id,p.id)).orderBy(asc(a.started_at)).all();return {task:p,children:_}}catch(i){throw new u("DB_ERROR","Failed to find task by id",i)}finally{o.close();}}}batchFetchTasks(t,e){let s=new Map;if(t.length===0)return s;let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=o.db.all(sql`
236
+ `);for(let K of R)c.add(K.agent_id);}catch(w){throw new p("DB_ERROR","Failed to aggregate task stats",w)}finally{k.close();}}return {taskCount:n,inputTokens:r,outputTokens:i,cachedInputTokens:a,costUsd:l,agentIds:Array.from(c)}}findTopLevelTasks(t,e,s){let n=this.resolveDbPaths(),r=new Set,i=[];for(let a of n){if(!existsSync(a))continue;let l=T(a);try{let c;s!==void 0?c=l.db.all(sql`
237
+ SELECT * FROM (
238
+ SELECT child.*,
239
+ ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
240
+ FROM tasks child
241
+ WHERE child.thread_id = ${t}
242
+ AND ${this.topLevelTaskPredicateSql()}
243
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
244
+ ) ranked
245
+ WHERE rn <= ${s}
246
+ ORDER BY started_at ASC
247
+ `):c=l.db.all(sql`
248
+ SELECT child.* FROM tasks child
249
+ WHERE child.thread_id = ${t}
250
+ AND ${this.topLevelTaskPredicateSql()}
251
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
252
+ ORDER BY child.started_at ASC
253
+ `);for(let _ of c)r.has(_.id)||(r.add(_.id),i.push(_));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}if(s!==void 0&&n.length>1){let a=new Map;for(let l of i){let c=l.agent_id??"";a.has(c)||a.set(c,[]),a.get(c).push(l);}i=[];for(let l of a.values())l.sort((c,_)=>(_.started_at??"").localeCompare(c.started_at??"")),i.push(...l.slice(0,s));i.sort((l,c)=>(l.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let a=T(i);try{let l=eq(o.thread_id,t),c=e?and(l,eq(o.workspace_id,e)):l,_=a.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let k of _)n.has(k.id)||(n.add(k.id),r.push(k));}catch(l){throw new p("DB_ERROR","Failed to find all tasks for thread",l)}finally{a.close();}}return r}findTaskById(t,e,s){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let i=T(r);try{let a=and(eq(o.id,e),eq(o.thread_id,t)),l=s?and(a,eq(o.workspace_id,s)):a,c=i.db.select().from(o).where(l).limit(1).get();if(!c)continue;let _=i.db.select().from(o).where(eq(o.parent_task_id,c.id)).orderBy(asc(o.started_at)).all();return {task:c,children:_}}catch(a){throw new p("DB_ERROR","Failed to find task by id",a)}finally{i.close();}}}batchFetchTasks(t,e){let s=new Map;if(t.length===0)return s;let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let i=T(r);try{let a=i.db.all(sql`
128
254
  SELECT child.* FROM tasks child
129
255
  WHERE child.thread_id IN (${sql.join(t.map(l=>sql`${l}`),sql`, `)})
130
256
  AND ${this.topLevelTaskPredicateSql()}
131
257
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
132
258
  ORDER BY child.started_at ASC
133
- `);for(let l of i){let p=l.thread_id;s.has(p)||s.set(p,[]),s.get(p).push(l);}}catch(i){throw new u("DB_ERROR","Failed to batch fetch tasks",i)}finally{o.close();}}return s}updateThreadTitle(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=eq(c.id,t),o=s?and(r,eq(c.workspace_id,s)):r;if(!n.db.select({id:c.id}).from(c).where(o).limit(1).get())return;n.db.update(c).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(c.id,t)).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to update thread title",r)}finally{n.close();}}upsertThread(t,e){let s=this.openHandle(true);try{let n=e.workspaceId?this.validateWorkspaceId(s,e.workspaceId):null,r=new Date().toISOString();if(s.db.select({id:c.id,message_count:c.message_count}).from(c).where(eq(c.id,t)).limit(1).get()){let i={updated_at:r};e.title!==void 0&&(i.title=e.title),e.titleLocked!==void 0&&(i.title_locked=e.titleLocked?1:0),s.db.update(c).set(i).where(eq(c.id,t)).run();}else s.db.insert(c).values({id:t,platform:e.platform,workspace_id:n,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to upsert thread",n)}finally{s.close();}}ensureThread(t,e,s){let n=this.openHandle(true);try{let r=s?this.validateWorkspaceId(n,s):null,o=n.db.select({id:c.id,platform:c.platform,workspace_id:c.workspace_id}).from(c).where(eq(c.id,t)).limit(1).get();if(o){r&&!o.workspace_id&&n.db.update(c).set({workspace_id:r}).where(eq(c.id,t)).run();return}let i=new Date().toISOString();n.db.insert(c).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:i,updated_at:i}).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to ensure thread",r)}finally{n.close();}}saveUserMessage(t,e,s){if(!this.dbExists())return {firstMessage:false};let n=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:n.db.transaction(i=>{let p=i.select({message_count:c.message_count}).from(c).where(eq(c.id,t)).limit(1).get()?.message_count===0;return i.run(sql`
259
+ `);for(let l of a){let c=l.thread_id;s.has(c)||s.set(c,[]),s.get(c).push(l);}}catch(a){throw new p("DB_ERROR","Failed to batch fetch tasks",a)}finally{i.close();}}return s}updateThreadTitle(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=eq(u.id,t),i=s?and(r,eq(u.workspace_id,s)):r;if(!n.db.select({id:u.id}).from(u).where(i).limit(1).get())return;n.db.update(u).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(u.id,t)).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to update thread title",r)}finally{n.close();}}upsertThread(t,e){let s=this.openHandle(true);try{let n=e.workspaceId?this.validateWorkspaceId(s,e.workspaceId):null,r=new Date().toISOString();if(s.db.select({id:u.id,message_count:u.message_count}).from(u).where(eq(u.id,t)).limit(1).get()){let a={updated_at:r};e.title!==void 0&&(a.title=e.title),e.titleLocked!==void 0&&(a.title_locked=e.titleLocked?1:0),s.db.update(u).set(a).where(eq(u.id,t)).run();}else s.db.insert(u).values({id:t,platform:e.platform,workspace_id:n,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to upsert thread",n)}finally{s.close();}}ensureThread(t,e,s){let n=this.openHandle(true);try{let r=s?this.validateWorkspaceId(n,s):null,i=n.db.select({id:u.id,platform:u.platform,workspace_id:u.workspace_id}).from(u).where(eq(u.id,t)).limit(1).get();if(i){r&&!i.workspace_id&&n.db.update(u).set({workspace_id:r}).where(eq(u.id,t)).run();return}let a=new Date().toISOString();n.db.insert(u).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:a,updated_at:a}).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to ensure thread",r)}finally{n.close();}}saveUserMessage(t,e,s){if(!this.dbExists())return {firstMessage:false};let n=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:n.db.transaction(a=>{let c=a.select({message_count:u.message_count}).from(u).where(eq(u.id,t)).limit(1).get()?.message_count===0;return a.run(sql`
134
260
  UPDATE threads
135
261
  SET first_message = COALESCE(first_message, ${e}),
136
262
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
@@ -138,7 +264,8 @@ ${s.join(`
138
264
  message_count = message_count + 1,
139
265
  updated_at = ${r}
140
266
  WHERE id = ${t}
141
- `),p},{behavior:"immediate"})}}catch(r){throw r instanceof u?r:new u("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(c).set({last_message:e,updated_at:r}).where(eq(c.id,t)).run();}catch(r){throw r instanceof u?r:new u("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(c).set(n).where(eq(c.id,t)).run();}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to update thread",n)}finally{s.close();}}togglePin(t,e){let s=this.openHandle(true);try{let n=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),r=s.db.select({pinned:c.pinned,metadata:c.metadata}).from(c).where(n).get();if(!r)return null;let o=r.pinned?0:1,i=r.metadata?JSON.parse(r.metadata):{};if(o){let l=e?and(eq(c.pinned,1),eq(c.workspace_id,e)):eq(c.pinned,1),p=s.db.select({metadata:c.metadata}).from(c).where(l).all(),_=0;for(let k of p){let w=k.metadata?JSON.parse(k.metadata):{};typeof w.pinOrder=="number"&&w.pinOrder>_&&(_=w.pinOrder);}i.pinOrder=_+1;}else delete i.pinOrder;return s.db.update(c).set({pinned:o,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(n).run(),{pinned:!!o}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to toggle pin",n)}finally{s.close();}}reorderPins(t,e){let s=this.openHandle(true);try{for(let n=0;n<t.length;n++){let r=e?and(eq(c.id,t[n]),eq(c.workspace_id,e)):eq(c.id,t[n]),o=s.db.select({metadata:c.metadata}).from(c).where(r).get();if(!o)continue;let i=o.metadata?JSON.parse(o.metadata):{};i.pinOrder=n+1,s.db.update(c).set({metadata:JSON.stringify(i)}).where(r).run();}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to reorder pins",n)}finally{s.close();}}toggleStar(t,e){let s=this.openHandle(true);try{let n=e?and(eq(c.id,t),eq(c.workspace_id,e)):eq(c.id,t),r=s.db.select({starred:c.starred}).from(c).where(n).get();if(!r)return null;let o=r.starred?0:1;return s.db.update(c).set({starred:o}).where(n).run(),{starred:!!o}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to toggle star",n)}finally{s.close();}}};function fe(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
267
+ `),c},{behavior:"immediate"})}}catch(r){throw r instanceof p?r:new p("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(eq(u.id,t)).run();}catch(r){throw r instanceof p?r:new p("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(eq(u.id,t)).run();}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to update thread",n)}finally{s.close();}}togglePin(t,e){let s=this.openHandle(true);try{let n=e?and(eq(u.id,t),eq(u.workspace_id,e)):eq(u.id,t),r=s.db.select({pinned:u.pinned,metadata:u.metadata}).from(u).where(n).get();if(!r)return null;let i=r.pinned?0:1,a=r.metadata?JSON.parse(r.metadata):{};if(i){let l=e?and(eq(u.pinned,1),eq(u.workspace_id,e)):eq(u.pinned,1),c=s.db.select({metadata:u.metadata}).from(u).where(l).all(),_=0;for(let k of c){let w=k.metadata?JSON.parse(k.metadata):{};typeof w.pinOrder=="number"&&w.pinOrder>_&&(_=w.pinOrder);}a.pinOrder=_+1;}else delete a.pinOrder;return s.db.update(u).set({pinned:i,metadata:Object.keys(a).length>0?JSON.stringify(a):null}).where(n).run(),{pinned:!!i}}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to toggle pin",n)}finally{s.close();}}reorderPins(t,e){let s=this.openHandle(true);try{for(let n=0;n<t.length;n++){let r=e?and(eq(u.id,t[n]),eq(u.workspace_id,e)):eq(u.id,t[n]),i=s.db.select({metadata:u.metadata}).from(u).where(r).get();if(!i)continue;let a=i.metadata?JSON.parse(i.metadata):{};a.pinOrder=n+1,s.db.update(u).set({metadata:JSON.stringify(a)}).where(r).run();}}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to reorder pins",n)}finally{s.close();}}toggleStar(t,e){let s=this.openHandle(true);try{let n=e?and(eq(u.id,t),eq(u.workspace_id,e)):eq(u.id,t),r=s.db.select({starred:u.starred}).from(u).where(n).get();if(!r)return null;let i=r.starred?0:1;return s.db.update(u).set({starred:i}).where(n).run(),{starred:!!i}}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to toggle star",n)}finally{s.close();}}};function Ee(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
142
268
  `).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(`
143
- `).trim()}function ge(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(`
144
- `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=fe(t);}return t}var tt=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Z({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 {created:false}}return n.ensureThread(t,e,s),{created:true}}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),o=n.findTopLevelTasks(t),i=new Set(["done","completed","success"]);o=o.filter(_=>(!_.status||i.has(_.status))&&(!e?.currentTraceId||_.trace_id!==e.currentTraceId)),o=o.slice(0,s);let l=r?.platform??"cli",p=this.rowsToMessages(o);return {threadId:t,platform:l,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){let{firstMessage:r}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:r}}async saveAssistantMessage(t,e,s,n){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}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(),metadata:{caller_agent_id:s.caller_agent_id}});let n=ge(s.result);n&&e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:{agent_id:s.agent_id,task_id:s.id}});}return e}};var lt=class extends P{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new tt(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,s,n){}async afterAssistantMessage(t,e,s){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{let n=await this._provider.ensureThread(e.threadId,s,e.workspaceId),r=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,r.id,n.created||r.firstMessage,e);}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{let{id:r}=await this._provider.saveAssistantMessage(s,e.result,n);await this.afterAssistantMessage(s,r,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{lt as ConversationPlugin,et as FileLoggerPlugin,dt as SqliteTracingPlugin};
269
+ `).trim()}function Se(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(`
270
+ `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=Ee(t);}return t}var nt=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new st({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 {created:false}}return n.ensureThread(t,e,s),{created:true}}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),i=n.findTopLevelTasks(t,void 0,s),a=new Set(["queued","cancelled"]);i=i.filter(_=>(!_.status||!a.has(_.status))&&(!e?.currentTraceId||_.trace_id!==e.currentTraceId));let l=r?.platform??"cli",c=this.rowsToMessages(i);return {threadId:t,platform:l,messages:c,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){let{firstMessage:r}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:r}}async saveAssistantMessage(t,e,s,n){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}close(){}normalizeStatus(t){if(t&&!["success","completed","done"].includes(t)){if(["failed","error"].includes(t))return "failed";if(t==="running")return "running"}}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(),metadata:{caller_agent_id:s.caller_agent_id}});let n=Se(s.result),r=this.normalizeStatus(s.status);if(n||r==="running"||r==="failed"){let i={agent_id:s.agent_id,task_id:s.id};r&&(i.status=r),r==="failed"&&s.error&&(i.reason=s.error.split(`
271
+ `)[0].slice(0,200)),e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:i});}}return e}};var pt=class extends L{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new nt(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,s,n){}async afterAssistantMessage(t,e,s){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{let n=await this._provider.ensureThread(e.threadId,s,e.workspaceId),r=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,r.id,n.created||r.firstMessage,e);}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{let{id:r}=await this._provider.saveAssistantMessage(s,e.result,n);await this.afterAssistantMessage(s,r,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{pt as ConversationPlugin,rt as FileLoggerPlugin,ut as SqliteTracingPlugin};