@crewx/sdk 0.9.0-rc.65 → 0.9.0-rc.66

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,52 +1,59 @@
1
- import*as V from'path';import V__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 as lt$1,or,notLike,like,asc,inArray,gte,isNotNull,ne}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey,check}from'drizzle-orm/sqlite-core';var wt=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var fe=()=>fileURLToPath(import.meta.url),ge=()=>V__default.dirname(fe()),k=ge();var et=class{detach(t){}};function Ft(o){let t=n=>String(n).padStart(2,"0");return `${o.getFullYear()}${t(o.getMonth()+1)}${t(o.getDate())}T${t(o.getHours())}${t(o.getMinutes())}${t(o.getSeconds())}`}function $t(o){let t=o.toISOString();return `${t.slice(0,10)} ${t.slice(11,19)} UTC`}var Dt=class extends et{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",n=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let s=Ft(n.timestamp),r=join(this.logsDir,`${s}_${n.traceId}.log`);this.logFiles.set(n.traceId,r);let i=`=== TASK LOG: ${n.traceId} ===
1
+ import*as Q from'path';import Q__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import Ie,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,isNull,lt,or,notLike,like,asc,inArray,gte,isNotNull,ne}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey}from'drizzle-orm/sqlite-core';var Tt=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var Ne=()=>fileURLToPath(import.meta.url),xe=()=>Q__default.dirname(Ne()),k=xe();var st=class{detach(t){}};function Gt(r){let t=e=>String(e).padStart(2,"0");return `${r.getFullYear()}${t(r.getMonth()+1)}${t(r.getDate())}T${t(r.getHours())}${t(r.getMinutes())}${t(r.getSeconds())}`}function It(r){let t=r.toISOString();return `${t.slice(0,10)} ${t.slice(11,19)} UTC`}var Pt=class extends st{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=Gt(e.timestamp),o=join(this.logsDir,`${s}_${e.traceId}.log`);this.logFiles.set(e.traceId,o);let i=`=== TASK LOG: ${e.traceId} ===
2
2
  CrewX Version: ${this.version}
3
- Mode: ${n.mode}
4
- Agent: ${n.agentRef}
5
- Started: ${$t(n.timestamp)}
6
- Message: ${n.message}
3
+ Mode: ${e.mode}
4
+ Agent: ${e.agentRef}
5
+ Started: ${It(e.timestamp)}
6
+ Message: ${e.message}
7
7
 
8
- `;writeFileSync(r,i,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",n=>{try{let s=this.logFiles.get(n.traceId);if(!s)return;let r=new Date().toISOString();appendFileSync(s,`[${r}] STDOUT: ${n.output}
9
- `,"utf8");}catch{}}),t.on("task:end",n=>{try{let s=this.logFiles.get(n.traceId);if(!s)return;let r=$t(new Date),i=n.error?`failed: ${n.error.message}`:"completed successfully",a=`[${r}] INFO: Task ${i} in ${n.durationMs}ms
10
- [${r}] INFO: Process closed with exit code: ${n.error?1:0}
11
- `;appendFileSync(s,a,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(t){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};function ye(o){let t=V.resolve(o);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(n,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Gt(o){let t=ye(o);return createHash("sha256").update(t).digest("hex")}var lt=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 x(o){let t=wt("better-sqlite3"),{drizzle:n}=wt("drizzle-orm/better-sqlite3"),s=new t(o);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400"),s.exec("PRAGMA optimize"),{db:n(s),runRaw:(r,i=[])=>s.prepare(r).run(...i),close:()=>s.close()}}var Jt=new Set,xe={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(o,t){return (o.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Ne(o,t){if(t>0||!Ot(o,"tasks"))return;let n=o.all("PRAGMA table_info(tasks)"),s=new Set(n.map(r=>r.name));for(let[r,i]of Object.entries(xe))s.has(r)||o.run(`ALTER TABLE tasks ADD COLUMN ${r} ${i}`);}var Ae={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"}};function be(o,t,n){if(!Ot(o,"__drizzle_migrations")||!Ot(o,"tasks"))return;let s=o.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(s.map(a=>a.hash)),i=JSON.parse(readFileSync(V__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of i.entries){let d=Ae[a.tag];if(!d)continue;let u=V__default.join(t,`${a.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(r.has(l))continue;let h=o.all("PRAGMA table_info(tasks)"),m=new Set(h.map(w=>w.name));for(let[w,O]of Object.entries(d))m.has(w)||(o.run(`ALTER TABLE tasks ADD COLUMN ${w} ${O}`),m.add(w));}}function Ce(o,t,n){let s=o.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(s.map(a=>a.hash)),i=JSON.parse(readFileSync(V__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of i.entries){let d=V__default.join(t,`${a.tag}.sql`);if(!existsSync(d))continue;let u=readFileSync(d,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let l=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,h=[],m;for(;(m=l.exec(u))!==null;)h.push({table:m[1],column:m[2]});if(h.length===0||!u.split(/-->\s*statement-breakpoint/).map(I=>I.trim()).filter(Boolean).every(I=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(I)))continue;h.every(({table:I,column:B})=>o.all(`PRAGMA table_info("${I}")`).some(Y=>Y.name===B))&&o.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${a.when})`);}}function ve(o){let{migrate:t}=wt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=wt("drizzle-orm"),s=[V__default.join(k,"../migrations"),V__default.join(k,"migrations"),V__default.join(k,"../../../../drizzle/migrations"),V__default.join(process.cwd(),"drizzle/migrations")],r=s.find(c=>existsSync(V__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
8
+ `;writeFileSync(o,i,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let o=new Date().toISOString();appendFileSync(s,`[${o}] STDOUT: ${e.output}
9
+ `,"utf8");}catch{}}),t.on("task:end",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let o=It(new Date),i=e.error?`failed: ${e.error.message}`:"completed successfully",a=`[${o}] INFO: Task ${i} in ${e.durationMs}ms
10
+ [${o}] INFO: Process closed with exit code: ${e.error?1:0}
11
+ `;appendFileSync(s,a,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function De(r){let t=Q.resolve(r);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 Vt(r){let t=De(r);return createHash("sha256").update(t).digest("hex")}var rt=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ie.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var Me=32*1024*1024;function b(r){let t=Tt("better-sqlite3"),{drizzle:e}=Tt("drizzle-orm/better-sqlite3"),s=new t(r);return s.exec("PRAGMA journal_mode = WAL"),s.exec(`PRAGMA journal_size_limit = ${Me}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400"),s.exec("PRAGMA optimize"),{db:e(s),runRaw:(o,i=[])=>s.prepare(o).run(...i),close:()=>s.close()}}var Qt=new Set,Ue={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function Mt(r,t){return (r.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function je(r,t){if(t>0||!Mt(r,"tasks"))return;let e=r.all("PRAGMA table_info(tasks)"),s=new Set(e.map(o=>o.name));for(let[o,i]of Object.entries(Ue))s.has(o)||r.run(`ALTER TABLE tasks ADD COLUMN ${o} ${i}`);}var qe={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"}};function Be(r,t,e){if(!Mt(r,"__drizzle_migrations")||!Mt(r,"tasks"))return;let s=r.all(e`SELECT hash FROM __drizzle_migrations`),o=new Set(s.map(a=>a.hash)),i=JSON.parse(readFileSync(Q__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of i.entries){let d=qe[a.tag];if(!d)continue;let u=Q__default.join(t,`${a.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(o.has(l))continue;let g=r.all("PRAGMA table_info(tasks)"),f=new Set(g.map(w=>w.name));for(let[w,$]of Object.entries(d))f.has(w)||(r.run(`ALTER TABLE tasks ADD COLUMN ${w} ${$}`),f.add(w));}}function He(r,t,e){let s=r.all(e`SELECT hash FROM __drizzle_migrations`),o=new Set(s.map(a=>a.hash)),i=JSON.parse(readFileSync(Q__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of i.entries){let d=Q__default.join(t,`${a.tag}.sql`);if(!existsSync(d))continue;let u=readFileSync(d,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(o.has(c))continue;let l=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,g=[],f;for(;(f=l.exec(u))!==null;)g.push({table:f[1],column:f[2]});if(g.length===0||!u.split(/-->\s*statement-breakpoint/).map(O=>O.trim()).filter(Boolean).every(O=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(O)))continue;g.every(({table:O,column:q})=>r.all(`PRAGMA table_info("${O}")`).some(V=>V.name===q))&&r.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${a.when})`);}}function Fe(r){let{migrate:t}=Tt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Tt("drizzle-orm"),s=[Q__default.join(k,"../migrations"),Q__default.join(k,"migrations"),Q__default.join(k,"../../../../drizzle/migrations"),Q__default.join(process.cwd(),"drizzle/migrations")],o=s.find(c=>existsSync(Q__default.join(c,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
12
12
  ${s.join(`
13
- `)}`);let i=o.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;i?.cnt&&(a=o.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ne(o,a),i?.cnt&&(Ce(o,r,n),be(o,r,n)),t(o,{migrationsFolder:r});let u=(o.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(u>0){let c=i?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function yt(o,t){Jt.has(t)||(ve(o),Jt.add(t));}var p=class extends Error{code;cause;constructor(t,n,s){super(n),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var _t=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 e=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)},o=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(o.agent_id),idx_tasks_status:index("idx_tasks_status").on(o.status),idx_tasks_started_at:index("idx_tasks_started_at").on(o.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(o.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(o.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(o.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(o.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(o.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(o.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(o.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(o.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(o.workspace_id,o.started_at)}));var _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>_t.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)},o=>({idx_threads_updated_at:index("idx_threads_updated_at").on(o.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(o.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(o.workspace_id,o.updated_at),idx_threads_title:index("idx_threads_title").on(o.title)}));var je=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>je.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")},o=>({idx_spans_task_id:index("idx_spans_task_id").on(o.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(o.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.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()},o=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(o.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(o.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(o.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},o=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(o.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(o.thread_id,o.seq),uniq_thread_boxes_thread_seq:unique().on(o.thread_id,o.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")},o=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(o.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(o.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(o.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(o.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")},o=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(o.provider,o.account_ref,o.limit_window,o.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(o.limit_window,o.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(o.provider,o.limit_window,o.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")},o=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(o.workspace_id,o.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")},o=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(o.workspace_id,sql`${o.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},o=>({pk:primaryKey({columns:[o.notification_id,o.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()},o=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(o.workspace_id,o.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(o.workspace_id,o.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},o=>({idCheck:check("ui_instances_id_ck",sql`length(${o.id}) BETWEEN 5 AND 128 AND ${o.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${o.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${o.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${o.definition_hash}) = 64 AND ${o.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${o.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${o.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${o.domain_ref_json}) AND json_type(${o.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${o.state_json}) AND json_type(${o.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${o.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${o.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${o.granted_capabilities_json}) AND json_type(${o.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${o.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${o.updated_at} >= ${o.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(o.workspace_id,o.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},o=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${o.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${o.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${o.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${o.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${o.actor_json}) AND json_type(${o.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${o.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${o.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${o.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${o.after_revision} IS NULL OR ${o.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${o.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${o.outcome} IS NULL OR ${o.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${o.input_json}) AND json_type(${o.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${o.result_json} IS NULL OR (json_valid(${o.result_json}) AND json_type(${o.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${o.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${o.settled_at} IS NULL OR ${o.settled_at} >= ${o.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
14
- (${o.status} = 'requested' AND ${o.after_revision} IS NULL AND ${o.outcome} IS NULL AND ${o.settled_at} IS NULL)
13
+ `)}`);let i=r.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;i?.cnt&&(a=r.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),je(r,a),i?.cnt&&(He(r,o,e),Be(r,o,e)),t(r,{migrationsFolder:o});let u=(r.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(u>0){let c=i?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function pt(r,t){Qt.has(t)||(Fe(r),Qt.add(t));}var _=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 gt=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 n=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"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),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)},r=>({log_storage_check:check("tasks_log_storage_ck",sql`${r.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(r.agent_id),idx_tasks_status:index("idx_tasks_status").on(r.status),idx_tasks_started_at:index("idx_tasks_started_at").on(r.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(r.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(r.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(r.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(r.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(r.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(r.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(r.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(r.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(r.workspace_id,r.started_at)}));var W=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>n.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},r=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(r.task_id,r.seq)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>gt.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)},r=>({idx_threads_updated_at:index("idx_threads_updated_at").on(r.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(r.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(r.workspace_id,r.updated_at),idx_threads_title:index("idx_threads_title").on(r.title)}));var en=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>n.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>en.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")},r=>({idx_spans_task_id:index("idx_spans_task_id").on(r.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(r.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>n.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()},r=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(r.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(r.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(r.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()},r=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(r.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(r.thread_id,r.seq),uniq_thread_boxes_thread_seq:unique().on(r.thread_id,r.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")},r=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(r.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(r.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(r.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(r.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")},r=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(r.provider,r.account_ref,r.limit_window,r.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(r.limit_window,r.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(r.provider,r.limit_window,r.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")},r=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(r.workspace_id,r.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")},r=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(r.workspace_id,sql`${r.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},r=>({pk:primaryKey({columns:[r.notification_id,r.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()},r=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(r.workspace_id,r.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(r.workspace_id,r.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},r=>({idCheck:check("ui_instances_id_ck",sql`length(${r.id}) BETWEEN 5 AND 128 AND ${r.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${r.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${r.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${r.definition_hash}) = 64 AND ${r.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${r.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${r.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${r.domain_ref_json}) AND json_type(${r.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${r.state_json}) AND json_type(${r.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${r.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${r.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${r.granted_capabilities_json}) AND json_type(${r.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${r.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${r.updated_at} >= ${r.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(r.workspace_id,r.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},r=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${r.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${r.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${r.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${r.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${r.actor_json}) AND json_type(${r.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${r.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${r.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${r.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${r.after_revision} IS NULL OR ${r.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${r.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${r.outcome} IS NULL OR ${r.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${r.input_json}) AND json_type(${r.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${r.result_json} IS NULL OR (json_valid(${r.result_json}) AND json_type(${r.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${r.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${r.settled_at} IS NULL OR ${r.settled_at} >= ${r.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
14
+ (${r.status} = 'requested' AND ${r.after_revision} IS NULL AND ${r.outcome} IS NULL AND ${r.settled_at} IS NULL)
15
15
  OR
16
- (${o.status} = 'settled' AND ${o.after_revision} IS NOT NULL AND ${o.outcome} IS NOT NULL AND ${o.settled_at} IS NOT NULL)
17
- )`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(o.instance_id,o.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(o.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(o.requested_at)}));var oe=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},o=>({idCheck:check("projects_id_ck",sql`${o.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${o.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${o.stages_json}) AND json_type(${o.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${o.stage_index} >= 1`)}));sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>oe.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},o=>({idCheck:check("project_criteria_id_ck",sql`${o.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${o.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${o.evidence_json}) AND json_type(${o.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(o.project_id,o.position)}));sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>oe.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},o=>({idCheck:check("project_events_id_ck",sql`${o.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${o.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${o.payload_json}) AND json_type(${o.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(o.project_id,o.seq)}));function ie(o){let t=o.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let n=t.lastIndexOf("/");return n>=0&&(t=t.slice(n+1)),t=t.replace(/-\d{8}$/,""),t}var rt="2026-05-09",pn="0.8.9-rc.13",ot=10,it=parseInt(pn.split("rc.")[1]);function ae(){let o=sql`
16
+ (${r.status} = 'settled' AND ${r.after_revision} IS NOT NULL AND ${r.outcome} IS NOT NULL AND ${r.settled_at} IS NOT NULL)
17
+ )`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(r.instance_id,r.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(r.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(r.requested_at)}));var le=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},r=>({idCheck:check("projects_id_ck",sql`${r.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${r.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${r.stages_json}) AND json_type(${r.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${r.stage_index} >= 1`)}));sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>le.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},r=>({idCheck:check("project_criteria_id_ck",sql`${r.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${r.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${r.evidence_json}) AND json_type(${r.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(r.project_id,r.position)}));sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>le.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},r=>({idCheck:check("project_events_id_ck",sql`${r.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${r.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${r.payload_json}) AND json_type(${r.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(r.project_id,r.seq)}));function ue(r){let t=r.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}function me(r,t){let e=t===void 0?"":` at index ${t}`;if(!r||typeof r!="object")throw new _("VALIDATION",`Task log entry${e} must be an object`);if(typeof r.timestamp!="string"||typeof r.level!="string"||typeof r.message!="string")throw new _("VALIDATION",`Task log entry${e} must contain string timestamp, level, and message fields`);return {timestamp:r.timestamp,level:r.level,message:r.message}}function ge(r,t){if(t===null||t.trim()==="")return [];let e;try{e=JSON.parse(t);}catch(s){throw new _("DB_ERROR",`Malformed legacy task logs: ${r}`,s)}if(!Array.isArray(e))throw new _("DB_ERROR",`Malformed legacy task logs: ${r} (expected an array)`);try{return e.map((s,o)=>me(s,o))}catch(s){throw s instanceof _?new _("DB_ERROR",`Malformed legacy task logs: ${r}`,s):s}}function he(r){if(r.log_storage!=="blob"&&r.log_storage!=="events")throw new _("DB_ERROR",`Invalid task log storage for task: ${r.id}`);if(!Number.isInteger(r.last_log_seq)||r.last_log_seq<0)throw new _("DB_ERROR",`Invalid task log sequence for task: ${r.id}`);if(!Number.isInteger(r.log_revision)||r.log_revision<0)throw new _("DB_ERROR",`Invalid task log revision for task: ${r.id}`);return r.log_storage}function fe(r){return {taskId:r.id,source:he(r),revision:r.log_revision,lastSeq:r.last_log_seq}}function Cn(r){if(!Number.isInteger(r)||r<0)throw new _("VALIDATION","Task log tail limit must be a non-negative integer")}var Ct=class extends rt{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 o=dirname(e);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let s=b(e);if(t)try{pt(s.db,e);}catch(o){throw s.close(),o}return s}findStateRow(t,e){return t.db.select({id:n.id,log_storage:n.log_storage,last_log_seq:n.last_log_seq,log_revision:n.log_revision,logs:n.logs}).from(n).where(eq(n.id,e)).limit(1).get()}findStateRowInTransaction(t,e){return t.select({id:n.id,log_storage:n.log_storage,last_log_seq:n.last_log_seq,log_revision:n.log_revision,logs:n.logs}).from(n).where(eq(n.id,e)).limit(1).get()}requireStateRowInTransaction(t,e){let s=this.findStateRowInTransaction(t,e);if(!s)throw new _("NOT_FOUND",`Task not found: ${e}`);return s}appendLog(t,e){return this.appendLogs(t,[e])}appendLogs(t,e){let s=e.map((i,a)=>me(i,a));if(s.length===0){let i=this.getLogState(t);if(!i)throw new _("NOT_FOUND",`Task not found: ${t}`);return i}let o=this.openHandle(true);try{return o.db.transaction(a=>{let d=this.requireStateRowInTransaction(a,t),u=he(d);if(u==="blob"){let f=ge(t,d.logs);if(a.update(n).set({logs:JSON.stringify([...f,...s]),log_revision:sql`${n.log_revision} + 1`}).where(eq(n.id,t)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:u,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let c=d.last_log_seq+1,l=d.last_log_seq+s.length;if(a.insert(W).values(s.map((f,w)=>({task_id:t,seq:c+w,timestamp:f.timestamp,level:f.level,message:f.message}))).run(),a.update(n).set({last_log_seq:l,log_revision:sql`${n.log_revision} + 1`}).where(eq(n.id,t)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:u,revision:d.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to append task log",i)}finally{o.close();}}getLogState(t){if(!this.dbExists())return;let e=this.openHandle(false);try{let s=this.findStateRow(e,t);return s?fe(s):void 0}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read task log state",s)}finally{e.close();}}readLogs(t){return this.readLogsInternal(t)}readLogsTail(t,e){return Cn(e),this.readLogsInternal(t,e)}readTail(t,e){return this.readLogsTail(t,e)}readLogsInternal(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.transaction(o=>{let i=this.findStateRowInTransaction(o,t);if(!i)return;let a=fe(i);if(a.source==="blob"){let l=ge(t,i.logs);return {...a,entries:e===void 0?l:l.slice(Math.max(0,l.length-e))}}let d=o.select({seq:W.seq,timestamp:W.timestamp,level:W.level,message:W.message}).from(W).where(eq(W.task_id,t)).orderBy(e===void 0?asc(W.seq):desc(W.seq)),c=(e===void 0?d.all():d.limit(e).all()).map(({timestamp:l,level:g,message:f})=>({timestamp:l,level:g,message:f}));return e!==void 0&&c.reverse(),{...a,entries:c}},{behavior:"deferred"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to read task logs",o)}finally{s.close();}}};var at="2026-05-09",Pn="0.8.9-rc.13",dt=10,ct=parseInt(Pn.split("rc.")[1]);function ke(){let r=sql`
18
18
  CASE
19
- WHEN ${e.model} LIKE 'claude-%' OR ${e.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
20
- WHEN ${e.model} LIKE 'gpt-%' OR ${e.model} LIKE 'codex-%' THEN 'codex'
21
- WHEN ${e.model} LIKE 'gemini-%' THEN 'gemini'
22
- WHEN ${e.model} LIKE 'grok-%' THEN 'grok'
23
- WHEN ${e.model} LIKE 'zai-%' OR ${e.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
24
- WHEN ${e.model} LIKE 'minimax/%' THEN 'minimax'
25
- WHEN ${e.model} LIKE 'qwen%' THEN 'qwen'
19
+ WHEN ${n.model} LIKE 'claude-%' OR ${n.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
20
+ WHEN ${n.model} LIKE 'gpt-%' OR ${n.model} LIKE 'codex-%' THEN 'codex'
21
+ WHEN ${n.model} LIKE 'gemini-%' THEN 'gemini'
22
+ WHEN ${n.model} LIKE 'grok-%' THEN 'grok'
23
+ WHEN ${n.model} LIKE 'zai-%' OR ${n.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
24
+ WHEN ${n.model} LIKE 'minimax/%' THEN 'minimax'
25
+ WHEN ${n.model} LIKE 'qwen%' THEN 'qwen'
26
26
  ELSE 'unknown'
27
27
  END
28
- `,t=sql`json_extract(${e.metadata}, '$.provider')`,n=sql`trim(${t})`,s=sql`substr(${n}, 1, instr(${n}, '/') - 1)`,r=sql`
28
+ `,t=sql`json_extract(${n.metadata}, '$.provider')`,e=sql`trim(${t})`,s=sql`substr(${e}, 1, instr(${e}, '/') - 1)`,o=sql`
29
29
  CASE
30
- WHEN instr(${n}, '/') > 0
30
+ WHEN instr(${e}, '/') > 0
31
31
  AND ${s} IN ('cli', 'acp', 'api', 'plugin', 'remote')
32
- THEN substr(${n}, instr(${n}, '/') + 1)
33
- ELSE ${n}
32
+ THEN substr(${e}, instr(${e}, '/') + 1)
33
+ ELSE ${e}
34
34
  END
35
35
  `;return sql`
36
36
  CASE
37
- WHEN ${e.metadata} IS NULL THEN ${o}
38
- WHEN json_valid(${e.metadata}) = 0 THEN 'unknown'
39
- WHEN json_type(${e.metadata}, '$') IS NOT 'object' THEN 'unknown'
40
- WHEN json_type(${e.metadata}, '$.provider') IS NULL THEN ${o}
41
- WHEN json_type(${e.metadata}, '$.provider') IS NOT 'text' THEN 'unknown'
42
- WHEN ${n} = '' THEN 'unknown'
43
- WHEN trim(${r}) = '' THEN 'unknown'
44
- ELSE ${r}
37
+ WHEN ${n.metadata} IS NULL THEN ${r}
38
+ WHEN json_valid(${n.metadata}) = 0 THEN 'unknown'
39
+ WHEN json_type(${n.metadata}, '$') IS NOT 'object' THEN 'unknown'
40
+ WHEN json_type(${n.metadata}, '$.provider') IS NULL THEN ${r}
41
+ WHEN json_type(${n.metadata}, '$.provider') IS NOT 'text' THEN 'unknown'
42
+ WHEN ${e} = '' THEN 'unknown'
43
+ WHEN trim(${o}) = '' THEN 'unknown'
44
+ ELSE ${o}
45
45
  END
46
- `}var hn=new Set(["workflow","mcp"]),de=600*1e3,bt=class extends lt{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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let s=x(n);if(t)try{yt(s.db,n);}catch(r){throw s.close(),r}return s}startTask(t){let n=this.openHandle(true);try{n.db.insert(e).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,project_id:t.projectId??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:e.id,set:{pid:sql`COALESCE(excluded.pid, ${e.pid})`},setWhere:eq(e.status,"running")}).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to start task",s)}finally{n.close();}}listTasksByProjectId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(e).where(eq(e.project_id,t)).orderBy(desc(e.started_at)).all()}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to list tasks by project",s)}finally{n.close();}}finishTask(t){let n=this.openHandle(true);try{let s=t.runEpoch??null;n.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
46
+ `}var Mn=new Set(["workflow","mcp"]),we=600*1e3,Dt=class extends rt{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Ct({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let o=dirname(e);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let s=b(e);if(t)try{pt(s.db,e);}catch(o){throw s.close(),o}return s}startTask(t){let e=this.openHandle(true);try{let s={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,project_id:t.projectId??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,log_storage:"events"},o=i=>{e.db.insert(n).values(i).onConflictDoUpdate({target:n.id,set:{pid:sql`COALESCE(excluded.pid, ${n.pid})`},setWhere:eq(n.status,"running")}).run();};try{o(s);}catch(i){let a=i instanceof Error?i.message:typeof i=="object"&&i!==null&&"message"in i?String(i.message):String(i);if(!/log_storage/i.test(a)||!/no such column|no column named/i.test(a))throw i;e.runRaw(`INSERT INTO tasks (
47
+ id, agent_id, prompt, mode, status, started_at, pid,
48
+ parent_task_id, caller_agent_id, trace_id, command, metadata,
49
+ workspace_id, project_id, platform, crewx_version, thread_id,
50
+ model, rendered_prompt, coding_agent_command
51
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
52
+ ON CONFLICT(id) DO UPDATE SET pid = COALESCE(excluded.pid, tasks.pid)
53
+ WHERE tasks.status = 'running'`,[s.id,s.agent_id,s.prompt,s.mode,s.status,s.started_at,s.pid,s.parent_task_id,s.caller_agent_id,s.trace_id,s.command,s.metadata,s.workspace_id,s.project_id,s.platform,s.crewx_version,s.thread_id,s.model,s.rendered_prompt,s.coding_agent_command]);}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to start task",s)}finally{e.close();}}listTasksByProjectId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(n).where(eq(n.project_id,t)).orderBy(desc(n.started_at)).all()}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to list tasks by project",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=?,
47
54
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
48
55
  model=COALESCE(?, model)
49
- 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{n.close();}}appendLog(t,n){let s=this.openHandle(true);try{s.db.transaction(r=>{let i=r.select({logs:e.logs}).from(e).where(eq(e.id,t)).limit(1).get(),a=i?.logs?JSON.parse(i.logs):[];a.push(n),r.update(e).set({logs:JSON.stringify(a)}).where(eq(e.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to append log",r)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(e).where(eq(e.status,"running")).orderBy(desc(e.started_at)).all()}catch(n){throw new p("DB_ERROR","Failed to get running tasks",n)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(e).orderBy(desc(e.started_at)).limit(100).all()}catch(n){throw new p("DB_ERROR","Failed to get all tasks",n)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(e).where(eq(e.id,t)).limit(1).get()??void 0}catch(s){throw new p("DB_ERROR","Failed to get task",s)}finally{n.close();}}killTask(t){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let s=n.db.select({id:e.id,status:e.status,pid:e.pid}).from(e).where(eq(e.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return n.db.update(e).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(e.id,t),eq(e.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{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=t.db.select({id:e.id,pid:e.pid,platform:e.platform,run_epoch:e.run_epoch}).from(e).where(eq(e.status,"running")).all(),s=Date.now(),r=new Set,i=0;for(let a of n){if(a.pid){let c=!1;try{process.kill(a.pid,0),c=!0;}catch{}c||(t.db.update(e).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(e.id,a.id),eq(e.status,"running"))).run(),i++);continue}if(hn.has(a.platform??"cli"))continue;let d=`${a.id}:${a.run_epoch??0}`;r.add(d);let u=this.pidNullObservedSince.get(d);if(u===void 0){this.pidNullObservedSince.set(d,s);continue}s-u>=de&&(t.db.update(e).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(e.id,a.id),eq(e.status,"running"))).run(),i++,this.pidNullObservedSince.delete(d));}for(let a of Array.from(this.pidNullObservedSince.keys()))r.has(a)||this.pidNullObservedSince.delete(a);return i}finally{t.close();}}reapRunningWorkflowTasks(t=de){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let s=new Date(Date.now()-t).toISOString();return n.db.update(e).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(e.status,"running"),eq(e.platform,"workflow"),isNull(e.pid),lt$1(e.started_at,s),or(isNull(e.metadata),and(notLike(e.metadata,'%"kind":"workflow_card"%'),notLike(e.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{n.close();}}findTaskStatus(t,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=x(r);try{let a=n?eq(e.workspace_id,n):void 0,d=a?and(eq(e.id,t),a):eq(e.id,t),u=i.db.select().from(e).where(d).limit(1).get()??void 0;if(!u){let c=or(eq(e.thread_id,t),and(isNull(e.thread_id),like(e.command,`%--thread=${t}%`))),l=a?and(c,a):c;u=i.db.select().from(e).where(l).orderBy(desc(e.started_at)).limit(1).get()??void 0;}if(u)return u}catch(a){throw new p("DB_ERROR","Failed to find task status",a)}finally{i.close();}}}findChildTasks(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=n?and(eq(e.parent_task_id,t),eq(e.workspace_id,n)):eq(e.parent_task_id,t),c=d.db.select().from(e).where(u).orderBy(asc(e.started_at)).all();for(let l of c)r.has(l.id)||(r.add(l.id),i.push(l));}catch(u){throw new p("DB_ERROR","Failed to find child tasks",u)}finally{d.close();}}return i}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(t?sql`
56
+ 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 _?s:new _("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){this.taskLogRepository.appendLog(t,e);}appendLogs(t,e){this.taskLogRepository.appendLogs(t,e);}readLogs(t){return this.taskLogRepository.readLogs(t)}readLogsTail(t,e){return this.taskLogRepository.readLogsTail(t,e)}getLogState(t){return this.taskLogRepository.getLogState(t)}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(n).where(eq(n.status,"running")).orderBy(desc(n.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(n).orderBy(desc(n.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(n).where(eq(n.id,t)).limit(1).get()??void 0}catch(s){throw new _("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:n.id,status:n.status,pid:n.pid}).from(n).where(eq(n.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(n).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(n.id,t),eq(n.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof _?s:new _("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:n.id,pid:n.pid,platform:n.platform,run_epoch:n.run_epoch}).from(n).where(eq(n.status,"running")).all(),s=Date.now(),o=new Set,i=0;for(let a of e){if(a.pid){let c=!1;try{process.kill(a.pid,0),c=!0;}catch{}c||(t.db.update(n).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(n.id,a.id),eq(n.status,"running"))).run(),i++);continue}if(Mn.has(a.platform??"cli"))continue;let d=`${a.id}:${a.run_epoch??0}`;o.add(d);let u=this.pidNullObservedSince.get(d);if(u===void 0){this.pidNullObservedSince.set(d,s);continue}s-u>=we&&(t.db.update(n).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(n.id,a.id),eq(n.status,"running"))).run(),i++,this.pidNullObservedSince.delete(d));}for(let a of Array.from(this.pidNullObservedSince.keys()))o.has(a)||this.pidNullObservedSince.delete(a);return i}finally{t.close();}}reapRunningWorkflowTasks(t=we){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let s=new Date(Date.now()-t).toISOString();return e.db.update(n).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(n.status,"running"),eq(n.platform,"workflow"),isNull(n.pid),lt(n.started_at,s),or(isNull(n.metadata),and(notLike(n.metadata,'%"kind":"workflow_card"%'),notLike(n.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=b(o);try{let a=e?eq(n.workspace_id,e):void 0,d=a?and(eq(n.id,t),a):eq(n.id,t),u=i.db.select().from(n).where(d).limit(1).get()??void 0;if(!u){let c=or(eq(n.thread_id,t),and(isNull(n.thread_id),like(n.command,`%--thread=${t}%`))),l=a?and(c,a):c;u=i.db.select().from(n).where(l).orderBy(desc(n.started_at)).limit(1).get()??void 0;}if(u)return u}catch(a){throw new _("DB_ERROR","Failed to find task status",a)}finally{i.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),o=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=b(a);try{let u=e?and(eq(n.parent_task_id,t),eq(n.workspace_id,e)):eq(n.parent_task_id,t),c=d.db.select().from(n).where(u).orderBy(asc(n.started_at)).all();for(let l of c)o.has(l.id)||(o.add(l.id),i.push(l));}catch(u){throw new _("DB_ERROR","Failed to find child tasks",u)}finally{d.close();}}return i}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
50
57
  SELECT
51
58
  COALESCE(workspace_id, 'unknown') AS workspace_id,
52
59
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -67,7 +74,7 @@ ${s.join(`
67
74
  FROM tasks
68
75
  GROUP BY workspace_id
69
76
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
70
- `)}catch(s){throw new p("DB_ERROR","Failed to get workspace usage summary",s)}finally{n.close();}}getThreadTokenUsage(t,n){let s=this.resolveDbPaths(),r=new Set,i=0,a=0,d=0;for(let u of s){if(!existsSync(u))continue;let c=x(u);try{let l=or(eq(e.thread_id,t),and(isNull(e.thread_id),like(e.command,`%--thread=${t}%`))),h=n?and(l,eq(e.workspace_id,n)):l,m=c.db.select({id:e.id,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cost_usd:e.cost_usd}).from(e).where(h).all();for(let w of m)r.has(w.id)||(r.add(w.id),i+=w.input_tokens??0,a+=w.output_tokens??0,d+=w.cost_usd??0);}catch(l){throw new p("DB_ERROR","Failed to get thread token usage",l)}finally{c.close();}}return {inputTokens:i,outputTokens:a,costUsd:d}}findTasksByThread(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=or(eq(e.thread_id,t),and(isNull(e.thread_id),like(e.command,`%--thread=${t}%`))),c=n?and(u,eq(e.workspace_id,n)):u,l=d.db.select().from(e).where(c).orderBy(asc(e.started_at)).all();for(let h of l)r.has(h.id)||(r.add(h.id),i.push(h));}catch(u){throw new p("DB_ERROR","Failed to find tasks by thread",u)}finally{d.close();}}return i}parseWorkflowCardMetadata(t){if(!t)return {};try{let n=JSON.parse(t);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let s=x(n);try{t.push(...s.db.select({id:e.id,agent_id:e.agent_id,thread_id:e.thread_id,workspace_id:e.workspace_id,platform:e.platform,status:e.status,error:e.error,completed_at:e.completed_at,duration_ms:e.duration_ms,started_at:e.started_at,metadata:e.metadata}).from(e).where(and(eq(e.platform,"workflow"),or(like(e.metadata,'%"kind":"workflow_card"%'),like(e.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(e.started_at)).all());}catch(r){throw new p("DB_ERROR","Failed to find workflow parent tasks",r)}finally{s.close();}}return t}batchFetchWorkflowCards(t,n){let s=new Map;if(t.length===0)return s;let r=new Set(t),i=new Map,a=n?eq(e.workspace_id,n):void 0,d=(u,c)=>{if(!u)return;let l=i.get(u);if(l&&c.started_at<=l)return;let h=this.parseWorkflowCardMetadata(c.metadata);h.kind!=="workflow_card"&&h.kind!=="workflow_ui_instance"||(i.set(u,c.started_at),s.set(u,{taskId:c.id,workflowRunId:h.workflowRunId,raw:c.result??void 0}));};for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let c=x(u);try{let l=and(inArray(e.thread_id,t),or(like(e.metadata,'%"kind":"workflow_card"%'),like(e.metadata,'%"kind":"workflow_ui_instance"%'))),h=c.db.select({id:e.id,thread_id:e.thread_id,metadata:e.metadata,result:e.result,started_at:e.started_at}).from(e).where(a?and(l,a):l).all();for(let O of h)d(O.thread_id,O);let m=and(isNull(e.thread_id),or(like(e.metadata,'%"kind":"workflow_card"%'),like(e.metadata,'%"kind":"workflow_ui_instance"%'))),w=c.db.select({id:e.id,command:e.command,metadata:e.metadata,result:e.result,started_at:e.started_at}).from(e).where(a?and(m,a):m).all();for(let O of w){let I=this.extractThreadIdFromCommand(O.command);!I||!r.has(I)||d(I,O);}}catch(l){throw new p("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{c.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(e.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&s.push(inArray(e.agent_id,r));let i=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;i&&s.push(inArray(e.status,i));let a=t.q??t.search;a&&s.push(like(e.prompt,`%${a}%`)),t.from&&s.push(gte(e.started_at,t.from)),t.to&&s.push(lt$1(e.started_at,t.to));let d=s.length>0?and(...s):void 0,u=n.db.select({count:sql`count(*)`}).from(e).where(d).get(),c=(t.sortDir??"DESC")==="ASC"?asc(e.started_at):desc(e.started_at);return {rows:n.db.select().from(e).where(d).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(s){throw new p("DB_ERROR","Failed to find all tasks",s)}finally{n.close();}}getAgentUsage(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(s?sql`
77
+ `)}catch(s){throw new _("DB_ERROR","Failed to get workspace usage summary",s)}finally{e.close();}}getThreadTokenUsage(t,e){let s=this.resolveDbPaths(),o=new Set,i=0,a=0,d=0;for(let u of s){if(!existsSync(u))continue;let c=b(u);try{let l=or(eq(n.thread_id,t),and(isNull(n.thread_id),like(n.command,`%--thread=${t}%`))),g=e?and(l,eq(n.workspace_id,e)):l,f=c.db.select({id:n.id,input_tokens:n.input_tokens,output_tokens:n.output_tokens,cost_usd:n.cost_usd}).from(n).where(g).all();for(let w of f)o.has(w.id)||(o.add(w.id),i+=w.input_tokens??0,a+=w.output_tokens??0,d+=w.cost_usd??0);}catch(l){throw new _("DB_ERROR","Failed to get thread token usage",l)}finally{c.close();}}return {inputTokens:i,outputTokens:a,costUsd:d}}findTasksByThread(t,e){let s=this.resolveDbPaths(),o=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=b(a);try{let u=or(eq(n.thread_id,t),and(isNull(n.thread_id),like(n.command,`%--thread=${t}%`))),c=e?and(u,eq(n.workspace_id,e)):u,l=d.db.select().from(n).where(c).orderBy(asc(n.started_at)).all();for(let g of l)o.has(g.id)||(o.add(g.id),i.push(g));}catch(u){throw new _("DB_ERROR","Failed to find tasks by thread",u)}finally{d.close();}}return i}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}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let e of this.resolveDbPaths()){if(!existsSync(e))continue;let s=b(e);try{t.push(...s.db.select({id:n.id,agent_id:n.agent_id,thread_id:n.thread_id,workspace_id:n.workspace_id,platform:n.platform,status:n.status,error:n.error,completed_at:n.completed_at,duration_ms:n.duration_ms,started_at:n.started_at,metadata:n.metadata}).from(n).where(and(eq(n.platform,"workflow"),or(like(n.metadata,'%"kind":"workflow_card"%'),like(n.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(n.started_at)).all());}catch(o){throw new _("DB_ERROR","Failed to find workflow parent tasks",o)}finally{s.close();}}return t}batchFetchWorkflowCards(t,e){let s=new Map;if(t.length===0)return s;let o=new Set(t),i=new Map,a=e?eq(n.workspace_id,e):void 0,d=(u,c)=>{if(!u)return;let l=i.get(u);if(l&&c.started_at<=l)return;let g=this.parseWorkflowCardMetadata(c.metadata);g.kind!=="workflow_card"&&g.kind!=="workflow_ui_instance"||(i.set(u,c.started_at),s.set(u,{taskId:c.id,workflowRunId:g.workflowRunId,raw:c.result??void 0}));};for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let c=b(u);try{let l=and(inArray(n.thread_id,t),or(like(n.metadata,'%"kind":"workflow_card"%'),like(n.metadata,'%"kind":"workflow_ui_instance"%'))),g=c.db.select({id:n.id,thread_id:n.thread_id,metadata:n.metadata,result:n.result,started_at:n.started_at}).from(n).where(a?and(l,a):l).all();for(let $ of g)d($.thread_id,$);let f=and(isNull(n.thread_id),or(like(n.metadata,'%"kind":"workflow_card"%'),like(n.metadata,'%"kind":"workflow_ui_instance"%'))),w=c.db.select({id:n.id,command:n.command,metadata:n.metadata,result:n.result,started_at:n.started_at}).from(n).where(a?and(f,a):f).all();for(let $ of w){let O=this.extractThreadIdFromCommand($.command);!O||!o.has(O)||d(O,$);}}catch(l){throw new _("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{c.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(n.workspace_id,t.workspaceId));let o=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;o&&s.push(inArray(n.agent_id,o));let i=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;i&&s.push(inArray(n.status,i));let a=t.q??t.search;a&&s.push(like(n.prompt,`%${a}%`)),t.from&&s.push(gte(n.started_at,t.from)),t.to&&s.push(lt(n.started_at,t.to));let d=s.length>0?and(...s):void 0,u=e.db.select({count:sql`count(*)`}).from(n).where(d).get(),c=(t.sortDir??"DESC")==="ASC"?asc(n.started_at):desc(n.started_at);return {rows:e.db.select().from(n).where(d).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(s){throw new _("DB_ERROR","Failed to find all tasks",s)}finally{e.close();}}getAgentUsage(t,e,s){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(s?sql`
71
78
  SELECT
72
79
  t.agent_id,
73
80
  t.workspace_id,
@@ -75,11 +82,11 @@ ${s.join(`
75
82
  COALESCE(SUM(
76
83
  COALESCE(t.input_tokens, 0)
77
84
  + CASE
78
- WHEN t.started_at >= ${rt}
85
+ WHEN t.started_at >= ${at}
79
86
  AND (
80
87
  t.crewx_version IS NULL
81
88
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
82
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
89
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${dt}) AS INTEGER) < ${ct})
83
90
  )
84
91
  THEN COALESCE(t.cached_input_tokens, 0)
85
92
  ELSE 0
@@ -91,18 +98,18 @@ ${s.join(`
91
98
  FROM tasks t
92
99
  WHERE t.status IN ('completed', 'success')
93
100
  AND t.started_at >= ${t}
94
- AND t.started_at < ${n}
101
+ AND t.started_at < ${e}
95
102
  AND t.workspace_id = ${s}
96
103
  GROUP BY t.agent_id, t.workspace_id
97
104
  ORDER BY (
98
105
  COALESCE(SUM(
99
106
  COALESCE(t.input_tokens, 0)
100
107
  + CASE
101
- WHEN t.started_at >= ${rt}
108
+ WHEN t.started_at >= ${at}
102
109
  AND (
103
110
  t.crewx_version IS NULL
104
111
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
105
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
112
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${dt}) AS INTEGER) < ${ct})
106
113
  )
107
114
  THEN COALESCE(t.cached_input_tokens, 0)
108
115
  ELSE 0
@@ -118,11 +125,11 @@ ${s.join(`
118
125
  COALESCE(SUM(
119
126
  COALESCE(t.input_tokens, 0)
120
127
  + CASE
121
- WHEN t.started_at >= ${rt}
128
+ WHEN t.started_at >= ${at}
122
129
  AND (
123
130
  t.crewx_version IS NULL
124
131
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
125
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
132
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${dt}) AS INTEGER) < ${ct})
126
133
  )
127
134
  THEN COALESCE(t.cached_input_tokens, 0)
128
135
  ELSE 0
@@ -134,17 +141,17 @@ ${s.join(`
134
141
  FROM tasks t
135
142
  WHERE t.status IN ('completed', 'success')
136
143
  AND t.started_at >= ${t}
137
- AND t.started_at < ${n}
144
+ AND t.started_at < ${e}
138
145
  GROUP BY t.agent_id, t.workspace_id
139
146
  ORDER BY (
140
147
  COALESCE(SUM(
141
148
  COALESCE(t.input_tokens, 0)
142
149
  + CASE
143
- WHEN t.started_at >= ${rt}
150
+ WHEN t.started_at >= ${at}
144
151
  AND (
145
152
  t.crewx_version IS NULL
146
153
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
147
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
154
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${dt}) AS INTEGER) < ${ct})
148
155
  )
149
156
  THEN COALESCE(t.cached_input_tokens, 0)
150
157
  ELSE 0
@@ -152,18 +159,18 @@ ${s.join(`
152
159
  ), 0)
153
160
  + COALESCE(SUM(t.output_tokens), 0)
154
161
  ) DESC
155
- `).map(a=>({agentId:a.agent_id,workspaceId:a.workspace_id??null,totalTasks:a.total_tasks,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(i){throw new p("DB_ERROR","Failed to get agent usage",i)}finally{r.close();}}getAgentUsageTrendRaw(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(s?sql`
162
+ `).map(a=>({agentId:a.agent_id,workspaceId:a.workspace_id??null,totalTasks:a.total_tasks,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(i){throw new _("DB_ERROR","Failed to get agent usage",i)}finally{o.close();}}getAgentUsageTrendRaw(t,e,s){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(s?sql`
156
163
  SELECT
157
164
  date(t.started_at) AS date,
158
165
  t.agent_id,
159
166
  COALESCE(SUM(
160
167
  COALESCE(t.input_tokens, 0)
161
168
  + CASE
162
- WHEN t.started_at >= ${rt}
169
+ WHEN t.started_at >= ${at}
163
170
  AND (
164
171
  t.crewx_version IS NULL
165
172
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
166
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
173
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${dt}) AS INTEGER) < ${ct})
167
174
  )
168
175
  THEN COALESCE(t.cached_input_tokens, 0)
169
176
  ELSE 0
@@ -175,7 +182,7 @@ ${s.join(`
175
182
  FROM tasks t
176
183
  WHERE t.status IN ('completed', 'success')
177
184
  AND t.started_at >= ${t}
178
- AND t.started_at < ${n}
185
+ AND t.started_at < ${e}
179
186
  AND t.workspace_id = ${s}
180
187
  GROUP BY date(t.started_at), t.agent_id
181
188
  ORDER BY date(t.started_at) ASC
@@ -186,11 +193,11 @@ ${s.join(`
186
193
  COALESCE(SUM(
187
194
  COALESCE(t.input_tokens, 0)
188
195
  + CASE
189
- WHEN t.started_at >= ${rt}
196
+ WHEN t.started_at >= ${at}
190
197
  AND (
191
198
  t.crewx_version IS NULL
192
199
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
193
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
200
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${dt}) AS INTEGER) < ${ct})
194
201
  )
195
202
  THEN COALESCE(t.cached_input_tokens, 0)
196
203
  ELSE 0
@@ -202,77 +209,77 @@ ${s.join(`
202
209
  FROM tasks t
203
210
  WHERE t.status IN ('completed', 'success')
204
211
  AND t.started_at >= ${t}
205
- AND t.started_at < ${n}
212
+ AND t.started_at < ${e}
206
213
  GROUP BY date(t.started_at), t.agent_id
207
214
  ORDER BY date(t.started_at) ASC
208
- `).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(i){throw new p("DB_ERROR","Failed to get agent usage trend",i)}finally{r.close();}}findTaskForStop(t,n){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(e).where(and(eq(e.id,t),eq(e.workspace_id,n))).limit(1).get()??void 0}catch(r){throw new p("DB_ERROR","Failed to find task for stop",r)}finally{s.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:e.id,thread_id:e.thread_id,status:e.status,result:e.result,error:e.error,started_at:e.started_at,completed_at:e.completed_at,metadata:e.metadata}).from(e).where(and(eq(e.agent_id,t.agentId),eq(e.workspace_id,t.workspaceId),sql`${e.metadata} IS NOT NULL AND json_valid(${e.metadata}) AND json_extract(${e.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(e.started_at)).limit(1).get()??null}catch(s){throw new p("DB_ERROR","Failed to find latest task by metadata",s)}finally{n.close();}}markTaskFailed(t,n,s){if(!this.dbExists())return;let r=this.openHandle(true);try{let i=new Date().toISOString(),a=s?and(eq(e.id,t),eq(e.status,"running"),eq(e.workspace_id,s)):and(eq(e.id,t),eq(e.status,"running"));r.db.update(e).set({status:"failed",error:n,completed_at:i}).where(a).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to mark task failed",i)}finally{r.close();}}findTasksByPromptHint(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=n?and(like(e.prompt,`%${t}%`),eq(e.workspace_id,n)):like(e.prompt,`%${t}%`),c=d.db.select().from(e).where(u).orderBy(asc(e.started_at)).all();for(let l of c)r.has(l.id)||(r.add(l.id),i.push(l));}catch(u){throw new p("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{d.close();}}return i}getProviderUsage(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{let i=ae(),a=sql`
209
- COALESCE(${e.input_tokens}, 0)
215
+ `).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(i){throw new _("DB_ERROR","Failed to get agent usage trend",i)}finally{o.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(n).where(and(eq(n.id,t),eq(n.workspace_id,e))).limit(1).get()??void 0}catch(o){throw new _("DB_ERROR","Failed to find task for stop",o)}finally{s.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let e=this.openHandle(false);try{return e.db.select({id:n.id,thread_id:n.thread_id,status:n.status,result:n.result,error:n.error,started_at:n.started_at,completed_at:n.completed_at,metadata:n.metadata}).from(n).where(and(eq(n.agent_id,t.agentId),eq(n.workspace_id,t.workspaceId),sql`${n.metadata} IS NOT NULL AND json_valid(${n.metadata}) AND json_extract(${n.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(n.started_at)).limit(1).get()??null}catch(s){throw new _("DB_ERROR","Failed to find latest task by metadata",s)}finally{e.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let o=this.openHandle(true);try{let i=new Date().toISOString(),a=s?and(eq(n.id,t),eq(n.status,"running"),eq(n.workspace_id,s)):and(eq(n.id,t),eq(n.status,"running"));o.db.update(n).set({status:"failed",error:e,completed_at:i}).where(a).run();}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to mark task failed",i)}finally{o.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),o=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=b(a);try{let u=e?and(like(n.prompt,`%${t}%`),eq(n.workspace_id,e)):like(n.prompt,`%${t}%`),c=d.db.select().from(n).where(u).orderBy(asc(n.started_at)).all();for(let l of c)o.has(l.id)||(o.add(l.id),i.push(l));}catch(u){throw new _("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{d.close();}}return i}getProviderUsage(t,e,s){if(!this.dbExists())return [];let o=this.openHandle(false);try{let i=ke(),a=sql`
216
+ COALESCE(${n.input_tokens}, 0)
210
217
  + CASE
211
- WHEN ${e.started_at} >= ${rt}
218
+ WHEN ${n.started_at} >= ${at}
212
219
  AND (
213
- ${e.crewx_version} IS NULL
214
- OR (${e.crewx_version} LIKE '0.8.%' AND ${e.crewx_version} NOT LIKE '0.8.9%')
215
- OR (${e.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${e.crewx_version}, ${ot}) AS INTEGER) < ${it})
220
+ ${n.crewx_version} IS NULL
221
+ OR (${n.crewx_version} LIKE '0.8.%' AND ${n.crewx_version} NOT LIKE '0.8.9%')
222
+ OR (${n.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${n.crewx_version}, ${dt}) AS INTEGER) < ${ct})
216
223
  )
217
- THEN COALESCE(${e.cached_input_tokens}, 0)
224
+ THEN COALESCE(${n.cached_input_tokens}, 0)
218
225
  ELSE 0
219
226
  END
220
- `,d=s?sql`WHERE ${e.status} IN ('completed', 'success') AND ${e.started_at} >= ${t} AND ${e.started_at} < ${n} AND ${e.workspace_id} = ${s}`:sql`WHERE ${e.status} IN ('completed', 'success') AND ${e.started_at} >= ${t} AND ${e.started_at} < ${n}`;return r.db.all(sql`
227
+ `,d=s?sql`WHERE ${n.status} IN ('completed', 'success') AND ${n.started_at} >= ${t} AND ${n.started_at} < ${e} AND ${n.workspace_id} = ${s}`:sql`WHERE ${n.status} IN ('completed', 'success') AND ${n.started_at} >= ${t} AND ${n.started_at} < ${e}`;return o.db.all(sql`
221
228
  SELECT
222
229
  ${i} AS provider,
223
230
  COUNT(*) AS total_tasks,
224
231
  COALESCE(SUM(${a}), 0) AS input_tokens,
225
- COALESCE(SUM(${e.output_tokens}), 0) AS output_tokens,
226
- COALESCE(SUM(${e.cached_input_tokens}), 0) AS cached_input_tokens,
227
- COALESCE(SUM(${e.cost_usd}), 0) AS cost_usd,
228
- COALESCE(SUM(${e.duration_ms}), 0) AS active_duration_ms,
229
- MAX(${e.completed_at}) AS last_active_at
230
- FROM ${e}
232
+ COALESCE(SUM(${n.output_tokens}), 0) AS output_tokens,
233
+ COALESCE(SUM(${n.cached_input_tokens}), 0) AS cached_input_tokens,
234
+ COALESCE(SUM(${n.cost_usd}), 0) AS cost_usd,
235
+ COALESCE(SUM(${n.duration_ms}), 0) AS active_duration_ms,
236
+ MAX(${n.completed_at}) AS last_active_at
237
+ FROM ${n}
231
238
  ${d}
232
239
  GROUP BY ${i}
233
- ORDER BY (COALESCE(SUM(${a}), 0) + COALESCE(SUM(${e.output_tokens}), 0)) DESC
234
- `).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(i){throw new p("DB_ERROR","Failed to get provider usage",i)}finally{r.close();}}getModelUsage(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{let i=ae(),a=sql`
235
- COALESCE(${e.input_tokens}, 0)
240
+ ORDER BY (COALESCE(SUM(${a}), 0) + COALESCE(SUM(${n.output_tokens}), 0)) DESC
241
+ `).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(i){throw new _("DB_ERROR","Failed to get provider usage",i)}finally{o.close();}}getModelUsage(t,e,s){if(!this.dbExists())return [];let o=this.openHandle(false);try{let i=ke(),a=sql`
242
+ COALESCE(${n.input_tokens}, 0)
236
243
  + CASE
237
- WHEN ${e.started_at} >= ${rt}
244
+ WHEN ${n.started_at} >= ${at}
238
245
  AND (
239
- ${e.crewx_version} IS NULL
240
- OR (${e.crewx_version} LIKE '0.8.%' AND ${e.crewx_version} NOT LIKE '0.8.9%')
241
- OR (${e.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${e.crewx_version}, ${ot}) AS INTEGER) < ${it})
246
+ ${n.crewx_version} IS NULL
247
+ OR (${n.crewx_version} LIKE '0.8.%' AND ${n.crewx_version} NOT LIKE '0.8.9%')
248
+ OR (${n.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${n.crewx_version}, ${dt}) AS INTEGER) < ${ct})
242
249
  )
243
- THEN COALESCE(${e.cached_input_tokens}, 0)
250
+ THEN COALESCE(${n.cached_input_tokens}, 0)
244
251
  ELSE 0
245
252
  END
246
- `,d=s?sql`WHERE ${e.status} IN ('completed', 'success') AND ${e.started_at} >= ${t} AND ${e.started_at} < ${n} AND ${e.workspace_id} = ${s}`:sql`WHERE ${e.status} IN ('completed', 'success') AND ${e.started_at} >= ${t} AND ${e.started_at} < ${n}`,u=r.db.all(sql`
253
+ `,d=s?sql`WHERE ${n.status} IN ('completed', 'success') AND ${n.started_at} >= ${t} AND ${n.started_at} < ${e} AND ${n.workspace_id} = ${s}`:sql`WHERE ${n.status} IN ('completed', 'success') AND ${n.started_at} >= ${t} AND ${n.started_at} < ${e}`,u=o.db.all(sql`
247
254
  SELECT
248
- ${e.model} AS model,
255
+ ${n.model} AS model,
249
256
  ${i} AS provider,
250
257
  COUNT(*) AS total_tasks,
251
258
  COALESCE(SUM(${a}), 0) AS input_tokens,
252
- COALESCE(SUM(${e.output_tokens}), 0) AS output_tokens,
253
- COALESCE(SUM(${e.cached_input_tokens}), 0) AS cached_input_tokens,
254
- COALESCE(SUM(${e.cost_usd}), 0) AS cost_usd,
255
- COALESCE(SUM(${e.duration_ms}), 0) AS active_duration_ms,
256
- MAX(${e.completed_at}) AS last_active_at
257
- FROM ${e}
259
+ COALESCE(SUM(${n.output_tokens}), 0) AS output_tokens,
260
+ COALESCE(SUM(${n.cached_input_tokens}), 0) AS cached_input_tokens,
261
+ COALESCE(SUM(${n.cost_usd}), 0) AS cost_usd,
262
+ COALESCE(SUM(${n.duration_ms}), 0) AS active_duration_ms,
263
+ MAX(${n.completed_at}) AS last_active_at
264
+ FROM ${n}
258
265
  ${d}
259
- GROUP BY ${e.model}, ${i}
260
- `),c=new Map;for(let l of u){let h=ie(l.model??""),m=JSON.stringify([l.provider,h]),w=c.get(m);w?(w.totalTasks+=l.total_tasks,w.inputTokens+=l.input_tokens,w.outputTokens+=l.output_tokens,w.cachedInputTokens+=l.cached_input_tokens,w.costUsd+=l.cost_usd,w.totalTokens+=l.input_tokens+l.output_tokens,w.activeDurationMs+=l.active_duration_ms??0,l.last_active_at&&(!w.lastActiveAt||l.last_active_at>w.lastActiveAt)&&(w.lastActiveAt=l.last_active_at)):c.set(m,{model:h,provider:l.provider,totalTasks:l.total_tasks,inputTokens:l.input_tokens,outputTokens:l.output_tokens,cachedInputTokens:l.cached_input_tokens,costUsd:l.cost_usd,totalTokens:l.input_tokens+l.output_tokens,activeDurationMs:l.active_duration_ms??0,lastActiveAt:l.last_active_at??null});}return Array.from(c.values()).sort((l,h)=>h.costUsd-l.costUsd)}catch(i){throw new p("DB_ERROR","Failed to get model usage",i)}finally{r.close();}}getTasksForReport(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{let i=s?sql`WHERE ${e.started_at} >= ${t} AND ${e.started_at} < ${n} AND ${e.workspace_id} = ${s}`:sql`WHERE ${e.started_at} >= ${t} AND ${e.started_at} < ${n}`;return r.db.all(sql`
266
+ GROUP BY ${n.model}, ${i}
267
+ `),c=new Map;for(let l of u){let g=ue(l.model??""),f=JSON.stringify([l.provider,g]),w=c.get(f);w?(w.totalTasks+=l.total_tasks,w.inputTokens+=l.input_tokens,w.outputTokens+=l.output_tokens,w.cachedInputTokens+=l.cached_input_tokens,w.costUsd+=l.cost_usd,w.totalTokens+=l.input_tokens+l.output_tokens,w.activeDurationMs+=l.active_duration_ms??0,l.last_active_at&&(!w.lastActiveAt||l.last_active_at>w.lastActiveAt)&&(w.lastActiveAt=l.last_active_at)):c.set(f,{model:g,provider:l.provider,totalTasks:l.total_tasks,inputTokens:l.input_tokens,outputTokens:l.output_tokens,cachedInputTokens:l.cached_input_tokens,costUsd:l.cost_usd,totalTokens:l.input_tokens+l.output_tokens,activeDurationMs:l.active_duration_ms??0,lastActiveAt:l.last_active_at??null});}return Array.from(c.values()).sort((l,g)=>g.costUsd-l.costUsd)}catch(i){throw new _("DB_ERROR","Failed to get model usage",i)}finally{o.close();}}getTasksForReport(t,e,s){if(!this.dbExists())return [];let o=this.openHandle(false);try{let i=s?sql`WHERE ${n.started_at} >= ${t} AND ${n.started_at} < ${e} AND ${n.workspace_id} = ${s}`:sql`WHERE ${n.started_at} >= ${t} AND ${n.started_at} < ${e}`;return o.db.all(sql`
261
268
  SELECT
262
- ${e.thread_id} AS thread_id,
263
- ${e.agent_id} AS agent_id,
264
- ${e.started_at} AS started_at,
265
- ${e.status} AS status,
266
- ${e.error} AS error,
267
- ${e.exit_code} AS exit_code
268
- FROM ${e}
269
+ ${n.thread_id} AS thread_id,
270
+ ${n.agent_id} AS agent_id,
271
+ ${n.started_at} AS started_at,
272
+ ${n.status} AS status,
273
+ ${n.error} AS error,
274
+ ${n.exit_code} AS exit_code
275
+ FROM ${n}
269
276
  ${i}
270
- ORDER BY ${e.started_at} ASC
271
- `).map(d=>({threadId:d.thread_id,agentId:d.agent_id,startedAt:d.started_at,status:d.status,error:d.error,exitCode:d.exit_code}))}catch(i){throw new p("DB_ERROR","Failed to get tasks for report",i)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(e.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&s.push(inArray(e.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&s.push(inArray(e.status,t.statuses)),t.from&&s.push(gte(e.started_at,t.from)),t.to&&s.push(lt$1(e.started_at,t.to));let r=s.length>0?and(...s):void 0,i=(t.order??"DESC")==="ASC"?asc(e.started_at):desc(e.started_at),a={id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id};return t.limit?n.db.select(a).from(e).where(r).orderBy(i).limit(t.limit).all():n.db.select(a).from(e).where(r).orderBy(i).all()}catch(s){throw new p("DB_ERROR","Failed to find task evidence",s)}finally{n.close();}}findThreadChains(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=t.maxThreads??8,r=t.maxTurnsPerThread??4,i=[isNotNull(e.thread_id),isNull(e.parent_task_id),isNull(e.caller_agent_id),or(isNull(e.platform),ne(e.platform,"workflow")),or(isNull(e.metadata),and(notLike(e.metadata,'%"kind":"workflow_card"%'),notLike(e.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(e.metadata),notLike(e.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&i.push(eq(e.workspace_id,t.workspaceId)),t.from&&i.push(gte(e.started_at,t.from)),t.to&&i.push(lt$1(e.started_at,t.to));let a=n.db.select({id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id}).from(e).where(and(...i)).orderBy(asc(e.started_at),asc(e.id)).all(),d=new Map;for(let c of a){if(!c.thread_id)continue;let l={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},h=d.get(c.thread_id);h?h.push(l):d.set(c.thread_id,[l]);}let u=[];for(let[c,l]of d){let h=l.filter(m=>m.agentId===t.targetAgentId).length;h<2||u.push({threadId:c,targetAgentTurnCount:h,turns:l});}return u.sort((c,l)=>{let h=c.turns[c.turns.length-1].startedAt,m=l.turns[l.turns.length-1].startedAt;return h<m?1:h>m?-1:0}),u.slice(0,s).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-r)}))}catch(s){throw new p("DB_ERROR","Failed to find thread chains",s)}finally{n.close();}}};var Bt=class extends et{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 n=new bt({dbPath:this.dbPath}),s=process.cwd(),i=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?Gt(s):null,a=process.argv.join(" ");this.unsubs.push(t.on("task:start",d=>{try{let u=d.callerAgentId??null,c=d.parentTaskId??null,l=d.rootTraceId??d.traceId,h=d.metadata?JSON.stringify(d.metadata):JSON.stringify({provider:d.provider??"cli/claude"});n.startTask({id:d.traceId,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:d.pid??null,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:a,codingAgentCommand:d.codingAgentCommand??null,workspaceId:d.workspaceId??i,projectId:d.projectId??null,callerAgentId:u,parentTaskId:c,traceId:l,metadata:h,threadId:d.threadId??null});}catch{}}),t.on("task:output",d=>{try{n.appendLog(d.traceId,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch{}}),t.on("task:end",d=>{try{let u=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null,c=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{}}):null;n.finishTask({id:d.traceId,status:d.error?"failed":"success",result:d.result??null,error:c,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch:u});}catch{}}));}detach(t){this.unsubs.forEach(n=>n()),this.unsubs=[];}};var Ct=class extends lt{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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let s=x(n);if(t)try{yt(s.db,n);}catch(r){throw s.close(),r}return s}validateWorkspaceId(t,n){return t.db.select({id:_t.id}).from(_t).where(eq(_t.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
277
+ ORDER BY ${n.started_at} ASC
278
+ `).map(d=>({threadId:d.thread_id,agentId:d.agent_id,startedAt:d.started_at,status:d.status,error:d.error,exitCode:d.exit_code}))}catch(i){throw new _("DB_ERROR","Failed to get tasks for report",i)}finally{o.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(n.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&s.push(inArray(n.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&s.push(inArray(n.status,t.statuses)),t.from&&s.push(gte(n.started_at,t.from)),t.to&&s.push(lt(n.started_at,t.to));let o=s.length>0?and(...s):void 0,i=(t.order??"DESC")==="ASC"?asc(n.started_at):desc(n.started_at),a={id:n.id,agent_id:n.agent_id,status:n.status,prompt:n.prompt,started_at:n.started_at,completed_at:n.completed_at,thread_id:n.thread_id};return t.limit?e.db.select(a).from(n).where(o).orderBy(i).limit(t.limit).all():e.db.select(a).from(n).where(o).orderBy(i).all()}catch(s){throw new _("DB_ERROR","Failed to find task evidence",s)}finally{e.close();}}findThreadChains(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let s=t.maxThreads??8,o=t.maxTurnsPerThread??4,i=[isNotNull(n.thread_id),isNull(n.parent_task_id),isNull(n.caller_agent_id),or(isNull(n.platform),ne(n.platform,"workflow")),or(isNull(n.metadata),and(notLike(n.metadata,'%"kind":"workflow_card"%'),notLike(n.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(n.metadata),notLike(n.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&i.push(eq(n.workspace_id,t.workspaceId)),t.from&&i.push(gte(n.started_at,t.from)),t.to&&i.push(lt(n.started_at,t.to));let a=e.db.select({id:n.id,agent_id:n.agent_id,status:n.status,prompt:n.prompt,started_at:n.started_at,completed_at:n.completed_at,thread_id:n.thread_id}).from(n).where(and(...i)).orderBy(asc(n.started_at),asc(n.id)).all(),d=new Map;for(let c of a){if(!c.thread_id)continue;let l={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},g=d.get(c.thread_id);g?g.push(l):d.set(c.thread_id,[l]);}let u=[];for(let[c,l]of d){let g=l.filter(f=>f.agentId===t.targetAgentId).length;g<2||u.push({threadId:c,targetAgentTurnCount:g,turns:l});}return u.sort((c,l)=>{let g=c.turns[c.turns.length-1].startedAt,f=l.turns[l.turns.length-1].startedAt;return g<f?1:g>f?-1:0}),u.slice(0,s).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-o)}))}catch(s){throw new _("DB_ERROR","Failed to find thread chains",s)}finally{e.close();}}};var zt=class extends st{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 Dt({dbPath:this.dbPath}),s=process.cwd(),i=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?Vt(s):null,a=process.argv.join(" ");this.unsubs.push(t.on("task:start",d=>{try{let u=d.callerAgentId??null,c=d.parentTaskId??null,l=d.rootTraceId??d.traceId,g=d.metadata?JSON.stringify(d.metadata):JSON.stringify({provider:d.provider??"cli/claude"});e.startTask({id:d.traceId,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:d.pid??null,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:a,codingAgentCommand:d.codingAgentCommand??null,workspaceId:d.workspaceId??i,projectId:d.projectId??null,callerAgentId:u,parentTaskId:c,traceId:l,metadata:g,threadId:d.threadId??null});}catch{}}),t.on("task:output",d=>{try{e.appendLog(d.traceId,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch{}}),t.on("task:end",d=>{try{let u=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null,c=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{}}):null;e.finishTask({id:d.traceId,status:d.error?"failed":"success",result:d.result??null,error:c,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch:u});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var $t=class extends rt{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 o=dirname(e);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let s=b(e);if(t)try{pt(s.db,e);}catch(o){throw s.close(),o}return s}validateWorkspaceId(t,e){return t.db.select({id:gt.id}).from(gt).where(eq(gt.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
272
279
  SELECT 1 FROM tasks parent
273
280
  WHERE parent.id = ${t}.parent_task_id
274
281
  AND parent.thread_id = ${t}.thread_id
275
- )`)}findAllThreads(t){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let a=x(i);try{let d=t?eq(_.workspace_id,t):void 0,u=a.db.select().from(_).where(d).orderBy(desc(_.updated_at)).all();for(let c of u)s.has(c.id)||(s.add(c.id),r.push(c));}catch(d){throw new p("DB_ERROR","Failed to find all threads",d)}finally{a.close();}}return r}findThreadsByIdsOrTitles(t,n){if(t.length===0)return [];let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=or(inArray(_.id,t),inArray(_.title,t)),c=n?and(u,eq(_.workspace_id,n)):u,l=d.db.select().from(_).where(c).orderBy(desc(_.updated_at)).all();for(let h of l)r.has(h.id)||(r.add(h.id),i.push(h));}catch(u){throw new p("DB_ERROR","Failed to find threads by ids or titles",u)}finally{d.close();}}return i}findThreadById(t,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=x(r);try{let a=eq(_.id,t),d=n?and(a,eq(_.workspace_id,n)):a,u=i.db.select().from(_).where(d).limit(1).get()??void 0;if(u)return u}catch(a){throw new p("DB_ERROR","Failed to find thread by id",a)}finally{i.close();}}}threadExists(t,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=x(r);try{let a=eq(_.id,t),d=n?and(a,eq(_.workspace_id,n)):a;if(i.db.select({id:_.id}).from(_).where(d).limit(1).get())return !0}catch(a){throw new p("DB_ERROR","Failed to check thread existence",a)}finally{i.close();}}return false}aggregateTaskStats(t,n){let s=this.resolveDbPaths(),r=0,i=0,a=0,d=0,u=0,c=new Set;for(let l of s){if(!existsSync(l))continue;let h=x(l);try{let m=h.db.get(sql`
282
+ )`)}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,o=[];for(let i of e){if(!existsSync(i))continue;let a=b(i);try{let d=t?eq(p.workspace_id,t):void 0,u=a.db.select().from(p).where(d).orderBy(desc(p.updated_at)).all();for(let c of u)s.has(c.id)||(s.add(c.id),o.push(c));}catch(d){throw new _("DB_ERROR","Failed to find all threads",d)}finally{a.close();}}return o}findThreadsByIdsOrTitles(t,e){if(t.length===0)return [];let s=this.resolveDbPaths(),o=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=b(a);try{let u=or(inArray(p.id,t),inArray(p.title,t)),c=e?and(u,eq(p.workspace_id,e)):u,l=d.db.select().from(p).where(c).orderBy(desc(p.updated_at)).all();for(let g of l)o.has(g.id)||(o.add(g.id),i.push(g));}catch(u){throw new _("DB_ERROR","Failed to find threads by ids or titles",u)}finally{d.close();}}return i}findThreadById(t,e){let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=b(o);try{let a=eq(p.id,t),d=e?and(a,eq(p.workspace_id,e)):a,u=i.db.select().from(p).where(d).limit(1).get()??void 0;if(u)return u}catch(a){throw new _("DB_ERROR","Failed to find thread by id",a)}finally{i.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=b(o);try{let a=eq(p.id,t),d=e?and(a,eq(p.workspace_id,e)):a;if(i.db.select({id:p.id}).from(p).where(d).limit(1).get())return !0}catch(a){throw new _("DB_ERROR","Failed to check thread existence",a)}finally{i.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),o=0,i=0,a=0,d=0,u=0,c=new Set;for(let l of s){if(!existsSync(l))continue;let g=b(l);try{let f=g.db.get(sql`
276
283
  SELECT
277
284
  count(*) AS cnt,
278
285
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -282,21 +289,21 @@ ${s.join(`
282
289
  FROM tasks child
283
290
  WHERE child.thread_id = ${t}
284
291
  AND ${this.topLevelTaskPredicateSql()}
285
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
286
- `);m&&(r+=m.cnt,i+=m.total_input,a+=m.total_output,d+=m.total_cached,u+=m.total_cost);let w=h.db.all(sql`
292
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
293
+ `);f&&(o+=f.cnt,i+=f.total_input,a+=f.total_output,d+=f.total_cached,u+=f.total_cost);let w=g.db.all(sql`
287
294
  SELECT DISTINCT child.agent_id FROM tasks child
288
295
  WHERE child.thread_id = ${t}
289
296
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
290
297
  AND ${this.topLevelTaskPredicateSql()}
291
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
292
- `);for(let O of w)c.add(O.agent_id);}catch(m){throw new p("DB_ERROR","Failed to aggregate task stats",m)}finally{h.close();}}return {taskCount:r,inputTokens:i,outputTokens:a,cachedInputTokens:d,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,n,s){let r=this.resolveDbPaths(),i=new Set,a=[];for(let d of r){if(!existsSync(d))continue;let u=x(d);try{let c;s!==void 0?c=u.db.all(sql`
298
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
299
+ `);for(let $ of w)c.add($.agent_id);}catch(f){throw new _("DB_ERROR","Failed to aggregate task stats",f)}finally{g.close();}}return {taskCount:o,inputTokens:i,outputTokens:a,cachedInputTokens:d,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,s){let o=this.resolveDbPaths(),i=new Set,a=[];for(let d of o){if(!existsSync(d))continue;let u=b(d);try{let c;s!==void 0?c=u.db.all(sql`
293
300
  SELECT * FROM (
294
301
  SELECT child.*,
295
302
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
296
303
  FROM tasks child
297
304
  WHERE child.thread_id = ${t}
298
305
  AND ${this.topLevelTaskPredicateSql()}
299
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
306
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
300
307
  ) ranked
301
308
  WHERE rn <= ${s}
302
309
  ORDER BY started_at ASC
@@ -304,9 +311,9 @@ ${s.join(`
304
311
  SELECT child.* FROM tasks child
305
312
  WHERE child.thread_id = ${t}
306
313
  AND ${this.topLevelTaskPredicateSql()}
307
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
314
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
308
315
  ORDER BY child.started_at ASC
309
- `);for(let l of c)i.has(l.id)||(i.add(l.id),a.push(l));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(s!==void 0&&r.length>1){let d=new Map;for(let u of a){let c=u.agent_id??"";d.has(c)||d.set(c,[]),d.get(c).push(u);}a=[];for(let u of d.values())u.sort((c,l)=>(l.started_at??"").localeCompare(c.started_at??"")),a.push(...u.slice(0,s));a.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return a}findAllTasks(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=eq(e.thread_id,t),c=n?and(u,eq(e.workspace_id,n)):u,l=d.db.select().from(e).where(c).orderBy(asc(e.started_at)).all();for(let h of l)r.has(h.id)||(r.add(h.id),i.push(h));}catch(u){throw new p("DB_ERROR","Failed to find all tasks for thread",u)}finally{d.close();}}return i}findTaskById(t,n,s){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let a=x(i);try{let d=and(eq(e.id,n),eq(e.thread_id,t)),u=s?and(d,eq(e.workspace_id,s)):d,c=a.db.select().from(e).where(u).limit(1).get();if(!c)continue;let l=a.db.select().from(e).where(eq(e.parent_task_id,c.id)).orderBy(asc(e.started_at)).all();return {task:c,children:l}}catch(d){throw new p("DB_ERROR","Failed to find task by id",d)}finally{a.close();}}}batchFetchTasksQuery(t,n){return sql`
316
+ `);for(let l of c)i.has(l.id)||(i.add(l.id),a.push(l));}catch(c){throw new _("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(s!==void 0&&o.length>1){let d=new Map;for(let u of a){let c=u.agent_id??"";d.has(c)||d.set(c,[]),d.get(c).push(u);}a=[];for(let u of d.values())u.sort((c,l)=>(l.started_at??"").localeCompare(c.started_at??"")),a.push(...u.slice(0,s));a.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return a}findAllTasks(t,e){let s=this.resolveDbPaths(),o=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=b(a);try{let u=eq(n.thread_id,t),c=e?and(u,eq(n.workspace_id,e)):u,l=d.db.select().from(n).where(c).orderBy(asc(n.started_at)).all();for(let g of l)o.has(g.id)||(o.add(g.id),i.push(g));}catch(u){throw new _("DB_ERROR","Failed to find all tasks for thread",u)}finally{d.close();}}return i}findTaskById(t,e,s){let o=this.resolveDbPaths();for(let i of o){if(!existsSync(i))continue;let a=b(i);try{let d=and(eq(n.id,e),eq(n.thread_id,t)),u=s?and(d,eq(n.workspace_id,s)):d,c=a.db.select().from(n).where(u).limit(1).get();if(!c)continue;let l=a.db.select().from(n).where(eq(n.parent_task_id,c.id)).orderBy(asc(n.started_at)).all();return {task:c,children:l}}catch(d){throw new _("DB_ERROR","Failed to find task by id",d)}finally{a.close();}}}batchFetchTasksQuery(t,e){return sql`
310
317
  SELECT child.id, child.thread_id, child.agent_id, child.status,
311
318
  child.parent_task_id, child.started_at, child.completed_at,
312
319
  child.duration_ms, child.input_tokens, child.output_tokens,
@@ -314,18 +321,18 @@ ${s.join(`
314
321
  FROM tasks child INDEXED BY idx_tasks_thread_id
315
322
  WHERE child.thread_id IN (${sql.join(t.map(s=>sql`${s}`),sql`, `)})
316
323
  AND ${this.topLevelTaskPredicateSql()}
317
- ${n?sql`AND child.workspace_id = ${n}`:sql``}
324
+ ${e?sql`AND child.workspace_id = ${e}`:sql``}
318
325
  ORDER BY child.started_at ASC
319
- `}batchFetchTasks(t,n){let s=new Map;if(t.length===0)return s;let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let a=x(i);try{let d=a.db.all(this.batchFetchTasksQuery(t,n));for(let u of d){let c=u.thread_id;s.has(c)||s.set(c,[]),s.get(c).push(u);}}catch(d){throw new p("DB_ERROR","Failed to batch fetch tasks",d)}finally{a.close();}}return s}explainBatchFetchTasksPlan(t,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=x(r);try{return i.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,n)}`).map(d=>d.detail)}finally{i.close();}}return []}updateThreadTitle(t,n,s){if(!this.dbExists())return;let r=this.openHandle(true);try{let i=eq(_.id,t),a=s?and(i,eq(_.workspace_id,s)):i;if(!r.db.select({id:_.id}).from(_).where(a).limit(1).get())return;r.db.update(_).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(_.id,t)).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to update thread title",i)}finally{r.close();}}upsertThread(t,n){let s=this.openHandle(true);try{let r=n.workspaceId?this.validateWorkspaceId(s,n.workspaceId):null,i=new Date().toISOString();if(s.db.select({id:_.id,message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()){let d={updated_at:i};n.title!==void 0&&(d.title=n.title),n.titleLocked!==void 0&&(d.title_locked=n.titleLocked?1:0),s.db.update(_).set(d).where(eq(_.id,t)).run();}else s.db.insert(_).values({id:t,platform:n.platform,workspace_id:r,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:i,updated_at:i}).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to upsert thread",r)}finally{s.close();}}ensureThread(t,n,s){let r=this.openHandle(true);try{let i=s?this.validateWorkspaceId(r,s):null,a=r.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(eq(_.id,t)).limit(1).get();if(a){i&&!a.workspace_id&&r.db.update(_).set({workspace_id:i}).where(eq(_.id,t)).run();return}let d=new Date().toISOString();r.db.insert(_).values({id:t,platform:n,workspace_id:i,message_count:0,created_at:d,updated_at:d}).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to ensure thread",i)}finally{r.close();}}saveUserMessage(t,n,s){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let i=new Date().toISOString();return {firstMessage:r.db.transaction(d=>{let c=d.select({message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()?.message_count===0;return d.run(sql`
326
+ `}batchFetchTasks(t,e){let s=new Map;if(t.length===0)return s;let o=this.resolveDbPaths();for(let i of o){if(!existsSync(i))continue;let a=b(i);try{let d=a.db.all(this.batchFetchTasksQuery(t,e));for(let u of d){let c=u.thread_id;s.has(c)||s.set(c,[]),s.get(c).push(u);}}catch(d){throw new _("DB_ERROR","Failed to batch fetch tasks",d)}finally{a.close();}}return s}explainBatchFetchTasksPlan(t,e){let s=this.resolveDbPaths();for(let o of s){if(!existsSync(o))continue;let i=b(o);try{return i.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,e)}`).map(d=>d.detail)}finally{i.close();}}return []}updateThreadTitle(t,e,s){if(!this.dbExists())return;let o=this.openHandle(true);try{let i=eq(p.id,t),a=s?and(i,eq(p.workspace_id,s)):i;if(!o.db.select({id:p.id}).from(p).where(a).limit(1).get())return;o.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to update thread title",i)}finally{o.close();}}upsertThread(t,e){let s=this.openHandle(true);try{let o=e.workspaceId?this.validateWorkspaceId(s,e.workspaceId):null,i=new Date().toISOString();if(s.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let d={updated_at:i};e.title!==void 0&&(d.title=e.title),e.titleLocked!==void 0&&(d.title_locked=e.titleLocked?1:0),s.db.update(p).set(d).where(eq(p.id,t)).run();}else s.db.insert(p).values({id:t,platform:e.platform,workspace_id:o,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:i,updated_at:i}).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to upsert thread",o)}finally{s.close();}}ensureThread(t,e,s){let o=this.openHandle(true);try{let i=s?this.validateWorkspaceId(o,s):null,a=o.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get();if(a){i&&!a.workspace_id&&o.db.update(p).set({workspace_id:i}).where(eq(p.id,t)).run();return}let d=new Date().toISOString();o.db.insert(p).values({id:t,platform:e,workspace_id:i,message_count:0,created_at:d,updated_at:d}).run();}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to ensure thread",i)}finally{o.close();}}saveUserMessage(t,e,s){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let i=new Date().toISOString();return {firstMessage:o.db.transaction(d=>{let c=d.select({message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()?.message_count===0;return d.run(sql`
320
327
  UPDATE threads
321
- SET first_message = COALESCE(first_message, ${n}),
322
- title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
323
- last_message = ${n},
328
+ SET first_message = COALESCE(first_message, ${e}),
329
+ title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
330
+ last_message = ${e},
324
331
  message_count = message_count + 1,
325
332
  updated_at = ${i}
326
333
  WHERE id = ${t}
327
- `),c},{behavior:"immediate"})}}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to save user message",i)}finally{r.close();}}saveAssistantMessage(t,n,s){if(!this.dbExists())return;let r=this.openHandle(true);try{let i=new Date().toISOString();r.db.update(_).set({last_message:n,updated_at:i}).where(eq(_.id,t)).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to save assistant message",i)}finally{r.close();}}updateThread(t,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),s.db.update(_).set(r).where(eq(_.id,t)).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to update thread",r)}finally{s.close();}}togglePin(t,n){let s=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),i=s.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!i)return null;let a=i.pinned?0:1,d=i.metadata?JSON.parse(i.metadata):{};if(a){let u=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),c=s.db.select({metadata:_.metadata}).from(_).where(u).all(),l=null;for(let h of c){let m=h.metadata?JSON.parse(h.metadata):{};typeof m.pinOrder=="number"&&(l===null||m.pinOrder<l)&&(l=m.pinOrder);}d.pinOrder=l===null?0:l-1;}else delete d.pinOrder;return s.db.update(_).set({pinned:a,metadata:Object.keys(d).length>0?JSON.stringify(d):null}).where(r).run(),{pinned:!!a}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to toggle pin",r)}finally{s.close();}}reorderPins(t,n){let s=this.openHandle(true);try{for(let r=0;r<t.length;r++){let i=n?and(eq(_.id,t[r]),eq(_.workspace_id,n)):eq(_.id,t[r]),a=s.db.select({metadata:_.metadata}).from(_).where(i).get();if(!a)continue;let d=a.metadata?JSON.parse(a.metadata):{};d.pinOrder=r+1,s.db.update(_).set({metadata:JSON.stringify(d)}).where(i).run();}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to reorder pins",r)}finally{s.close();}}toggleStar(t,n){let s=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),i=s.db.select({starred:_.starred}).from(_).where(r).get();if(!i)return null;let a=i.starred?0:1;return s.db.update(_).set({starred:a}).where(r).run(),{starred:!!a}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to toggle star",r)}finally{s.close();}}resolveOverdriveForRequest(t,n,s,r){let a=this.openHandle(true);try{let d=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t);return a.db.transaction(c=>{let l=c.select({metadata:_.metadata}).from(_).where(d).get();if(!l)return null;let h=l.metadata?JSON.parse(l.metadata):{},m=h.overdrive??{},w=r?.defaultTurns??m.defaultTurns??3,O=r?.updatedBy??"ui",I=new Date().toISOString(),B,z,Y,pt;switch(s){case "enable-count":{let ht=r?.turns??w,ft=r?.consumeCurrent?Math.max(ht-1,0):ht;B=ft>0?"count":"off",z=ft,Y=!0,pt="count";break}case "enable-latch":{B="latch",z=0,Y=!0,pt="latch";break}case "disable":{B="off",z=0,Y=!1;break}default:{let ht=m.state??"off",ft=typeof m.remaining=="number"?m.remaining:0;if(ht==="count"&&ft>0){let qt=ft-1;qt<=0?(B="off",z=0):(B="count",z=qt),Y=!0,pt="count";}else ht==="latch"?(B="latch",z=0,Y=!0,pt="latch"):(B="off",z=0,Y=!1);break}}return h.overdrive={state:B,remaining:z,defaultTurns:w,updatedAt:I,updatedBy:O},c.update(_).set({metadata:JSON.stringify(h),updated_at:I}).where(d).run(),{applied:Y,appliedMode:pt,state:B,remaining:z}},{behavior:"immediate"})}catch(d){throw d instanceof p?d:new p("DB_ERROR","Failed to resolve overdrive",d)}finally{a.close();}}};function Sn(o){return o.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
328
- `).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(`
329
- `).trim()}function Tn(o){if(!o)return "";let t=o;try{let n=JSON.parse(t);Array.isArray(n)?t=n.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
330
- `):n&&typeof n=="object"&&n.result!==void 0&&(t=n.result||"");}catch{t=Sn(t);}return t}var vt=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Ct({dbPath:this.dbPath})}updateThread(t,n){this.getThreadRepo().updateThread(t,{title:n.title});}async ensureThread(t,n,s){let r=this.getThreadRepo(),i=r.findThreadById(t);if(i){if(i.platform!==n)throw new Error(`Thread '${t}' already exists with platform '${i.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return {created:false}}return r.ensureThread(t,n,s),{created:true}}async fetchHistory(t,n){let s=n?.limit??100,r=this.getThreadRepo(),i=r.findThreadById(t),a=r.findTopLevelTasks(t,void 0,s),d=new Set(["queued","cancelled"]);a=a.filter(l=>(!l.status||!d.has(l.status))&&(!n?.currentTraceId||l.trace_id!==n.currentTraceId));let u=i?.platform??"cli",c=this.rowsToMessages(a);return {threadId:t,platform:u,messages:c,metadata:{title:i?.title??void 0,firstMessage:i?.first_message??void 0,lastMessage:i?.last_message??void 0,messageCount:i?.message_count??0,updatedAt:i?.updated_at?new Date(i.updated_at).getTime():void 0}}}async saveUserMessage(t,n,s,r){let{firstMessage:i}=this.getThreadRepo().saveUserMessage(t,n);return {id:t,firstMessage:i}}async saveAssistantMessage(t,n,s,r){return this.getThreadRepo().saveAssistantMessage(t,n),{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 n=[];for(let s of t){s.prompt&&n.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 r=Tn(s.result),i=this.normalizeStatus(s.status);if(r||i==="running"||i==="failed"){let a={agent_id:s.agent_id,task_id:s.id};i&&(a.status=i),i==="failed"&&s.error&&(a.reason=s.error.split(`
331
- `)[0].slice(0,200)),n.push({id:`${s.id}-assistant`,text:r,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:a});}}return n}};var Ht=class extends et{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new vt(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,n,s,r){}async afterAssistantMessage(t,n,s){}attach(t){this.unsubStart=t.on("task:start",async n=>{if(!n.threadId)return;let s=n.platform??"cli";try{let r=await this._provider.ensureThread(n.threadId,s,n.workspaceId),i=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,i.id,r.created||i.firstMessage,n);}catch{}}),this.unsubEnd=t.on("task:end",async n=>{if(!n.result)return;let s=n.metadata?.threadId;if(!s)return;let r=n.agentRef?.replace(/^@/,"")??"";try{let{id:i}=await this._provider.saveAssistantMessage(s,n.result,r);await this.afterAssistantMessage(s,i,n);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{Ht as ConversationPlugin,Dt as FileLoggerPlugin,Bt as SqliteTracingPlugin};
334
+ `),c},{behavior:"immediate"})}}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to save user message",i)}finally{o.close();}}saveAssistantMessage(t,e,s){if(!this.dbExists())return;let o=this.openHandle(true);try{let i=new Date().toISOString();o.db.update(p).set({last_message:e,updated_at:i}).where(eq(p.id,t)).run();}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to save assistant message",i)}finally{o.close();}}updateThread(t,e){if(!this.dbExists())return;let s=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};e.title!==void 0&&(o.title=e.title,o.title_locked=1),e.titleLocked!==void 0&&(o.title_locked=e.titleLocked?1:0),s.db.update(p).set(o).where(eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to update thread",o)}finally{s.close();}}togglePin(t,e){let s=this.openHandle(true);try{let o=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),i=s.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(o).get();if(!i)return null;let a=i.pinned?0:1,d=i.metadata?JSON.parse(i.metadata):{};if(a){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),c=s.db.select({metadata:p.metadata}).from(p).where(u).all(),l=null;for(let g of c){let f=g.metadata?JSON.parse(g.metadata):{};typeof f.pinOrder=="number"&&(l===null||f.pinOrder<l)&&(l=f.pinOrder);}d.pinOrder=l===null?0:l-1;}else delete d.pinOrder;return s.db.update(p).set({pinned:a,metadata:Object.keys(d).length>0?JSON.stringify(d):null}).where(o).run(),{pinned:!!a}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to toggle pin",o)}finally{s.close();}}reorderPins(t,e){let s=this.openHandle(true);try{for(let o=0;o<t.length;o++){let i=e?and(eq(p.id,t[o]),eq(p.workspace_id,e)):eq(p.id,t[o]),a=s.db.select({metadata:p.metadata}).from(p).where(i).get();if(!a)continue;let d=a.metadata?JSON.parse(a.metadata):{};d.pinOrder=o+1,s.db.update(p).set({metadata:JSON.stringify(d)}).where(i).run();}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to reorder pins",o)}finally{s.close();}}toggleStar(t,e){let s=this.openHandle(true);try{let o=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),i=s.db.select({starred:p.starred}).from(p).where(o).get();if(!i)return null;let a=i.starred?0:1;return s.db.update(p).set({starred:a}).where(o).run(),{starred:!!a}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to toggle star",o)}finally{s.close();}}resolveOverdriveForRequest(t,e,s,o){let a=this.openHandle(true);try{let d=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return a.db.transaction(c=>{let l=c.select({metadata:p.metadata}).from(p).where(d).get();if(!l)return null;let g=l.metadata?JSON.parse(l.metadata):{},f=g.overdrive??{},w=o?.defaultTurns??f.defaultTurns??3,$=o?.updatedBy??"ui",O=new Date().toISOString(),q,z,V,ft;switch(s){case "enable-count":{let mt=o?.turns??w,ht=o?.consumeCurrent?Math.max(mt-1,0):mt;q=ht>0?"count":"off",z=ht,V=!0,ft="count";break}case "enable-latch":{q="latch",z=0,V=!0,ft="latch";break}case "disable":{q="off",z=0,V=!1;break}default:{let mt=f.state??"off",ht=typeof f.remaining=="number"?f.remaining:0;if(mt==="count"&&ht>0){let Kt=ht-1;Kt<=0?(q="off",z=0):(q="count",z=Kt),V=!0,ft="count";}else mt==="latch"?(q="latch",z=0,V=!0,ft="latch"):(q="off",z=0,V=!1);break}}return g.overdrive={state:q,remaining:z,defaultTurns:w,updatedAt:O,updatedBy:$},c.update(p).set({metadata:JSON.stringify(g),updated_at:O}).where(d).run(),{applied:V,appliedMode:ft,state:q,remaining:z}},{behavior:"immediate"})}catch(d){throw d instanceof _?d:new _("DB_ERROR","Failed to resolve overdrive",d)}finally{a.close();}}};function Wn(r){return r.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
335
+ `).filter(o=>!(o.startsWith("Loaded ")&&o.includes("layouts from")||o.includes("[dotenv@")||o.includes("[Nest]")&&o.includes("DEBUG")||o.startsWith("Registered custom layout:")||o.startsWith("Updated custom layout:"))).join(`
336
+ `).trim()}function Kn(r){if(!r)return "";let t=r;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
337
+ `):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=Wn(t);}return t}var Ot=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new $t({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let o=this.getThreadRepo(),i=o.findThreadById(t);if(i){if(i.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${i.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return o.ensureThread(t,e,s),{created:true}}async fetchHistory(t,e){let s=e?.limit??100,o=this.getThreadRepo(),i=o.findThreadById(t),a=o.findTopLevelTasks(t,void 0,s),d=new Set(["queued","cancelled"]);a=a.filter(l=>(!l.status||!d.has(l.status))&&(!e?.currentTraceId||l.trace_id!==e.currentTraceId));let u=i?.platform??"cli",c=this.rowsToMessages(a);return {threadId:t,platform:u,messages:c,metadata:{title:i?.title??void 0,firstMessage:i?.first_message??void 0,lastMessage:i?.last_message??void 0,messageCount:i?.message_count??0,updatedAt:i?.updated_at?new Date(i.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,o){let{firstMessage:i}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:i}}async saveAssistantMessage(t,e,s,o){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 o=Kn(s.result),i=this.normalizeStatus(s.status);if(o||i==="running"||i==="failed"){let a={agent_id:s.agent_id,task_id:s.id};i&&(a.status=i),i==="failed"&&s.error&&(a.reason=s.error.split(`
338
+ `)[0].slice(0,200)),e.push({id:`${s.id}-assistant`,text:o,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:a});}}return e}};var Wt=class extends st{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new Ot(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,s,o){}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 o=await this._provider.ensureThread(e.threadId,s,e.workspaceId),i=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,i.id,o.created||i.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let o=e.agentRef?.replace(/^@/,"")??"";try{let{id:i}=await this._provider.saveAssistantMessage(s,e.result,o);await this.afterAssistantMessage(s,i,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{Wt as ConversationPlugin,Pt as FileLoggerPlugin,zt as SqliteTracingPlugin};