@crewx/sdk 0.9.0-rc.32 → 0.9.0-rc.34

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
- import*as F from'path';import F__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import re,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,isNull,lt,or,like,asc,inArray,gte}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey}from'drizzle-orm/sqlite-core';var rt=(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 Yt=()=>fileURLToPath(import.meta.url),Jt=()=>F__default.dirname(Yt()),k=Jt();var q=class{detach(t){}};function xt(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 ft=class extends q{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 n=xt(e.timestamp),r=join(this.logsDir,`${n}_${e.traceId}.log`);this.logFiles.set(e.traceId,r);let o=`=== TASK LOG: ${e.traceId} ===
1
+ import*as B from'path';import B__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import re,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,isNull,lt,or,like,asc,inArray,gte}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey}from'drizzle-orm/sqlite-core';var ot=(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 Yt=()=>fileURLToPath(import.meta.url),Jt=()=>B__default.dirname(Yt()),k=Jt();var q=class{detach(t){}};function xt(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 ft=class extends q{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 n=xt(e.timestamp),r=join(this.logsDir,`${n}_${e.traceId}.log`);this.logFiles.set(e.traceId,r);let o=`=== TASK LOG: ${e.traceId} ===
2
2
  CrewX Version: ${this.version}
3
3
  Mode: ${e.mode}
4
4
  Agent: ${e.agentRef}
@@ -8,12 +8,12 @@ Message: ${e.message}
8
8
  `;writeFileSync(r,o,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",e=>{try{let n=this.logFiles.get(e.traceId);if(!n)return;let r=new Date().toISOString();appendFileSync(n,`[${r}] STDOUT: ${e.output}
9
9
  `,"utf8");}catch{}}),t.on("task:end",e=>{try{let n=this.logFiles.get(e.traceId);if(!n)return;let r=new Date().toLocaleString(),o=e.error?`failed: ${e.error.message}`:"completed successfully",i=`[${r}] INFO: Task ${o} in ${e.durationMs}ms
10
10
  [${r}] INFO: Process closed with exit code: ${e.error?1:0}
11
- `;appendFileSync(n,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function ee(d){let t=F.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 Ot(d){let t=ee(d);return createHash("sha256").update(t).digest("hex")}var Q=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(re.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=rt("better-sqlite3"),{drizzle:e}=rt("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"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:e(n),runRaw:(r,o=[])=>n.prepare(r).run(...o),close:()=>n.close()}}var Dt=new Set,oe={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 gt(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ie(d,t){if(t>0||!gt(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,o]of Object.entries(oe))n.has(r)||d.run(`ALTER TABLE tasks ADD COLUMN ${r} ${o}`);}var ae={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function de(d,t,e){if(!gt(d,"__drizzle_migrations")||!gt(d,"tasks"))return;let n=d.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(F__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=ae[i.tag];if(!a)continue;let c=F__default.join(t,`${i.tag}.sql`);if(!existsSync(c))continue;let l=readFileSync(c,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(r.has(u))continue;let h=d.all("PRAGMA table_info(tasks)"),m=new Set(h.map(T=>T.name));for(let[T,C]of Object.entries(a))m.has(T)||(d.run(`ALTER TABLE tasks ADD COLUMN ${T} ${C}`),m.add(T));}}function le(d,t,e){let n=d.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(F__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=F__default.join(t,`${i.tag}.sql`);if(!existsSync(a))continue;let c=readFileSync(a,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(r.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,h=[],m;for(;(m=u.exec(c))!==null;)h.push({table:m[1],column:m[2]});if(h.length===0||!c.split(/-->\s*statement-breakpoint/).map(N=>N.trim()).filter(Boolean).every(N=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(N)))continue;h.every(({table:N,column:L})=>d.all(`PRAGMA table_info("${N}")`).some(U=>U.name===L))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function ce(d){let{migrate:t}=rt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=rt("drizzle-orm"),n=[F__default.join(k,"../migrations"),F__default.join(k,"migrations"),F__default.join(k,"../../../../drizzle/migrations"),F__default.join(process.cwd(),"drizzle/migrations")],r=n.find(l=>existsSync(F__default.join(l,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
11
+ `;appendFileSync(n,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function ee(d){let t=B.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 Ot(d){let t=ee(d);return createHash("sha256").update(t).digest("hex")}var Q=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(re.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=ot("better-sqlite3"),{drizzle:e}=ot("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"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:e(n),runRaw:(r,o=[])=>n.prepare(r).run(...o),close:()=>n.close()}}var Dt=new Set,oe={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 gt(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ie(d,t){if(t>0||!gt(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,o]of Object.entries(oe))n.has(r)||d.run(`ALTER TABLE tasks ADD COLUMN ${r} ${o}`);}var ae={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function de(d,t,e){if(!gt(d,"__drizzle_migrations")||!gt(d,"tasks"))return;let n=d.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(B__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=ae[i.tag];if(!a)continue;let c=B__default.join(t,`${i.tag}.sql`);if(!existsSync(c))continue;let l=readFileSync(c,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(r.has(u))continue;let m=d.all("PRAGMA table_info(tasks)"),h=new Set(m.map(T=>T.name));for(let[T,C]of Object.entries(a))h.has(T)||(d.run(`ALTER TABLE tasks ADD COLUMN ${T} ${C}`),h.add(T));}}function le(d,t,e){let n=d.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(B__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=B__default.join(t,`${i.tag}.sql`);if(!existsSync(a))continue;let c=readFileSync(a,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(r.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],h;for(;(h=u.exec(c))!==null;)m.push({table:h[1],column:h[2]});if(m.length===0||!c.split(/-->\s*statement-breakpoint/).map(N=>N.trim()).filter(Boolean).every(N=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(N)))continue;m.every(({table:N,column:L})=>d.all(`PRAGMA table_info("${N}")`).some(U=>U.name===L))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function ce(d){let{migrate:t}=ot("drizzle-orm/better-sqlite3/migrator"),{sql:e}=ot("drizzle-orm"),n=[B__default.join(k,"../migrations"),B__default.join(k,"migrations"),B__default.join(k,"../../../../drizzle/migrations"),B__default.join(process.cwd(),"drizzle/migrations")],r=n.find(l=>existsSync(B__default.join(l,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
12
12
  ${n.join(`
13
- `)}`);let o=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ie(d,i),o?.cnt&&(le(d,r,e),de(d,r,e)),t(d,{migrationsFolder:r});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function it(d,t){Dt.has(t)||(ce(d),Dt.add(t));}var _=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);}};var Z=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 s=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 p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Z.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),idx_threads_ws_updated:index("idx_threads_ws_updated").on(d.workspace_id,d.updated_at),idx_threads_title:index("idx_threads_title").on(d.title)}));var ke=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>ke.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(()=>s.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(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},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)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},d=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(d.workspace_id,d.month)}));sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},d=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(d.workspace_id,sql`${d.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},d=>({pk:primaryKey({columns:[d.notification_id,d.user_id]})}));sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},d=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(d.workspace_id,d.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(d.workspace_id,d.created_at)}));function Ht(d){let t=d.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var j="2026-05-09",He="0.8.9-rc.13",G=10,X=parseInt(He.split("rc.")[1]),Be=new Set(["workflow","mcp"]),qt=600*1e3,_t=class extends Q{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let n=y(e);if(t)try{it(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(s).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:s.id,set:{pid:sql`COALESCE(excluded.pid, ${s.pid})`},setWhere:eq(s.status,"running")}).run();}catch(n){throw n instanceof _?n:new _("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
13
+ `)}`);let o=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ie(d,i),o?.cnt&&(le(d,r,e),de(d,r,e)),t(d,{migrationsFolder:r});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function at(d,t){Dt.has(t)||(ce(d),Dt.add(t));}var _=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);}};var Z=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 s=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 p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Z.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),idx_threads_ws_updated:index("idx_threads_ws_updated").on(d.workspace_id,d.updated_at),idx_threads_title:index("idx_threads_title").on(d.title)}));var ke=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>ke.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(()=>s.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(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},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)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},d=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(d.workspace_id,d.month)}));sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},d=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(d.workspace_id,sql`${d.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},d=>({pk:primaryKey({columns:[d.notification_id,d.user_id]})}));sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},d=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(d.workspace_id,d.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(d.workspace_id,d.created_at)}));function Ft(d){let t=d.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var j="2026-05-09",Fe="0.8.9-rc.13",G=10,X=parseInt(Fe.split("rc.")[1]),He=new Set(["workflow","mcp"]),qt=600*1e3,_t=class extends Q{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let n=y(e);if(t)try{at(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(s).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:s.id,set:{pid:sql`COALESCE(excluded.pid, ${s.pid})`},setWhere:eq(s.status,"running")}).run();}catch(n){throw n instanceof _?n:new _("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
14
14
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
15
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,n]);}catch(n){throw n instanceof _?n:new _("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({logs:s.logs}).from(s).where(eq(s.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(e),r.update(s).set({logs:JSON.stringify(i)}).where(eq(s.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).where(eq(s.status,"running")).orderBy(desc(s.started_at)).all()}catch(e){throw new _("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(s).orderBy(desc(s.started_at)).limit(100).all()}catch(e){throw new _("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(s).where(eq(s.id,t)).limit(1).get()??void 0}catch(n){throw new _("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:s.id,status:s.status,pid:s.pid}).from(s).where(eq(s.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(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(s.id,t),eq(s.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof _?n:new _("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(eq(s.status,"running")).all(),n=Date.now(),r=new Set,o=0;for(let i of e){if(i.pid){let l=!1;try{process.kill(i.pid,0),l=!0;}catch{}l||(t.db.update(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(s.id,i.id),eq(s.status,"running"))).run(),o++);continue}if(Be.has(i.platform??"cli"))continue;let a=`${i.id}:${i.run_epoch??0}`;r.add(a);let c=this.pidNullObservedSince.get(a);if(c===void 0){this.pidNullObservedSince.set(a,n);continue}n-c>=qt&&(t.db.update(s).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(s.id,i.id),eq(s.status,"running"))).run(),o++,this.pidNullObservedSince.delete(a));}for(let i of Array.from(this.pidNullObservedSince.keys()))r.has(i)||this.pidNullObservedSince.delete(i);return o}finally{t.close();}}reapRunningWorkflowTasks(t=qt){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let n=new Date(Date.now()-t).toISOString();return e.db.update(s).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(s.status,"running"),eq(s.platform,"workflow"),isNull(s.pid),lt(s.started_at,n))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=e?eq(s.workspace_id,e):void 0,a=i?and(eq(s.id,t),i):eq(s.id,t),c=o.db.select().from(s).where(a).limit(1).get()??void 0;if(!c){let l=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),u=i?and(l,i):l;c=o.db.select().from(s).where(u).orderBy(desc(s.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new _("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=e?and(eq(s.parent_task_id,t),eq(s.workspace_id,e)):eq(s.parent_task_id,t),l=a.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let u of l)r.has(u.id)||(r.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find child tasks",c)}finally{a.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
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,n]);}catch(n){throw n instanceof _?n:new _("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({logs:s.logs}).from(s).where(eq(s.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(e),r.update(s).set({logs:JSON.stringify(i)}).where(eq(s.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).where(eq(s.status,"running")).orderBy(desc(s.started_at)).all()}catch(e){throw new _("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(s).orderBy(desc(s.started_at)).limit(100).all()}catch(e){throw new _("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(s).where(eq(s.id,t)).limit(1).get()??void 0}catch(n){throw new _("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:s.id,status:s.status,pid:s.pid}).from(s).where(eq(s.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(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(s.id,t),eq(s.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof _?n:new _("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(eq(s.status,"running")).all(),n=Date.now(),r=new Set,o=0;for(let i of e){if(i.pid){let l=!1;try{process.kill(i.pid,0),l=!0;}catch{}l||(t.db.update(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(s.id,i.id),eq(s.status,"running"))).run(),o++);continue}if(He.has(i.platform??"cli"))continue;let a=`${i.id}:${i.run_epoch??0}`;r.add(a);let c=this.pidNullObservedSince.get(a);if(c===void 0){this.pidNullObservedSince.set(a,n);continue}n-c>=qt&&(t.db.update(s).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(s.id,i.id),eq(s.status,"running"))).run(),o++,this.pidNullObservedSince.delete(a));}for(let i of Array.from(this.pidNullObservedSince.keys()))r.has(i)||this.pidNullObservedSince.delete(i);return o}finally{t.close();}}reapRunningWorkflowTasks(t=qt){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let n=new Date(Date.now()-t).toISOString();return e.db.update(s).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(s.status,"running"),eq(s.platform,"workflow"),isNull(s.pid),lt(s.started_at,n))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=e?eq(s.workspace_id,e):void 0,a=i?and(eq(s.id,t),i):eq(s.id,t),c=o.db.select().from(s).where(a).limit(1).get()??void 0;if(!c){let l=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),u=i?and(l,i):l;c=o.db.select().from(s).where(u).orderBy(desc(s.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new _("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=e?and(eq(s.parent_task_id,t),eq(s.workspace_id,e)):eq(s.parent_task_id,t),l=a.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let u of l)r.has(u.id)||(r.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find child tasks",c)}finally{a.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
17
17
  SELECT
18
18
  COALESCE(workspace_id, 'unknown') AS workspace_id,
19
19
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -34,7 +34,7 @@ ${n.join(`
34
34
  FROM tasks
35
35
  GROUP BY workspace_id
36
36
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
37
- `)}catch(n){throw new _("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,o=0,i=0,a=0;for(let c of n){if(!existsSync(c))continue;let l=y(c);try{let u=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),h=e?and(u,eq(s.workspace_id,e)):u,m=l.db.select({id:s.id,input_tokens:s.input_tokens,output_tokens:s.output_tokens,cost_usd:s.cost_usd}).from(s).where(h).all();for(let T of m)r.has(T.id)||(r.add(T.id),o+=T.input_tokens??0,i+=T.output_tokens??0,a+=T.cost_usd??0);}catch(u){throw new _("DB_ERROR","Failed to get thread token usage",u)}finally{l.close();}}return {inputTokens:o,outputTokens:i,costUsd:a}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),l=e?and(c,eq(s.workspace_id,e)):c,u=a.db.select().from(s).where(l).orderBy(asc(s.started_at)).all();for(let h of u)r.has(h.id)||(r.add(h.id),o.push(h));}catch(c){throw new _("DB_ERROR","Failed to find tasks by thread",c)}finally{a.close();}}return o}parseWorkflowCardMetadata(t){if(!t)return {};try{let e=JSON.parse(t);return {kind:typeof e.kind=="string"?e.kind:void 0,workflowRunId:typeof e.workflowRunId=="string"?e.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}batchFetchWorkflowCards(t,e){let n=new Map;if(t.length===0)return n;let r=new Set(t),o=new Map,i=e?eq(s.workspace_id,e):void 0,a=(c,l)=>{if(!c)return;let u=o.get(c);if(u&&l.started_at<=u)return;let h=this.parseWorkflowCardMetadata(l.metadata);h.kind==="workflow_card"&&(o.set(c,l.started_at),n.set(c,{taskId:l.id,workflowRunId:h.workflowRunId,raw:l.result??void 0}));};for(let c of this.resolveDbPaths()){if(!existsSync(c))continue;let l=y(c);try{let u=and(inArray(s.thread_id,t),like(s.metadata,'%"kind":"workflow_card"%')),h=l.db.select({id:s.id,thread_id:s.thread_id,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(i?and(u,i):u).all();for(let C of h)a(C.thread_id,C);let m=and(isNull(s.thread_id),like(s.metadata,'%"kind":"workflow_card"%')),T=l.db.select({id:s.id,command:s.command,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(i?and(m,i):m).all();for(let C of T){let N=this.extractThreadIdFromCommand(C.command);!N||!r.has(N)||a(N,C);}}catch(u){throw new _("DB_ERROR","Failed to batch fetch workflow cards",u)}finally{l.close();}}return n}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(s.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(s.agent_id,r));let o=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;o&&n.push(inArray(s.status,o));let i=t.q??t.search;i&&n.push(like(s.prompt,`%${i}%`)),t.from&&n.push(gte(s.started_at,t.from)),t.to&&n.push(lt(s.started_at,t.to));let a=n.length>0?and(...n):void 0,c=e.db.select({count:sql`count(*)`}).from(s).where(a).get(),l=(t.sortDir??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at);return {rows:e.db.select().from(s).where(a).orderBy(l).limit(t.limit).offset(t.offset).all(),total:c?.count??0}}catch(n){throw new _("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
37
+ `)}catch(n){throw new _("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,o=0,i=0,a=0;for(let c of n){if(!existsSync(c))continue;let l=y(c);try{let u=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),m=e?and(u,eq(s.workspace_id,e)):u,h=l.db.select({id:s.id,input_tokens:s.input_tokens,output_tokens:s.output_tokens,cost_usd:s.cost_usd}).from(s).where(m).all();for(let T of h)r.has(T.id)||(r.add(T.id),o+=T.input_tokens??0,i+=T.output_tokens??0,a+=T.cost_usd??0);}catch(u){throw new _("DB_ERROR","Failed to get thread token usage",u)}finally{l.close();}}return {inputTokens:o,outputTokens:i,costUsd:a}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),l=e?and(c,eq(s.workspace_id,e)):c,u=a.db.select().from(s).where(l).orderBy(asc(s.started_at)).all();for(let m of u)r.has(m.id)||(r.add(m.id),o.push(m));}catch(c){throw new _("DB_ERROR","Failed to find tasks by thread",c)}finally{a.close();}}return o}parseWorkflowCardMetadata(t){if(!t)return {};try{let e=JSON.parse(t);return {kind:typeof e.kind=="string"?e.kind:void 0,workflowRunId:typeof e.workflowRunId=="string"?e.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}batchFetchWorkflowCards(t,e){let n=new Map;if(t.length===0)return n;let r=new Set(t),o=new Map,i=e?eq(s.workspace_id,e):void 0,a=(c,l)=>{if(!c)return;let u=o.get(c);if(u&&l.started_at<=u)return;let m=this.parseWorkflowCardMetadata(l.metadata);m.kind==="workflow_card"&&(o.set(c,l.started_at),n.set(c,{taskId:l.id,workflowRunId:m.workflowRunId,raw:l.result??void 0}));};for(let c of this.resolveDbPaths()){if(!existsSync(c))continue;let l=y(c);try{let u=and(inArray(s.thread_id,t),like(s.metadata,'%"kind":"workflow_card"%')),m=l.db.select({id:s.id,thread_id:s.thread_id,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(i?and(u,i):u).all();for(let C of m)a(C.thread_id,C);let h=and(isNull(s.thread_id),like(s.metadata,'%"kind":"workflow_card"%')),T=l.db.select({id:s.id,command:s.command,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(i?and(h,i):h).all();for(let C of T){let N=this.extractThreadIdFromCommand(C.command);!N||!r.has(N)||a(N,C);}}catch(u){throw new _("DB_ERROR","Failed to batch fetch workflow cards",u)}finally{l.close();}}return n}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(s.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(s.agent_id,r));let o=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;o&&n.push(inArray(s.status,o));let i=t.q??t.search;i&&n.push(like(s.prompt,`%${i}%`)),t.from&&n.push(gte(s.started_at,t.from)),t.to&&n.push(lt(s.started_at,t.to));let a=n.length>0?and(...n):void 0,c=e.db.select({count:sql`count(*)`}).from(s).where(a).get(),l=(t.sortDir??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at);return {rows:e.db.select().from(s).where(a).orderBy(l).limit(t.limit).offset(t.offset).all(),total:c?.count??0}}catch(n){throw new _("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
38
38
  SELECT
39
39
  t.agent_id,
40
40
  t.workspace_id,
@@ -172,7 +172,7 @@ ${n.join(`
172
172
  AND t.started_at < ${e}
173
173
  GROUP BY date(t.started_at), t.agent_id
174
174
  ORDER BY date(t.started_at) ASC
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(o){throw new _("DB_ERROR","Failed to get agent usage trend",o)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(s).where(and(eq(s.id,t),eq(s.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new _("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString(),i=n?and(eq(s.id,t),eq(s.status,"running"),eq(s.workspace_id,n)):and(eq(s.id,t),eq(s.status,"running"));r.db.update(s).set({status:"failed",error:e,completed_at:o}).where(i).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to mark task failed",o)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=e?and(like(s.prompt,`%${t}%`),eq(s.workspace_id,e)):like(s.prompt,`%${t}%`),l=a.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let u of l)r.has(u.id)||(r.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{a.close();}}return o}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=sql`
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(o){throw new _("DB_ERROR","Failed to get agent usage trend",o)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(s).where(and(eq(s.id,t),eq(s.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new _("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let e=this.openHandle(false);try{return e.db.select({id:s.id,thread_id:s.thread_id,status:s.status,result:s.result,error:s.error,started_at:s.started_at,completed_at:s.completed_at}).from(s).where(and(eq(s.agent_id,t.agentId),eq(s.workspace_id,t.workspaceId),sql`${s.metadata} IS NOT NULL AND json_valid(${s.metadata}) AND json_extract(${s.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(s.started_at)).limit(1).get()??null}catch(n){throw new _("DB_ERROR","Failed to find latest task by metadata",n)}finally{e.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString(),i=n?and(eq(s.id,t),eq(s.status,"running"),eq(s.workspace_id,n)):and(eq(s.id,t),eq(s.status,"running"));r.db.update(s).set({status:"failed",error:e,completed_at:o}).where(i).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to mark task failed",o)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=e?and(like(s.prompt,`%${t}%`),eq(s.workspace_id,e)):like(s.prompt,`%${t}%`),l=a.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let u of l)r.has(u.id)||(r.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{a.close();}}return o}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=sql`
176
176
  CASE
177
177
  WHEN ${s.model} LIKE 'claude-%' OR ${s.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
178
178
  WHEN ${s.model} LIKE 'gpt-%' OR ${s.model} LIKE 'codex-%' THEN 'codex'
@@ -244,7 +244,7 @@ ${n.join(`
244
244
  FROM ${s}
245
245
  ${a}
246
246
  GROUP BY ${s.model}
247
- `),l=new Map;for(let u of c){let h=Ht(u.model??""),m=l.get(h);m?(m.totalTasks+=u.total_tasks,m.inputTokens+=u.input_tokens,m.outputTokens+=u.output_tokens,m.cachedInputTokens+=u.cached_input_tokens,m.costUsd+=u.cost_usd,m.totalTokens+=u.input_tokens+u.output_tokens,m.activeDurationMs+=u.active_duration_ms??0,u.last_active_at&&(!m.lastActiveAt||u.last_active_at>m.lastActiveAt)&&(m.lastActiveAt=u.last_active_at)):l.set(h,{model:h,provider:u.provider,totalTasks:u.total_tasks,inputTokens:u.input_tokens,outputTokens:u.output_tokens,cachedInputTokens:u.cached_input_tokens,costUsd:u.cost_usd,totalTokens:u.input_tokens+u.output_tokens,activeDurationMs:u.active_duration_ms??0,lastActiveAt:u.last_active_at??null});}return Array.from(l.values()).sort((u,h)=>h.costUsd-u.costUsd)}catch(o){throw new _("DB_ERROR","Failed to get model usage",o)}finally{r.close();}}getTasksForReport(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=n?sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e} AND ${s.workspace_id} = ${n}`:sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e}`;return r.db.all(sql`
247
+ `),l=new Map;for(let u of c){let m=Ft(u.model??""),h=l.get(m);h?(h.totalTasks+=u.total_tasks,h.inputTokens+=u.input_tokens,h.outputTokens+=u.output_tokens,h.cachedInputTokens+=u.cached_input_tokens,h.costUsd+=u.cost_usd,h.totalTokens+=u.input_tokens+u.output_tokens,h.activeDurationMs+=u.active_duration_ms??0,u.last_active_at&&(!h.lastActiveAt||u.last_active_at>h.lastActiveAt)&&(h.lastActiveAt=u.last_active_at)):l.set(m,{model:m,provider:u.provider,totalTasks:u.total_tasks,inputTokens:u.input_tokens,outputTokens:u.output_tokens,cachedInputTokens:u.cached_input_tokens,costUsd:u.cost_usd,totalTokens:u.input_tokens+u.output_tokens,activeDurationMs:u.active_duration_ms??0,lastActiveAt:u.last_active_at??null});}return Array.from(l.values()).sort((u,m)=>m.costUsd-u.costUsd)}catch(o){throw new _("DB_ERROR","Failed to get model usage",o)}finally{r.close();}}getTasksForReport(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=n?sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e} AND ${s.workspace_id} = ${n}`:sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e}`;return r.db.all(sql`
248
248
  SELECT
249
249
  ${s.thread_id} AS thread_id,
250
250
  ${s.agent_id} AS agent_id,
@@ -255,11 +255,11 @@ ${n.join(`
255
255
  FROM ${s}
256
256
  ${o}
257
257
  ORDER BY ${s.started_at} ASC
258
- `).map(a=>({threadId:a.thread_id,agentId:a.agent_id,startedAt:a.started_at,status:a.status,error:a.error,exitCode:a.exit_code}))}catch(o){throw new _("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}};var Rt=class extends q{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 _t({dbPath:this.dbPath}),n=process.cwd(),o=existsSync(join(n,"crewx.yaml"))||existsSync(join(n,"crewx.yml"))?Ot(n):null,i=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let c=a.callerAgentId??null,l=a.parentTaskId??null,u=a.rootTraceId??a.traceId,h=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??o,callerAgentId:c,parentTaskId:l,traceId:u,metadata:h,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 c=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:c});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var ht=class extends Q{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let n=y(e);if(t)try{it(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:Z.id}).from(Z).where(eq(Z.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
258
+ `).map(a=>({threadId:a.thread_id,agentId:a.agent_id,startedAt:a.started_at,status:a.status,error:a.error,exitCode:a.exit_code}))}catch(o){throw new _("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}};var Rt=class extends q{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 _t({dbPath:this.dbPath}),n=process.cwd(),o=existsSync(join(n,"crewx.yaml"))||existsSync(join(n,"crewx.yml"))?Ot(n):null,i=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let c=a.callerAgentId??null,l=a.parentTaskId??null,u=a.rootTraceId??a.traceId,m=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??o,callerAgentId:c,parentTaskId:l,traceId:u,metadata:m,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 c=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:c});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var mt=class extends Q{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let n=y(e);if(t)try{at(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:Z.id}).from(Z).where(eq(Z.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
259
259
  SELECT 1 FROM tasks parent
260
260
  WHERE parent.id = ${t}.parent_task_id
261
261
  AND parent.thread_id = ${t}.thread_id
262
- )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let o of e){if(!existsSync(o))continue;let i=y(o);try{let a=t?eq(p.workspace_id,t):void 0,c=i.db.select().from(p).where(a).orderBy(desc(p.updated_at)).all();for(let l of c)n.has(l.id)||(n.add(l.id),r.push(l));}catch(a){throw new _("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return r}findThreadsByIdsOrTitles(t,e){if(t.length===0)return [];let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=or(inArray(p.id,t),inArray(p.title,t)),l=e?and(c,eq(p.workspace_id,e)):c,u=a.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let h of u)r.has(h.id)||(r.add(h.id),o.push(h));}catch(c){throw new _("DB_ERROR","Failed to find threads by ids or titles",c)}finally{a.close();}}return o}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=eq(p.id,t),a=e?and(i,eq(p.workspace_id,e)):i,c=o.db.select().from(p).where(a).limit(1).get()??void 0;if(c)return c}catch(i){throw new _("DB_ERROR","Failed to find thread by id",i)}finally{o.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=eq(p.id,t),a=e?and(i,eq(p.workspace_id,e)):i;if(o.db.select({id:p.id}).from(p).where(a).limit(1).get())return !0}catch(i){throw new _("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,o=0,i=0,a=0,c=0,l=new Set;for(let u of n){if(!existsSync(u))continue;let h=y(u);try{let m=h.db.get(sql`
262
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let o of e){if(!existsSync(o))continue;let i=y(o);try{let a=t?eq(p.workspace_id,t):void 0,c=i.db.select().from(p).where(a).orderBy(desc(p.updated_at)).all();for(let l of c)n.has(l.id)||(n.add(l.id),r.push(l));}catch(a){throw new _("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return r}findThreadsByIdsOrTitles(t,e){if(t.length===0)return [];let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=or(inArray(p.id,t),inArray(p.title,t)),l=e?and(c,eq(p.workspace_id,e)):c,u=a.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let m of u)r.has(m.id)||(r.add(m.id),o.push(m));}catch(c){throw new _("DB_ERROR","Failed to find threads by ids or titles",c)}finally{a.close();}}return o}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=eq(p.id,t),a=e?and(i,eq(p.workspace_id,e)):i,c=o.db.select().from(p).where(a).limit(1).get()??void 0;if(c)return c}catch(i){throw new _("DB_ERROR","Failed to find thread by id",i)}finally{o.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=y(r);try{let i=eq(p.id,t),a=e?and(i,eq(p.workspace_id,e)):i;if(o.db.select({id:p.id}).from(p).where(a).limit(1).get())return !0}catch(i){throw new _("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,o=0,i=0,a=0,c=0,l=new Set;for(let u of n){if(!existsSync(u))continue;let m=y(u);try{let h=m.db.get(sql`
263
263
  SELECT
264
264
  count(*) AS cnt,
265
265
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -270,13 +270,13 @@ ${n.join(`
270
270
  WHERE child.thread_id = ${t}
271
271
  AND ${this.topLevelTaskPredicateSql()}
272
272
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
273
- `);m&&(r+=m.cnt,o+=m.total_input,i+=m.total_output,a+=m.total_cached,c+=m.total_cost);let T=h.db.all(sql`
273
+ `);h&&(r+=h.cnt,o+=h.total_input,i+=h.total_output,a+=h.total_cached,c+=h.total_cost);let T=m.db.all(sql`
274
274
  SELECT DISTINCT child.agent_id FROM tasks child
275
275
  WHERE child.thread_id = ${t}
276
276
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
277
277
  AND ${this.topLevelTaskPredicateSql()}
278
278
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
279
- `);for(let C of T)l.add(C.agent_id);}catch(m){throw new _("DB_ERROR","Failed to aggregate task stats",m)}finally{h.close();}}return {taskCount:r,inputTokens:o,outputTokens:i,cachedInputTokens:a,costUsd:c,agentIds:Array.from(l)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),o=new Set,i=[];for(let a of r){if(!existsSync(a))continue;let c=y(a);try{let l;n!==void 0?l=c.db.all(sql`
279
+ `);for(let C of T)l.add(C.agent_id);}catch(h){throw new _("DB_ERROR","Failed to aggregate task stats",h)}finally{m.close();}}return {taskCount:r,inputTokens:o,outputTokens:i,cachedInputTokens:a,costUsd:c,agentIds:Array.from(l)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),o=new Set,i=[];for(let a of r){if(!existsSync(a))continue;let c=y(a);try{let l;n!==void 0?l=c.db.all(sql`
280
280
  SELECT * FROM (
281
281
  SELECT child.*,
282
282
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -293,7 +293,7 @@ ${n.join(`
293
293
  AND ${this.topLevelTaskPredicateSql()}
294
294
  ${e?sql`AND child.workspace_id = ${e}`:sql``}
295
295
  ORDER BY child.started_at ASC
296
- `);for(let u of l)o.has(u.id)||(o.add(u.id),i.push(u));}catch(l){throw new _("DB_ERROR","Failed to find top-level tasks",l)}finally{c.close();}}if(n!==void 0&&r.length>1){let a=new Map;for(let c of i){let l=c.agent_id??"";a.has(l)||a.set(l,[]),a.get(l).push(c);}i=[];for(let c of a.values())c.sort((l,u)=>(u.started_at??"").localeCompare(l.started_at??"")),i.push(...c.slice(0,n));i.sort((c,l)=>(c.started_at??"").localeCompare(l.started_at??""));}return i}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=eq(s.thread_id,t),l=e?and(c,eq(s.workspace_id,e)):c,u=a.db.select().from(s).where(l).orderBy(asc(s.started_at)).all();for(let h of u)r.has(h.id)||(r.add(h.id),o.push(h));}catch(c){throw new _("DB_ERROR","Failed to find all tasks for thread",c)}finally{a.close();}}return o}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let i=y(o);try{let a=and(eq(s.id,e),eq(s.thread_id,t)),c=n?and(a,eq(s.workspace_id,n)):a,l=i.db.select().from(s).where(c).limit(1).get();if(!l)continue;let u=i.db.select().from(s).where(eq(s.parent_task_id,l.id)).orderBy(asc(s.started_at)).all();return {task:l,children:u}}catch(a){throw new _("DB_ERROR","Failed to find task by id",a)}finally{i.close();}}}batchFetchTasksQuery(t,e){return sql`
296
+ `);for(let u of l)o.has(u.id)||(o.add(u.id),i.push(u));}catch(l){throw new _("DB_ERROR","Failed to find top-level tasks",l)}finally{c.close();}}if(n!==void 0&&r.length>1){let a=new Map;for(let c of i){let l=c.agent_id??"";a.has(l)||a.set(l,[]),a.get(l).push(c);}i=[];for(let c of a.values())c.sort((l,u)=>(u.started_at??"").localeCompare(l.started_at??"")),i.push(...c.slice(0,n));i.sort((c,l)=>(c.started_at??"").localeCompare(l.started_at??""));}return i}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=y(i);try{let c=eq(s.thread_id,t),l=e?and(c,eq(s.workspace_id,e)):c,u=a.db.select().from(s).where(l).orderBy(asc(s.started_at)).all();for(let m of u)r.has(m.id)||(r.add(m.id),o.push(m));}catch(c){throw new _("DB_ERROR","Failed to find all tasks for thread",c)}finally{a.close();}}return o}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let i=y(o);try{let a=and(eq(s.id,e),eq(s.thread_id,t)),c=n?and(a,eq(s.workspace_id,n)):a,l=i.db.select().from(s).where(c).limit(1).get();if(!l)continue;let u=i.db.select().from(s).where(eq(s.parent_task_id,l.id)).orderBy(asc(s.started_at)).all();return {task:l,children:u}}catch(a){throw new _("DB_ERROR","Failed to find task by id",a)}finally{i.close();}}}batchFetchTasksQuery(t,e){return sql`
297
297
  SELECT child.id, child.thread_id, child.agent_id, child.status,
298
298
  child.parent_task_id, child.started_at, child.completed_at,
299
299
  child.duration_ms, child.input_tokens, child.output_tokens,
@@ -311,8 +311,8 @@ ${n.join(`
311
311
  message_count = message_count + 1,
312
312
  updated_at = ${o}
313
313
  WHERE id = ${t}
314
- `),l},{behavior:"immediate"})}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save assistant message",o)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!o)return null;let i=o.pinned?0:1,a=o.metadata?JSON.parse(o.metadata):{};if(i){let c=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),l=n.db.select({metadata:p.metadata}).from(p).where(c).all(),u=null;for(let h of l){let m=h.metadata?JSON.parse(h.metadata):{};typeof m.pinOrder=="number"&&(u===null||m.pinOrder<u)&&(u=m.pinOrder);}a.pinOrder=u===null?0:u-1;}else delete a.pinOrder;return n.db.update(p).set({pinned:i,metadata:Object.keys(a).length>0?JSON.stringify(a):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let o=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),i=n.db.select({metadata:p.metadata}).from(p).where(o).get();if(!i)continue;let a=i.metadata?JSON.parse(i.metadata):{};a.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(a)}).where(o).run();}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({starred:p.starred}).from(p).where(r).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(p).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let a=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return i.db.transaction(l=>{let u=l.select({metadata:p.metadata}).from(p).where(a).get();if(!u)return null;let h=u.metadata?JSON.parse(u.metadata):{},m=h.overdrive??{},T=r?.defaultTurns??m.defaultTurns??3,C=r?.updatedBy??"ui",N=new Date().toISOString(),L,P,U,tt;switch(n){case "enable-count":{let et=r?.turns??T,nt=r?.consumeCurrent?Math.max(et-1,0):et;L=nt>0?"count":"off",P=nt,U=!0,tt="count";break}case "enable-latch":{L="latch",P=0,U=!0,tt="latch";break}case "disable":{L="off",P=0,U=!1;break}default:{let et=m.state??"off",nt=typeof m.remaining=="number"?m.remaining:0;if(et==="count"&&nt>0){let Tt=nt-1;Tt<=0?(L="off",P=0):(L="count",P=Tt),U=!0,tt="count";}else et==="latch"?(L="latch",P=0,U=!0,tt="latch"):(L="off",P=0,U=!1);break}}return h.overdrive={state:L,remaining:P,defaultTurns:T,updatedAt:N,updatedBy:C},l.update(p).set({metadata:JSON.stringify(h),updated_at:N}).where(a).run(),{applied:U,appliedMode:tt,state:L,remaining:P}},{behavior:"immediate"})}catch(a){throw a instanceof _?a:new _("DB_ERROR","Failed to resolve overdrive",a)}finally{i.close();}}};function Ye(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
314
+ `),l},{behavior:"immediate"})}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save assistant message",o)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!o)return null;let i=o.pinned?0:1,a=o.metadata?JSON.parse(o.metadata):{};if(i){let c=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),l=n.db.select({metadata:p.metadata}).from(p).where(c).all(),u=null;for(let m of l){let h=m.metadata?JSON.parse(m.metadata):{};typeof h.pinOrder=="number"&&(u===null||h.pinOrder<u)&&(u=h.pinOrder);}a.pinOrder=u===null?0:u-1;}else delete a.pinOrder;return n.db.update(p).set({pinned:i,metadata:Object.keys(a).length>0?JSON.stringify(a):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let o=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),i=n.db.select({metadata:p.metadata}).from(p).where(o).get();if(!i)continue;let a=i.metadata?JSON.parse(i.metadata):{};a.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(a)}).where(o).run();}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({starred:p.starred}).from(p).where(r).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(p).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let a=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return i.db.transaction(l=>{let u=l.select({metadata:p.metadata}).from(p).where(a).get();if(!u)return null;let m=u.metadata?JSON.parse(u.metadata):{},h=m.overdrive??{},T=r?.defaultTurns??h.defaultTurns??3,C=r?.updatedBy??"ui",N=new Date().toISOString(),L,P,U,tt;switch(n){case "enable-count":{let et=r?.turns??T,nt=r?.consumeCurrent?Math.max(et-1,0):et;L=nt>0?"count":"off",P=nt,U=!0,tt="count";break}case "enable-latch":{L="latch",P=0,U=!0,tt="latch";break}case "disable":{L="off",P=0,U=!1;break}default:{let et=h.state??"off",nt=typeof h.remaining=="number"?h.remaining:0;if(et==="count"&&nt>0){let Tt=nt-1;Tt<=0?(L="off",P=0):(L="count",P=Tt),U=!0,tt="count";}else et==="latch"?(L="latch",P=0,U=!0,tt="latch"):(L="off",P=0,U=!1);break}}return m.overdrive={state:L,remaining:P,defaultTurns:T,updatedAt:N,updatedBy:C},l.update(p).set({metadata:JSON.stringify(m),updated_at:N}).where(a).run(),{applied:U,appliedMode:tt,state:L,remaining:P}},{behavior:"immediate"})}catch(a){throw a instanceof _?a:new _("DB_ERROR","Failed to resolve overdrive",a)}finally{i.close();}}};function Ye(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
315
315
  `).filter(r=>!(r.startsWith("Loaded ")&&r.includes("layouts from")||r.includes("[dotenv@")||r.includes("[Nest]")&&r.includes("DEBUG")||r.startsWith("Registered custom layout:")||r.startsWith("Updated custom layout:"))).join(`
316
316
  `).trim()}function Je(d){if(!d)return "";let t=d;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(n=>n?.type==="text"&&n?.text).map(n=>n.text).join(`
317
- `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=Ye(t);}return t}var mt=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new ht({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,n){let r=this.getThreadRepo(),o=r.findThreadById(t);if(o){if(o.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${o.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return r.ensureThread(t,e,n),{created:true}}async fetchHistory(t,e){let n=e?.limit??100,r=this.getThreadRepo(),o=r.findThreadById(t),i=r.findTopLevelTasks(t,void 0,n),a=new Set(["queued","cancelled"]);i=i.filter(u=>(!u.status||!a.has(u.status))&&(!e?.currentTraceId||u.trace_id!==e.currentTraceId));let c=o?.platform??"cli",l=this.rowsToMessages(i);return {threadId:t,platform:c,messages:l,metadata:{title:o?.title??void 0,firstMessage:o?.first_message??void 0,lastMessage:o?.last_message??void 0,messageCount:o?.message_count??0,updatedAt:o?.updated_at?new Date(o.updated_at).getTime():void 0}}}async saveUserMessage(t,e,n,r){let{firstMessage:o}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:o}}async saveAssistantMessage(t,e,n,r){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 n of t){n.prompt&&e.push({id:`${n.id}-user`,text:n.prompt,isAssistant:false,timestamp:new Date(n.started_at).getTime(),metadata:{caller_agent_id:n.caller_agent_id}});let r=Je(n.result),o=this.normalizeStatus(n.status);if(r||o==="running"||o==="failed"){let i={agent_id:n.agent_id,task_id:n.id};o&&(i.status=o),o==="failed"&&n.error&&(i.reason=n.error.split(`
318
- `)[0].slice(0,200)),e.push({id:`${n.id}-assistant`,text:r,isAssistant:true,timestamp:new Date(n.started_at).getTime(),metadata:i});}}return e}};var yt=class extends q{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new mt(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,n,r){}async afterAssistantMessage(t,e,n){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let n=e.platform??"cli";try{let r=await this._provider.ensureThread(e.threadId,n,e.workspaceId),o=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,o.id,r.created||o.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let n=e.metadata?.threadId;if(!n)return;let r=e.agentRef?.replace(/^@/,"")??"";try{let{id:o}=await this._provider.saveAssistantMessage(n,e.result,r);await this.afterAssistantMessage(n,o,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{yt as ConversationPlugin,ft as FileLoggerPlugin,Rt as SqliteTracingPlugin};
317
+ `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=Ye(t);}return t}var ht=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new mt({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,n){let r=this.getThreadRepo(),o=r.findThreadById(t);if(o){if(o.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${o.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return r.ensureThread(t,e,n),{created:true}}async fetchHistory(t,e){let n=e?.limit??100,r=this.getThreadRepo(),o=r.findThreadById(t),i=r.findTopLevelTasks(t,void 0,n),a=new Set(["queued","cancelled"]);i=i.filter(u=>(!u.status||!a.has(u.status))&&(!e?.currentTraceId||u.trace_id!==e.currentTraceId));let c=o?.platform??"cli",l=this.rowsToMessages(i);return {threadId:t,platform:c,messages:l,metadata:{title:o?.title??void 0,firstMessage:o?.first_message??void 0,lastMessage:o?.last_message??void 0,messageCount:o?.message_count??0,updatedAt:o?.updated_at?new Date(o.updated_at).getTime():void 0}}}async saveUserMessage(t,e,n,r){let{firstMessage:o}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:o}}async saveAssistantMessage(t,e,n,r){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 n of t){n.prompt&&e.push({id:`${n.id}-user`,text:n.prompt,isAssistant:false,timestamp:new Date(n.started_at).getTime(),metadata:{caller_agent_id:n.caller_agent_id}});let r=Je(n.result),o=this.normalizeStatus(n.status);if(r||o==="running"||o==="failed"){let i={agent_id:n.agent_id,task_id:n.id};o&&(i.status=o),o==="failed"&&n.error&&(i.reason=n.error.split(`
318
+ `)[0].slice(0,200)),e.push({id:`${n.id}-assistant`,text:r,isAssistant:true,timestamp:new Date(n.started_at).getTime(),metadata:i});}}return e}};var yt=class extends q{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new ht(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,n,r){}async afterAssistantMessage(t,e,n){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let n=e.platform??"cli";try{let r=await this._provider.ensureThread(e.threadId,n,e.workspaceId),o=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,o.id,r.created||o.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let n=e.metadata?.threadId;if(!n)return;let r=e.agentRef?.replace(/^@/,"")??"";try{let{id:o}=await this._provider.saveAssistantMessage(n,e.result,r);await this.afterAssistantMessage(n,o,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{yt as ConversationPlugin,ft as FileLoggerPlugin,Rt as SqliteTracingPlugin};