@crewx/sdk 0.9.0-rc.13 → 0.9.0-rc.15
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.
- package/dist/esm/index.js +1 -1
- package/dist/esm/plugins/index.js +15 -19
- package/dist/esm/repository/index.js +7 -11
- package/dist/index.js +1 -1
- package/dist/migrations/0010_analyze_stats.sql +6 -0
- package/dist/migrations/meta/0010_snapshot.json +1335 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.js +14 -18
- package/dist/repository/index.js +6 -10
- package/package.json +1 -1
package/dist/esm/index.js
CHANGED
|
@@ -47,7 +47,7 @@ ${n??""}
|
|
|
47
47
|
---
|
|
48
48
|
`)}let s=(await e.readdir(n)).filter(a=>a.endsWith(".md"));if(s.length===0)return "";let i=[];for(let a of s){let d=e.resolvePath(n,a),l=await e.readFile(d),u=Zi.exec(l);!u||!ea.test(u[1])||Qi.test(l)&&i.push(l);}return i.join(`
|
|
49
49
|
---
|
|
50
|
-
`)}c();function ta(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return `${e}-${t}-${r}`}async function vo(n,e=We){let t=e.resolvePath(n,`${ta()}.md`);return await e.exists(t)?e.readFile(t):""}Oe();c();var Et=new AsyncLocalStorage;function Kr(n){if(n)return {parentTaskId:n.parentTaskId??null,rootTraceId:n.rootTraceId,callerAgentId:n.callerAgentId??null}}c();function na(n){return typeof n!="string"?"":n.replace(/</g,"<").replace(/>/g,">")}function Vr(n){return n.messages.map(e=>({text:na(e.text),isAssistant:e.isAssistant,timestamp:e.timestamp,metadata:e.metadata,files:void 0}))}c();Oe();Me();c();c();var at=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(aa.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};c();function Ce(n){let e=ee("better-sqlite3"),{drizzle:t}=ee("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),{db:t(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}c();var _o=new Set,da={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 Jr(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function la(n,e){if(e>0||!Jr(n,"tasks"))return;let t=n.all("PRAGMA table_info(tasks)"),r=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(da))r.has(o)||n.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var ca={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ua(n,e,t){if(!Jr(n,"__drizzle_migrations")||!Jr(n,"tasks"))return;let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(X__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=ca[i.tag];if(!a)continue;let d=X__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let l=readFileSync(d,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(o.has(u))continue;let m=n.all("PRAGMA table_info(tasks)"),f=new Set(m.map(g=>g.name));for(let[g,w]of Object.entries(a))f.has(g)||(n.run(`ALTER TABLE tasks ADD COLUMN ${g} ${w}`),f.add(g));}}function pa(n,e,t){let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(X__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=X__default.join(e,`${i.tag}.sql`);if(!existsSync(a))continue;let d=readFileSync(a,"utf-8"),l=createHash("sha256").update(d).digest("hex");if(o.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],f;for(;(f=u.exec(d))!==null;)m.push({table:f[1],column:f[2]});if(m.length===0||!d.split(/-->\s*statement-breakpoint/).map(v=>v.trim()).filter(Boolean).every(v=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(v)))continue;m.every(({table:v,column:k})=>n.all(`PRAGMA table_info("${v}")`).some(x=>x.name===k))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function ga(n){let{migrate:e}=ee("drizzle-orm/better-sqlite3/migrator"),{sql:t}=ee("drizzle-orm"),r=[X__default.join(y,"../migrations"),X__default.join(y,"migrations"),X__default.join(y,"../../../../drizzle/migrations"),X__default.join(process.cwd(),"drizzle/migrations")],o=r.find(l=>existsSync(X__default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
50
|
+
`)}c();function ta(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return `${e}-${t}-${r}`}async function vo(n,e=We){let t=e.resolvePath(n,`${ta()}.md`);return await e.exists(t)?e.readFile(t):""}Oe();c();var Et=new AsyncLocalStorage;function Kr(n){if(n)return {parentTaskId:n.parentTaskId??null,rootTraceId:n.rootTraceId,callerAgentId:n.callerAgentId??null}}c();function na(n){return typeof n!="string"?"":n.replace(/</g,"<").replace(/>/g,">")}function Vr(n){return n.messages.map(e=>({text:na(e.text),isAssistant:e.isAssistant,timestamp:e.timestamp,metadata:e.metadata,files:void 0}))}c();Oe();Me();c();c();var at=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(aa.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};c();function Ce(n){let e=ee("better-sqlite3"),{drizzle:t}=ee("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),r.exec("PRAGMA optimize"),{db:t(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}c();var _o=new Set,da={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 Jr(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function la(n,e){if(e>0||!Jr(n,"tasks"))return;let t=n.all("PRAGMA table_info(tasks)"),r=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(da))r.has(o)||n.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var ca={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ua(n,e,t){if(!Jr(n,"__drizzle_migrations")||!Jr(n,"tasks"))return;let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(X__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=ca[i.tag];if(!a)continue;let d=X__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let l=readFileSync(d,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(o.has(u))continue;let m=n.all("PRAGMA table_info(tasks)"),f=new Set(m.map(g=>g.name));for(let[g,w]of Object.entries(a))f.has(g)||(n.run(`ALTER TABLE tasks ADD COLUMN ${g} ${w}`),f.add(g));}}function pa(n,e,t){let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(X__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=X__default.join(e,`${i.tag}.sql`);if(!existsSync(a))continue;let d=readFileSync(a,"utf-8"),l=createHash("sha256").update(d).digest("hex");if(o.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],f;for(;(f=u.exec(d))!==null;)m.push({table:f[1],column:f[2]});if(m.length===0||!d.split(/-->\s*statement-breakpoint/).map(v=>v.trim()).filter(Boolean).every(v=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(v)))continue;m.every(({table:v,column:k})=>n.all(`PRAGMA table_info("${v}")`).some(x=>x.name===k))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function ga(n){let{migrate:e}=ee("drizzle-orm/better-sqlite3/migrator"),{sql:t}=ee("drizzle-orm"),r=[X__default.join(y,"../migrations"),X__default.join(y,"migrations"),X__default.join(y,"../../../../drizzle/migrations"),X__default.join(process.cwd(),"drizzle/migrations")],o=r.find(l=>existsSync(X__default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
51
51
|
${r.join(`
|
|
52
52
|
`)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),la(n,i),s?.cnt&&(pa(n,o,t),ua(n,o,t)),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${d} migration${d>1?"s":""} applied).`);}}function tr(n,e){_o.has(e)||(ga(n),_o.add(e));}c();var O=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};c();c();var ko=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()});c();var p=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)},n=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));c();var Ao=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>ko.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)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(n.workspace_id,n.updated_at)}));c();var Xe=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>p.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Xe.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")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));c();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>p.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()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));c();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>Ao.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()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));c();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")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));c();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")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));c();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")},n=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(n.workspace_id,n.month)}));var De="2026-05-09",Ua="0.8.9-rc.13",Le=10,$e=parseInt(Ua.split("rc.")[1]),ja=new Set(["workflow","mcp"]),Ha=600*1e3,Rt=class extends at{dbPath;pidNullObservedSince=new Map;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new O("NOT_FOUND","Database not found");let r=Ce(t);if(e)try{tr(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(p).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoUpdate({target:p.id,set:{pid:sql`COALESCE(excluded.pid, ${p.pid})`},setWhere:eq(p.status,"running")}).run();}catch(r){throw r instanceof O?r:new O("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{let r=e.runEpoch??null;t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
53
53
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import*as I from'path';import I__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import Jt,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,or,isNull,like,asc,inArray,gte,lt as lt$1}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique,uniqueIndex}from'drizzle-orm/sqlite-core';var et=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var Ft=()=>fileURLToPath(import.meta.url),
|
|
1
|
+
import*as I from'path';import I__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import Jt,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,or,isNull,like,asc,inArray,gte,lt as lt$1}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique,uniqueIndex}from'drizzle-orm/sqlite-core';var et=(d=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(d,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):d)(function(d){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+d+'" is not supported')});var Ft=()=>fileURLToPath(import.meta.url),zt=()=>I__default.dirname(Ft()),k=zt();var H=class{detach(t){}};function Rt(d){let t=e=>String(e).padStart(2,"0");return `${d.getFullYear()}${t(d.getMonth()+1)}${t(d.getDate())}T${t(d.getHours())}${t(d.getMinutes())}${t(d.getSeconds())}`}var pt=class extends H{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let n=Rt(e.timestamp),s=join(this.logsDir,`${n}_${e.traceId}.log`);this.logFiles.set(e.traceId,s);let o=`=== TASK LOG: ${e.traceId} ===
|
|
2
2
|
CrewX Version: ${this.version}
|
|
3
3
|
Mode: ${e.mode}
|
|
4
4
|
Agent: ${e.agentRef}
|
|
@@ -8,9 +8,9 @@ Message: ${e.message}
|
|
|
8
8
|
`;writeFileSync(s,o,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",e=>{try{let n=this.logFiles.get(e.traceId);if(!n)return;let s=new Date().toISOString();appendFileSync(n,`[${s}] STDOUT: ${e.output}
|
|
9
9
|
`,"utf8");}catch{}}),t.on("task:end",e=>{try{let n=this.logFiles.get(e.traceId);if(!n)return;let s=new Date().toLocaleString(),o=e.error?`failed: ${e.error.message}`:"completed successfully",i=`[${s}] INFO: Task ${o} in ${e.durationMs}ms
|
|
10
10
|
[${s}] INFO: Process closed with exit code: ${e.error?1:0}
|
|
11
|
-
`;appendFileSync(n,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Gt(d){let t=I.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function
|
|
11
|
+
`;appendFileSync(n,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Gt(d){let t=I.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function xt(d){let t=Gt(d);return createHash("sha256").update(t).digest("hex")}var Y=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Jt.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};function T(d){let t=et("better-sqlite3"),{drizzle:e}=et("drizzle-orm/better-sqlite3"),n=new t(d);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:e(n),runRaw:(s,o=[])=>n.prepare(s).run(...o),close:()=>n.close()}}var Ct=new Set,Vt={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function _t(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Qt(d,t){if(t>0||!_t(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),n=new Set(e.map(s=>s.name));for(let[s,o]of Object.entries(Vt))n.has(s)||d.run(`ALTER TABLE tasks ADD COLUMN ${s} ${o}`);}var Zt={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function te(d,t,e){if(!_t(d,"__drizzle_migrations")||!_t(d,"tasks"))return;let n=d.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(I__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=Zt[i.tag];if(!a)continue;let l=I__default.join(t,`${i.tag}.sql`);if(!existsSync(l))continue;let c=readFileSync(l,"utf-8"),u=createHash("sha256").update(c).digest("hex");if(s.has(u))continue;let f=d.all("PRAGMA table_info(tasks)"),m=new Set(f.map(R=>R.name));for(let[R,X]of Object.entries(a))m.has(R)||(d.run(`ALTER TABLE tasks ADD COLUMN ${R} ${X}`),m.add(R));}}function ee(d,t,e){let n=d.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(I__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=I__default.join(t,`${i.tag}.sql`);if(!existsSync(a))continue;let l=readFileSync(a,"utf-8"),c=createHash("sha256").update(l).digest("hex");if(s.has(c))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],m;for(;(m=u.exec(l))!==null;)f.push({table:m[1],column:m[2]});if(f.length===0||!l.split(/-->\s*statement-breakpoint/).map(U=>U.trim()).filter(Boolean).every(U=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(U)))continue;f.every(({table:U,column:O})=>d.all(`PRAGMA table_info("${U}")`).some(L=>L.name===O))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function ne(d){let{migrate:t}=et("drizzle-orm/better-sqlite3/migrator"),{sql:e}=et("drizzle-orm"),n=[I__default.join(k,"../migrations"),I__default.join(k,"migrations"),I__default.join(k,"../../../../drizzle/migrations"),I__default.join(process.cwd(),"drizzle/migrations")],s=n.find(c=>existsSync(I__default.join(c,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
|
|
12
12
|
${n.join(`
|
|
13
|
-
`)}`);let o=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Qt(d,i),o?.cnt&&(ee(d,s,e),te(d,s,e)),t(d,{migrationsFolder:s});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function st(d,t){Ct.has(t)||(ne(d),Ct.add(t));}var _=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};var J=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 r=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>J.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(d.workspace_id,d.updated_at)}));var ce=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>r.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>ce.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>r.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},d=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(d.workspace_id,d.month)}));function It(d){let t=d.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var F="2026-05-09",Oe="0.8.9-rc.13",
|
|
13
|
+
`)}`);let o=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Qt(d,i),o?.cnt&&(ee(d,s,e),te(d,s,e)),t(d,{migrationsFolder:s});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function st(d,t){Ct.has(t)||(ne(d),Ct.add(t));}var _=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};var J=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 r=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>J.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(d.workspace_id,d.updated_at)}));var ce=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>r.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>ce.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>r.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},d=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(d.workspace_id,d.month)}));function It(d){let t=d.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var F="2026-05-09",Oe="0.8.9-rc.13",z=10,q=parseInt(Oe.split("rc.")[1]),Ne=new Set(["workflow","mcp"]),De=600*1e3,lt=class extends Y{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let n=T(e);if(t)try{st(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(r).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:r.id,set:{pid:sql`COALESCE(excluded.pid, ${r.pid})`},setWhere:eq(r.status,"running")}).run();}catch(n){throw n instanceof _?n:new _("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
14
14
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
15
15
|
model=COALESCE(?, model)
|
|
16
16
|
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof _?n:new _("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let o=s.select({logs:r.logs}).from(r).where(eq(r.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(e),s.update(r).set({logs:JSON.stringify(i)}).where(eq(r.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(r).where(eq(r.status,"running")).orderBy(desc(r.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(r).orderBy(desc(r.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(r).where(eq(r.id,t)).limit(1).get()??void 0}catch(n){throw new _("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:r.id,status:r.status,pid:r.pid}).from(r).where(eq(r.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(r).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(r.id,t),eq(r.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof _?n:new _("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:r.id,pid:r.pid,platform:r.platform,run_epoch:r.run_epoch}).from(r).where(eq(r.status,"running")).all(),n=Date.now(),s=new Set,o=0;for(let i of e){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(t.db.update(r).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(r.id,i.id),eq(r.status,"running"))).run(),o++);continue}if(Ne.has(i.platform??"cli"))continue;let a=`${i.id}:${i.run_epoch??0}`;s.add(a);let l=this.pidNullObservedSince.get(a);if(l===void 0){this.pidNullObservedSince.set(a,n);continue}n-l>=De&&(t.db.update(r).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(r.id,i.id),eq(r.status,"running"))).run(),o++,this.pidNullObservedSince.delete(a));}for(let i of Array.from(this.pidNullObservedSince.keys()))s.has(i)||this.pidNullObservedSince.delete(i);return o}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let o=T(s);try{let i=e?eq(r.workspace_id,e):void 0,a=i?and(eq(r.id,t),i):eq(r.id,t),l=o.db.select().from(r).where(a).limit(1).get()??void 0;if(!l){let c=or(eq(r.thread_id,t),and(isNull(r.thread_id),like(r.command,`%--thread=${t}%`))),u=i?and(c,i):c;l=o.db.select().from(r).where(u).orderBy(desc(r.started_at)).limit(1).get()??void 0;}if(l)return l}catch(i){throw new _("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let a=T(i);try{let l=e?and(eq(r.parent_task_id,t),eq(r.workspace_id,e)):eq(r.parent_task_id,t),c=a.db.select().from(r).where(l).orderBy(asc(r.started_at)).all();for(let u of c)s.has(u.id)||(s.add(u.id),o.push(u));}catch(l){throw new _("DB_ERROR","Failed to find child tasks",l)}finally{a.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
@@ -46,7 +46,7 @@ ${n.join(`
|
|
|
46
46
|
AND (
|
|
47
47
|
t.crewx_version IS NULL
|
|
48
48
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
49
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
49
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${z}) AS INTEGER) < ${q})
|
|
50
50
|
)
|
|
51
51
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
52
52
|
ELSE 0
|
|
@@ -69,7 +69,7 @@ ${n.join(`
|
|
|
69
69
|
AND (
|
|
70
70
|
t.crewx_version IS NULL
|
|
71
71
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
72
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
72
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${z}) AS INTEGER) < ${q})
|
|
73
73
|
)
|
|
74
74
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
75
75
|
ELSE 0
|
|
@@ -89,7 +89,7 @@ ${n.join(`
|
|
|
89
89
|
AND (
|
|
90
90
|
t.crewx_version IS NULL
|
|
91
91
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
92
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
92
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${z}) AS INTEGER) < ${q})
|
|
93
93
|
)
|
|
94
94
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
95
95
|
ELSE 0
|
|
@@ -111,7 +111,7 @@ ${n.join(`
|
|
|
111
111
|
AND (
|
|
112
112
|
t.crewx_version IS NULL
|
|
113
113
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
114
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
114
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${z}) AS INTEGER) < ${q})
|
|
115
115
|
)
|
|
116
116
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
117
117
|
ELSE 0
|
|
@@ -130,7 +130,7 @@ ${n.join(`
|
|
|
130
130
|
AND (
|
|
131
131
|
t.crewx_version IS NULL
|
|
132
132
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
133
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
133
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${z}) AS INTEGER) < ${q})
|
|
134
134
|
)
|
|
135
135
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
136
136
|
ELSE 0
|
|
@@ -157,7 +157,7 @@ ${n.join(`
|
|
|
157
157
|
AND (
|
|
158
158
|
t.crewx_version IS NULL
|
|
159
159
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
160
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
160
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${z}) AS INTEGER) < ${q})
|
|
161
161
|
)
|
|
162
162
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
163
163
|
ELSE 0
|
|
@@ -189,7 +189,7 @@ ${n.join(`
|
|
|
189
189
|
AND (
|
|
190
190
|
${r.crewx_version} IS NULL
|
|
191
191
|
OR (${r.crewx_version} LIKE '0.8.%' AND ${r.crewx_version} NOT LIKE '0.8.9%')
|
|
192
|
-
OR (${r.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${r.crewx_version}, ${
|
|
192
|
+
OR (${r.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${r.crewx_version}, ${z}) AS INTEGER) < ${q})
|
|
193
193
|
)
|
|
194
194
|
THEN COALESCE(${r.cached_input_tokens}, 0)
|
|
195
195
|
ELSE 0
|
|
@@ -225,7 +225,7 @@ ${n.join(`
|
|
|
225
225
|
AND (
|
|
226
226
|
${r.crewx_version} IS NULL
|
|
227
227
|
OR (${r.crewx_version} LIKE '0.8.%' AND ${r.crewx_version} NOT LIKE '0.8.9%')
|
|
228
|
-
OR (${r.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${r.crewx_version}, ${
|
|
228
|
+
OR (${r.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${r.crewx_version}, ${z}) AS INTEGER) < ${q})
|
|
229
229
|
)
|
|
230
230
|
THEN COALESCE(${r.cached_input_tokens}, 0)
|
|
231
231
|
ELSE 0
|
|
@@ -255,14 +255,10 @@ ${n.join(`
|
|
|
255
255
|
FROM ${r}
|
|
256
256
|
${o}
|
|
257
257
|
ORDER BY ${r.started_at} ASC
|
|
258
|
-
`).map(a=>({threadId:a.thread_id,agentId:a.agent_id,startedAt:a.started_at,status:a.status,error:a.error,exitCode:a.exit_code}))}catch(o){throw new _("DB_ERROR","Failed to get tasks for report",o)}finally{s.close();}}};var Et=class extends H{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 lt({dbPath:this.dbPath}),n=process.cwd(),o=existsSync(join(n,"crewx.yaml"))||existsSync(join(n,"crewx.yml"))?
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
SELECT 1 FROM tasks parent
|
|
263
|
-
WHERE parent.id = ${t}.parent_task_id
|
|
264
|
-
AND parent.thread_id = ${t}.thread_id
|
|
265
|
-
)
|
|
258
|
+
`).map(a=>({threadId:a.thread_id,agentId:a.agent_id,startedAt:a.started_at,status:a.status,error:a.error,exitCode:a.exit_code}))}catch(o){throw new _("DB_ERROR","Failed to get tasks for report",o)}finally{s.close();}}};var Et=class extends H{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 lt({dbPath:this.dbPath}),n=process.cwd(),o=existsSync(join(n,"crewx.yaml"))||existsSync(join(n,"crewx.yml"))?xt(n):null,i=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let l=a.callerAgentId??null,c=a.parentTaskId??null,u=a.rootTraceId??a.traceId,f=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});e.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:i,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??o,callerAgentId:l,parentTaskId:c,traceId:u,metadata:f,threadId:a.threadId??null});}catch{}}),t.on("task:output",a=>{try{e.appendLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch{}}),t.on("task:end",a=>{try{let l=typeof a.metadata?.runEpoch=="number"?a.metadata.runEpoch:null;e.finishTask({id:a.traceId,status:a.error?"failed":"success",result:a.result??null,error:a.error?JSON.stringify(a.error):null,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null,runEpoch:l});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var ct=class extends Y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let n=T(e);if(t)try{st(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:J.id}).from(J).where(eq(J.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
|
|
259
|
+
SELECT 1 FROM tasks parent
|
|
260
|
+
WHERE parent.id = ${t}.parent_task_id
|
|
261
|
+
AND parent.thread_id = ${t}.thread_id
|
|
266
262
|
)`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let o of e){if(!existsSync(o))continue;let i=T(o);try{let a=t?eq(p.workspace_id,t):void 0,l=i.db.select().from(p).where(a).orderBy(desc(p.updated_at)).all();for(let c of l)n.has(c.id)||(n.add(c.id),s.push(c));}catch(a){throw new _("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let o=T(s);try{let i=eq(p.id,t),a=e?and(i,eq(p.workspace_id,e)):i,l=o.db.select().from(p).where(a).limit(1).get()??void 0;if(l)return l}catch(i){throw new _("DB_ERROR","Failed to find thread by id",i)}finally{o.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let o=T(s);try{let i=eq(p.id,t),a=e?and(i,eq(p.workspace_id,e)):i;if(o.db.select({id:p.id}).from(p).where(a).limit(1).get())return !0}catch(i){throw new _("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,o=0,i=0,a=0,l=0,c=new Set;for(let u of n){if(!existsSync(u))continue;let f=T(u);try{let m=f.db.get(sql`
|
|
267
263
|
SELECT
|
|
268
264
|
count(*) AS cnt,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import*as W from'path';import W__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Qt,{existsSync,mkdirSync,readFileSync}from'fs';import Ee from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt,lte}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,getTableConfig}from'drizzle-orm/sqlite-core';var pt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var ge=()=>fileURLToPath(import.meta.url),we=()=>W__default.dirname(ge()),b=we();var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ee.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 d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function k(a){let t=pt("better-sqlite3"),{drizzle:e}=pt("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(r,o=[])=>n.prepare(r).run(...o),close:()=>n.close()}}var zt=new Set,Re={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 Rt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ye(a,t){if(t>0||!Rt(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,o]of Object.entries(Re))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${o}`);}var Se={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function xe(a,t,e){if(!Rt(a,"__drizzle_migrations")||!Rt(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(W__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=Se[i.tag];if(!l)continue;let u=W__default.join(t,`${i.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),_=createHash("sha256").update(c).digest("hex");if(r.has(_))continue;let m=a.all("PRAGMA table_info(tasks)"),f=new Set(m.map(y=>y.name));for(let[y,j]of Object.entries(l))f.has(y)||(a.run(`ALTER TABLE tasks ADD COLUMN ${y} ${j}`),f.add(y));}}function Te(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(W__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=W__default.join(t,`${i.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],f;for(;(f=_.exec(u))!==null;)m.push({table:f[1],column:f[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(z=>z.trim()).filter(Boolean).every(z=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(z)))continue;m.every(({table:z,column:v})=>a.all(`PRAGMA table_info("${z}")`).some(U=>U.name===v))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function rt(a){let{migrate:t}=pt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=pt("drizzle-orm"),n=[W__default.join(b,"../migrations"),W__default.join(b,"migrations"),W__default.join(b,"../../../../drizzle/migrations"),W__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(W__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
|
|
1
|
+
import*as W from'path';import W__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Qt,{existsSync,mkdirSync,readFileSync}from'fs';import Ee from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt,lte}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,getTableConfig}from'drizzle-orm/sqlite-core';var pt=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var ge=()=>fileURLToPath(import.meta.url),we=()=>W__default.dirname(ge()),b=we();var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Ee.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 d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function k(a){let t=pt("better-sqlite3"),{drizzle:e}=pt("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:e(n),runRaw:(r,o=[])=>n.prepare(r).run(...o),close:()=>n.close()}}var zt=new Set,Re={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 Rt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ye(a,t){if(t>0||!Rt(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,o]of Object.entries(Re))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${o}`);}var Se={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function xe(a,t,e){if(!Rt(a,"__drizzle_migrations")||!Rt(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(W__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=Se[i.tag];if(!l)continue;let u=W__default.join(t,`${i.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),_=createHash("sha256").update(c).digest("hex");if(r.has(_))continue;let m=a.all("PRAGMA table_info(tasks)"),f=new Set(m.map(y=>y.name));for(let[y,j]of Object.entries(l))f.has(y)||(a.run(`ALTER TABLE tasks ADD COLUMN ${y} ${j}`),f.add(y));}}function Te(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(W__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=W__default.join(t,`${i.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],f;for(;(f=_.exec(u))!==null;)m.push({table:f[1],column:f[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(z=>z.trim()).filter(Boolean).every(z=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(z)))continue;m.every(({table:z,column:v})=>a.all(`PRAGMA table_info("${z}")`).some(U=>U.name===v))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function rt(a){let{migrate:t}=pt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=pt("drizzle-orm"),n=[W__default.join(b,"../migrations"),W__default.join(b,"migrations"),W__default.join(b,"../../../../drizzle/migrations"),W__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(W__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${n.join(`
|
|
3
|
-
`)}`);let o=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ye(a,i),o?.cnt&&(Te(a,r,e),xe(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function A(a,t){zt.has(t)||(rt(a),zt.add(t));}var h=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var s=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>h.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)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at)}));var G=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>G.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")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var q=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var B=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()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var st=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")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var O=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")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var L=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")},a=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));function Tt(a){let t=W.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Xt(a){let t=Tt(a);return createHash("sha256").update(t).digest("hex")}function gt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Ot=class extends x{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{rt(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=gt(basename(n)),i=`${gt(basename(dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:h.id}).from(h).where(and(eq(h.slug,c),ne$1(h.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let _=`${i}-${c}`;if(!u(_))return _}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let r of e)if(r.slug.includes("/")){let o=gt(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:o,updated_at:new Date().toISOString()}).where(eq(h.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:o,workspacePath:i}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:o,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:i,updated_at:l}).where(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(t){let e=Tt(t),n=this.openHandle(true);try{let r=Xt(e),o=basename(e),i=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:i,name:o,workspacePath:e}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
|
|
3
|
+
`)}`);let o=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ye(a,i),o?.cnt&&(Te(a,r,e),xe(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function A(a,t){zt.has(t)||(rt(a),zt.add(t));}var h=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var s=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>h.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)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at)}));var G=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>G.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")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var q=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var B=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()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var st=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")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var N=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")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var L=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")},a=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));function Tt(a){let t=W.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Xt(a){let t=Tt(a);return createHash("sha256").update(t).digest("hex")}function gt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Nt=class extends x{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{rt(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=gt(basename(n)),i=`${gt(basename(dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:h.id}).from(h).where(and(eq(h.slug,c),ne$1(h.id,e))).limit(1).all().length>0;for(let c of l)if(!u(c))return c;for(let c=2;c<1e3;c+=1){let _=`${i}-${c}`;if(!u(_))return _}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let r of e)if(r.slug.includes("/")){let o=gt(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:o,updated_at:new Date().toISOString()}).where(eq(h.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:o,workspacePath:i}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:o,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:i,updated_at:l}).where(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(t){let e=Tt(t),n=this.openHandle(true);try{let r=Xt(e),o=basename(e),i=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:i,name:o,workspacePath:e}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
|
|
4
4
|
(SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
|
|
5
5
|
FROM threads t
|
|
6
6
|
WHERE t.workspace_id = ${t}
|
|
@@ -250,14 +250,10 @@ ${n.join(`
|
|
|
250
250
|
FROM ${s}
|
|
251
251
|
${o}
|
|
252
252
|
ORDER BY ${s.started_at} ASC
|
|
253
|
-
`).map(l=>({threadId:l.thread_id,agentId:l.agent_id,startedAt:l.started_at,status:l.status,error:l.error,exitCode:l.exit_code}))}catch(o){throw new d("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}};var Lt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(eq(h.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
SELECT 1 FROM tasks parent
|
|
258
|
-
WHERE parent.id = ${t}.parent_task_id
|
|
259
|
-
AND parent.thread_id = ${t}.thread_id
|
|
260
|
-
)
|
|
253
|
+
`).map(l=>({threadId:l.thread_id,agentId:l.agent_id,startedAt:l.started_at,status:l.status,error:l.error,exitCode:l.exit_code}))}catch(o){throw new d("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}};var Lt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(eq(h.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
|
|
254
|
+
SELECT 1 FROM tasks parent
|
|
255
|
+
WHERE parent.id = ${t}.parent_task_id
|
|
256
|
+
AND parent.thread_id = ${t}.thread_id
|
|
261
257
|
)`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let o of e){if(!existsSync(o))continue;let i=k(o);try{let l=t?eq(p.workspace_id,t):void 0,u=i.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let c of u)n.has(c.id)||(n.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=k(r);try{let i=eq(p.id,t),l=e?and(i,eq(p.workspace_id,e)):i,u=o.db.select().from(p).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find thread by id",i)}finally{o.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=k(r);try{let i=eq(p.id,t),l=e?and(i,eq(p.workspace_id,e)):i;if(o.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(i){throw new d("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,o=0,i=0,l=0,u=0,c=new Set;for(let _ of n){if(!existsSync(_))continue;let m=k(_);try{let f=m.db.get(sql`
|
|
262
258
|
SELECT
|
|
263
259
|
count(*) AS cnt,
|
|
@@ -306,4 +302,4 @@ ${n.join(`
|
|
|
306
302
|
message_count = message_count + 1,
|
|
307
303
|
updated_at = ${o}
|
|
308
304
|
WHERE id = ${t}
|
|
309
|
-
`),c},{behavior:"immediate"})}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save assistant message",o)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!o)return null;let i=o.pinned?0:1,l=o.metadata?JSON.parse(o.metadata):{};if(i){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),_=0;for(let m of c){let f=m.metadata?JSON.parse(m.metadata):{};typeof f.pinOrder=="number"&&f.pinOrder>_&&(_=f.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let o=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),i=n.db.select({metadata:p.metadata}).from(p).where(o).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(o).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({starred:p.starred}).from(p).where(r).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(p).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let l=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return i.db.transaction(c=>{let _=c.select({metadata:p.metadata}).from(p).where(l).get();if(!_)return null;let m=_.metadata?JSON.parse(_.metadata):{},f=m.overdrive??{},y=r?.defaultTurns??f.defaultTurns??3,j=r?.updatedBy??"ui",z=new Date().toISOString(),v,S,U,it;switch(n){case "enable-count":{let at=r?.turns??y,dt=r?.consumeCurrent?Math.max(at-1,0):at;v=dt>0?"count":"off",S=dt,U=!0,it="count";break}case "enable-latch":{v="latch",S=0,U=!0,it="latch";break}case "disable":{v="off",S=0,U=!1;break}default:{let at=f.state??"off",dt=typeof f.remaining=="number"?f.remaining:0;if(at==="count"&&dt>0){let Mt=dt-1;Mt<=0?(v="off",S=0):(v="count",S=Mt),U=!0,it="count";}else at==="latch"?(v="latch",S=0,U=!0,it="latch"):(v="off",S=0,U=!1);break}}return m.overdrive={state:v,remaining:S,defaultTurns:y,updatedAt:z,updatedBy:j},c.update(p).set({metadata:JSON.stringify(m),updated_at:z}).where(l).run(),{applied:U,appliedMode:it,state:v,remaining:S}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var $t=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(G).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(G).where(eq(G.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(G).where(eq(G.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var Pt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(q).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(q).where(eq(q.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:q.tool_name,count:sql`count(*)`}).from(q).where(eq(q.task_id,t)).groupBy(q.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var It=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(B).where(eq(B.thread_id,t)).orderBy(asc(B.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(B).where(and(eq(B.id,e),eq(B.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(B).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(B).where(eq(B.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Bt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let o of t)r.insert(st).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:n,metadata:o.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(st).orderBy(desc(st.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function pe(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Ut=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=pe(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(O).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[O.provider,O.account_ref,O.limit_window,O.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:O.provider,bucket_start:O.bucket_start,used_percent:O.used_percent,remaining_percent:O.remaining_percent,resets_at:O.resets_at}).from(O).where(and(eq(O.limit_window,t.window),gte(O.bucket_start,t.fromIso),lte(O.bucket_start,t.toIso))).orderBy(asc(O.bucket_start)).all(),r=new Map;for(let o of n)r.has(o.provider)||r.set(o.provider,[]),r.get(o.provider).push({bucketStart:o.bucket_start,usedPercent:o.used_percent,remainingPercent:o.remaining_percent,resetsAt:o.resets_at??null});return Array.from(r.entries()).map(([o,i])=>({provider:o,points:i}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var Ht=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(L).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[L.workspace_id,L.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let n=e.db.select().from(L).where(and(eq(L.workspace_id,t.workspaceId),eq(L.month,t.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{e.close();}}findByMonth(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(L).where(and(eq(L.workspace_id,t),eq(L.month,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{n.close();}}listByWorkspace(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(L).where(eq(L.workspace_id,t)).orderBy(desc(L.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};export{x as BaseSqliteRepository,d as RepositoryError,Bt as RequestLogRepository,$t as SpanRepository,vt as TaskRepository,It as ThreadBoxRepository,Lt as ThreadRepository,Pt as ToolCallRepository,Ut as UsageLimitSnapshotRepository,Ht as UsageReportRepository,Ot as WorkspaceRepository,pe as calcBucketStart,k as openDrizzleDb,sn as pushSchema,rt as runMigrations,A as runMigrationsOnce,s as tasks};
|
|
305
|
+
`),c},{behavior:"immediate"})}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:o}).where(eq(p.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save assistant message",o)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!o)return null;let i=o.pinned?0:1,l=o.metadata?JSON.parse(o.metadata):{};if(i){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),_=0;for(let m of c){let f=m.metadata?JSON.parse(m.metadata):{};typeof f.pinOrder=="number"&&f.pinOrder>_&&(_=f.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let o=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),i=n.db.select({metadata:p.metadata}).from(p).where(o).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(o).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),o=n.db.select({starred:p.starred}).from(p).where(r).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(p).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let l=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return i.db.transaction(c=>{let _=c.select({metadata:p.metadata}).from(p).where(l).get();if(!_)return null;let m=_.metadata?JSON.parse(_.metadata):{},f=m.overdrive??{},y=r?.defaultTurns??f.defaultTurns??3,j=r?.updatedBy??"ui",z=new Date().toISOString(),v,S,U,it;switch(n){case "enable-count":{let at=r?.turns??y,dt=r?.consumeCurrent?Math.max(at-1,0):at;v=dt>0?"count":"off",S=dt,U=!0,it="count";break}case "enable-latch":{v="latch",S=0,U=!0,it="latch";break}case "disable":{v="off",S=0,U=!1;break}default:{let at=f.state??"off",dt=typeof f.remaining=="number"?f.remaining:0;if(at==="count"&&dt>0){let Mt=dt-1;Mt<=0?(v="off",S=0):(v="count",S=Mt),U=!0,it="count";}else at==="latch"?(v="latch",S=0,U=!0,it="latch"):(v="off",S=0,U=!1);break}}return m.overdrive={state:v,remaining:S,defaultTurns:y,updatedAt:z,updatedBy:j},c.update(p).set({metadata:JSON.stringify(m),updated_at:z}).where(l).run(),{applied:U,appliedMode:it,state:v,remaining:S}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Pt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(G).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(G).where(eq(G.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(G).where(eq(G.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var $t=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(q).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(q).where(eq(q.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{e.close();}}aggregateByName(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select({toolName:q.tool_name,count:sql`count(*)`}).from(q).where(eq(q.task_id,t)).groupBy(q.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{e.close();}}};var It=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(B).where(eq(B.thread_id,t)).orderBy(asc(B.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(B).where(and(eq(B.id,e),eq(B.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(B).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(B).where(eq(B.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Bt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let o of t)r.insert(st).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:n,metadata:o.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(st).orderBy(desc(st.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function pe(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Ut=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=pe(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(N).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[N.provider,N.account_ref,N.limit_window,N.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:N.provider,bucket_start:N.bucket_start,used_percent:N.used_percent,remaining_percent:N.remaining_percent,resets_at:N.resets_at}).from(N).where(and(eq(N.limit_window,t.window),gte(N.bucket_start,t.fromIso),lte(N.bucket_start,t.toIso))).orderBy(asc(N.bucket_start)).all(),r=new Map;for(let o of n)r.has(o.provider)||r.set(o.provider,[]),r.get(o.provider).push({bucketStart:o.bucket_start,usedPercent:o.used_percent,remainingPercent:o.remaining_percent,resetsAt:o.resets_at??null});return Array.from(r.entries()).map(([o,i])=>({provider:o,points:i}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var Ht=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(L).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[L.workspace_id,L.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let n=e.db.select().from(L).where(and(eq(L.workspace_id,t.workspaceId),eq(L.month,t.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{e.close();}}findByMonth(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(L).where(and(eq(L.workspace_id,t),eq(L.month,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{n.close();}}listByWorkspace(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(L).where(eq(L.workspace_id,t)).orderBy(desc(L.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};export{x as BaseSqliteRepository,d as RepositoryError,Bt as RequestLogRepository,Pt as SpanRepository,vt as TaskRepository,It as ThreadBoxRepository,Lt as ThreadRepository,$t as ToolCallRepository,Ut as UsageLimitSnapshotRepository,Ht as UsageReportRepository,Nt as WorkspaceRepository,pe as calcBucketStart,k as openDrizzleDb,sn as pushSchema,rt as runMigrations,A as runMigrationsOnce,s as tasks};
|
package/dist/index.js
CHANGED
|
@@ -47,7 +47,7 @@ ${n??""}
|
|
|
47
47
|
---
|
|
48
48
|
`)}let s=(await e.readdir(n)).filter(a=>a.endsWith(".md"));if(s.length===0)return "";let i=[];for(let a of s){let d=e.resolvePath(n,a),l=await e.readFile(d),u=Gi.exec(l);!u||!Ji.test(u[1])||Vi.test(l)&&i.push(l);}return i.join(`
|
|
49
49
|
---
|
|
50
|
-
`)}c();function Xi(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return `${e}-${t}-${r}`}async function ho(n,e=Be){let t=e.resolvePath(n,`${Xi()}.md`);return await e.exists(t)?e.readFile(t):""}Ie();c();var At=new async_hooks.AsyncLocalStorage;function zr(n){if(n)return {parentTaskId:n.parentTaskId??null,rootTraceId:n.rootTraceId,callerAgentId:n.callerAgentId??null}}c();function Qi(n){return typeof n!="string"?"":n.replace(/</g,"<").replace(/>/g,">")}function Kr(n){return n.messages.map(e=>({text:Qi(e.text),isAssistant:e.isAssistant,timestamp:e.timestamp,metadata:e.metadata,files:void 0}))}c();Ie();Oe();c();c();var it=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:J.join(ra__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return To.existsSync(e??this.resolveDbPath())}};c();function Pe(n){let e=Z("better-sqlite3"),{drizzle:t}=Z("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),{db:t(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}c();var wo=new Set,na={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 Gr(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function oa(n,e){if(e>0||!Gr(n,"tasks"))return;let t=n.all("PRAGMA table_info(tasks)"),r=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(na))r.has(o)||n.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var sa={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ia(n,e,t){if(!Gr(n,"__drizzle_migrations")||!Gr(n,"tasks"))return;let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(To.readFileSync(J__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=sa[i.tag];if(!a)continue;let d=J__namespace.default.join(e,`${i.tag}.sql`);if(!To.existsSync(d))continue;let l=To.readFileSync(d,"utf-8"),u=crypto$1.createHash("sha256").update(l).digest("hex");if(o.has(u))continue;let m=n.all("PRAGMA table_info(tasks)"),f=new Set(m.map(g=>g.name));for(let[g,h]of Object.entries(a))f.has(g)||(n.run(`ALTER TABLE tasks ADD COLUMN ${g} ${h}`),f.add(g));}}function aa(n,e,t){let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(To.readFileSync(J__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=J__namespace.default.join(e,`${i.tag}.sql`);if(!To.existsSync(a))continue;let d=To.readFileSync(a,"utf-8"),l=crypto$1.createHash("sha256").update(d).digest("hex");if(o.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],f;for(;(f=u.exec(d))!==null;)m.push({table:f[1],column:f[2]});if(m.length===0||!d.split(/-->\s*statement-breakpoint/).map(w=>w.trim()).filter(Boolean).every(w=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(w)))continue;m.every(({table:w,column:x})=>n.all(`PRAGMA table_info("${w}")`).some(_=>_.name===x))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function da(n){let{migrate:e}=Z("drizzle-orm/better-sqlite3/migrator"),{sql:t}=Z("drizzle-orm"),r=[J__namespace.default.join(__dirname,"../migrations"),J__namespace.default.join(__dirname,"migrations"),J__namespace.default.join(__dirname,"../../../../drizzle/migrations"),J__namespace.default.join(process.cwd(),"drizzle/migrations")],o=r.find(l=>To.existsSync(J__namespace.default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
50
|
+
`)}c();function Xi(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return `${e}-${t}-${r}`}async function ho(n,e=Be){let t=e.resolvePath(n,`${Xi()}.md`);return await e.exists(t)?e.readFile(t):""}Ie();c();var At=new async_hooks.AsyncLocalStorage;function zr(n){if(n)return {parentTaskId:n.parentTaskId??null,rootTraceId:n.rootTraceId,callerAgentId:n.callerAgentId??null}}c();function Qi(n){return typeof n!="string"?"":n.replace(/</g,"<").replace(/>/g,">")}function Kr(n){return n.messages.map(e=>({text:Qi(e.text),isAssistant:e.isAssistant,timestamp:e.timestamp,metadata:e.metadata,files:void 0}))}c();Ie();Oe();c();c();var it=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:J.join(ra__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return To.existsSync(e??this.resolveDbPath())}};c();function Pe(n){let e=Z("better-sqlite3"),{drizzle:t}=Z("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),r.exec("PRAGMA optimize"),{db:t(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}c();var wo=new Set,na={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 Gr(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function oa(n,e){if(e>0||!Gr(n,"tasks"))return;let t=n.all("PRAGMA table_info(tasks)"),r=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(na))r.has(o)||n.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var sa={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ia(n,e,t){if(!Gr(n,"__drizzle_migrations")||!Gr(n,"tasks"))return;let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(To.readFileSync(J__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=sa[i.tag];if(!a)continue;let d=J__namespace.default.join(e,`${i.tag}.sql`);if(!To.existsSync(d))continue;let l=To.readFileSync(d,"utf-8"),u=crypto$1.createHash("sha256").update(l).digest("hex");if(o.has(u))continue;let m=n.all("PRAGMA table_info(tasks)"),f=new Set(m.map(g=>g.name));for(let[g,h]of Object.entries(a))f.has(g)||(n.run(`ALTER TABLE tasks ADD COLUMN ${g} ${h}`),f.add(g));}}function aa(n,e,t){let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(To.readFileSync(J__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=J__namespace.default.join(e,`${i.tag}.sql`);if(!To.existsSync(a))continue;let d=To.readFileSync(a,"utf-8"),l=crypto$1.createHash("sha256").update(d).digest("hex");if(o.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],f;for(;(f=u.exec(d))!==null;)m.push({table:f[1],column:f[2]});if(m.length===0||!d.split(/-->\s*statement-breakpoint/).map(w=>w.trim()).filter(Boolean).every(w=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(w)))continue;m.every(({table:w,column:x})=>n.all(`PRAGMA table_info("${w}")`).some(_=>_.name===x))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function da(n){let{migrate:e}=Z("drizzle-orm/better-sqlite3/migrator"),{sql:t}=Z("drizzle-orm"),r=[J__namespace.default.join(__dirname,"../migrations"),J__namespace.default.join(__dirname,"migrations"),J__namespace.default.join(__dirname,"../../../../drizzle/migrations"),J__namespace.default.join(process.cwd(),"drizzle/migrations")],o=r.find(l=>To.existsSync(J__namespace.default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
51
51
|
${r.join(`
|
|
52
52
|
`)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),oa(n,i),s?.cnt&&(aa(n,o,t),ia(n,o,t)),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${d} migration${d>1?"s":""} applied).`);}}function er(n,e){wo.has(e)||(da(n),wo.add(e));}c();var I=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};c();c();var _o=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});c();var p=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},n=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(n.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));c();var xo=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>_o.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(n.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(n.workspace_id,n.updated_at)}));c();var Je=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>p.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Je.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},n=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(n.parent_span_id)}));c();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>p.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},n=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(n.timestamp)}));c();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>xo.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(n.thread_id,n.seq)}));c();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},n=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(n.partition_key)}));c();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},n=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));c();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},n=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(n.workspace_id,n.month)}));var Ne="2026-05-09",Ma="0.8.9-rc.13",De=10,Le=parseInt(Ma.split("rc.")[1]),Na=new Set(["workflow","mcp"]),Da=600*1e3,Et=class extends it{dbPath;pidNullObservedSince=new Map;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=J.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=J.dirname(t);To.existsSync(o)||To.mkdirSync(o,{recursive:true});}else if(!To.existsSync(t))throw new I("NOT_FOUND","Database not found");let r=Pe(t);if(e)try{er(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(p).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoUpdate({target:p.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${p.pid})`},setWhere:drizzleOrm.eq(p.status,"running")}).run();}catch(r){throw r instanceof I?r:new I("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{let r=e.runEpoch??null;t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
53
53
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|