@crewx/sdk 0.9.0-rc.20 → 0.9.0-rc.21
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 +36 -36
- package/dist/esm/plugins/index.js +8 -8
- package/dist/esm/repository/index.js +12 -12
- package/dist/index.js +42 -42
- package/dist/plugins/index.js +7 -7
- package/dist/repository/index.js +12 -12
- package/dist/repository/task.repository.d.ts +1 -0
- package/package.json +1 -1
package/dist/plugins/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var fs=require('fs'),L=require('path'),
|
|
1
|
+
'use strict';var fs=require('fs'),L=require('path'),Gt=require('os'),crypto=require('crypto'),drizzleOrm=require('drizzle-orm'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var L__namespace=/*#__PURE__*/_interopNamespace(L);var Gt__default=/*#__PURE__*/_interopDefault(Gt);var tt=(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 U=class{detach(t){}};function bt(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 U{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=L.join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",e=>{try{fs.existsSync(this.logsDir)||fs.mkdirSync(this.logsDir,{recursive:!0});let n=bt(e.timestamp),s=L.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,12 +8,12 @@ Message: ${e.message}
|
|
|
8
8
|
`;fs.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();fs.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
|
-
`;fs.appendFileSync(n,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function
|
|
11
|
+
`;fs.appendFileSync(n,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Wt(d){let t=L__namespace.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function At(d){let t=Wt(d);return crypto.createHash("sha256").update(t).digest("hex")}var X=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:L.join(Gt__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return fs.existsSync(t??this.resolveDbPath())}};function b(d){let t=tt("better-sqlite3"),{drizzle:e}=tt("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 xt=new Set,Xt={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 Yt(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(Xt))n.has(s)||d.run(`ALTER TABLE tasks ADD COLUMN ${s} ${o}`);}var Jt={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Vt(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(fs.readFileSync(L__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=Jt[i.tag];if(!a)continue;let c=L__namespace.default.join(t,`${i.tag}.sql`);if(!fs.existsSync(c))continue;let l=fs.readFileSync(c,"utf-8"),u=crypto.createHash("sha256").update(l).digest("hex");if(s.has(u))continue;let g=d.all("PRAGMA table_info(tasks)"),h=new Set(g.map(R=>R.name));for(let[R,G]of Object.entries(a))h.has(R)||(d.run(`ALTER TABLE tasks ADD COLUMN ${R} ${G}`),h.add(R));}}function Qt(d,t,e){let n=d.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(i=>i.hash)),o=JSON.parse(fs.readFileSync(L__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let a=L__namespace.default.join(t,`${i.tag}.sql`);if(!fs.existsSync(a))continue;let c=fs.readFileSync(a,"utf-8"),l=crypto.createHash("sha256").update(c).digest("hex");if(s.has(l))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,g=[],h;for(;(h=u.exec(c))!==null;)g.push({table:h[1],column:h[2]});if(g.length===0||!c.split(/-->\s*statement-breakpoint/).map(M=>M.trim()).filter(Boolean).every(M=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(M)))continue;g.every(({table:M,column:C})=>d.all(`PRAGMA table_info("${M}")`).some($=>$.name===C))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${i.when})`);}}function Zt(d){let{migrate:t}=tt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=tt("drizzle-orm"),n=[L__namespace.default.join(__dirname,"../migrations"),L__namespace.default.join(__dirname,"migrations"),L__namespace.default.join(__dirname,"../../../../drizzle/migrations"),L__namespace.default.join(process.cwd(),"drizzle/migrations")],s=n.find(l=>fs.existsSync(L__namespace.default.join(l,"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),Gt(d,i),o?.cnt&&(Jt(d,s,e),Yt(d,s,e)),t(d,{migrationsFolder:s});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function nt(d,t){xt.has(t)||(Vt(d),xt.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 Y=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var r=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)},d=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(d.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Y.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)},d=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(d.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(d.workspace_id,d.updated_at)}));var oe=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>r.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>oe.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},d=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>r.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},d=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(d.thread_id,d.seq)}));sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},d=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(d.partition_key)}));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")},d=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));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")},d=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(d.workspace_id,d.month)}));function Lt(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 B="2026-05-09",Te="0.8.9-rc.13",F=10,z=parseInt(Te.split("rc.")[1]),ye=new Set(["workflow","mcp"]),Ae=600*1e3,dt=class extends X{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=L.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=L.dirname(e);fs.existsSync(s)||fs.mkdirSync(s,{recursive:true});}else if(!fs.existsSync(e))throw new _("NOT_FOUND","Database not found");let n=b(e);if(t)try{nt(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:drizzleOrm.sql`COALESCE(excluded.pid, ${r.pid})`},setWhere:drizzleOrm.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=?,
|
|
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),Yt(d,i),o?.cnt&&(Qt(d,s,e),Vt(d,s,e)),t(d,{migrationsFolder:s});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let l=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function nt(d,t){xt.has(t)||(Zt(d),xt.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 Y=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var r=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)},d=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(d.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Y.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)},d=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(d.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(d.workspace_id,d.updated_at)}));var ae=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>r.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>ae.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},d=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>r.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},d=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(d.thread_id,d.seq)}));sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},d=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(d.partition_key)}));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")},d=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));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")},d=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(d.workspace_id,d.month)}));function Lt(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 B="2026-05-09",ye="0.8.9-rc.13",F=10,z=parseInt(ye.split("rc.")[1]),Ae=new Set(["workflow","mcp"]),Mt=600*1e3,lt=class extends X{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=L.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=L.dirname(e);fs.existsSync(s)||fs.mkdirSync(s,{recursive:true});}else if(!fs.existsSync(e))throw new _("NOT_FOUND","Database not found");let n=b(e);if(t)try{nt(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:drizzleOrm.sql`COALESCE(excluded.pid, ${r.pid})`},setWhere:drizzleOrm.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
|
-
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(drizzleOrm.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(drizzleOrm.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(drizzleOrm.eq(r.status,"running")).orderBy(drizzleOrm.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(drizzleOrm.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(drizzleOrm.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(drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(r.id,t),drizzleOrm.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(drizzleOrm.eq(r.status,"running")).all(),n=Date.now(),s=new Set,o=0;for(let i of e){if(i.pid){let l=!1;try{process.kill(i.pid,0),l=!0;}catch{}l||(t.db.update(r).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(r.id,i.id),drizzleOrm.eq(r.status,"running"))).run(),o++);continue}if(
|
|
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(drizzleOrm.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(drizzleOrm.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(drizzleOrm.eq(r.status,"running")).orderBy(drizzleOrm.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(drizzleOrm.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(drizzleOrm.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(drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(r.id,t),drizzleOrm.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(drizzleOrm.eq(r.status,"running")).all(),n=Date.now(),s=new Set,o=0;for(let i of e){if(i.pid){let l=!1;try{process.kill(i.pid,0),l=!0;}catch{}l||(t.db.update(r).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(r.id,i.id),drizzleOrm.eq(r.status,"running"))).run(),o++);continue}if(Ae.has(i.platform??"cli"))continue;let a=`${i.id}:${i.run_epoch??0}`;s.add(a);let c=this.pidNullObservedSince.get(a);if(c===void 0){this.pidNullObservedSince.set(a,n);continue}n-c>=Mt&&(t.db.update(r).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(r.id,i.id),drizzleOrm.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();}}reapRunningWorkflowTasks(t=Mt){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let n=new Date(Date.now()-t).toISOString();return e.db.update(r).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(r.status,"running"),drizzleOrm.eq(r.platform,"workflow"),drizzleOrm.isNull(r.pid),drizzleOrm.lt(r.started_at,n))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!fs.existsSync(s))continue;let o=b(s);try{let i=e?drizzleOrm.eq(r.workspace_id,e):void 0,a=i?drizzleOrm.and(drizzleOrm.eq(r.id,t),i):drizzleOrm.eq(r.id,t),c=o.db.select().from(r).where(a).limit(1).get()??void 0;if(!c){let l=drizzleOrm.or(drizzleOrm.eq(r.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(r.thread_id),drizzleOrm.like(r.command,`%--thread=${t}%`))),u=i?drizzleOrm.and(l,i):l;c=o.db.select().from(r).where(u).orderBy(drizzleOrm.desc(r.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new _("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,o=[];for(let i of n){if(!fs.existsSync(i))continue;let a=b(i);try{let c=e?drizzleOrm.and(drizzleOrm.eq(r.parent_task_id,t),drizzleOrm.eq(r.workspace_id,e)):drizzleOrm.eq(r.parent_task_id,t),l=a.db.select().from(r).where(c).orderBy(drizzleOrm.asc(r.started_at)).all();for(let u of l)s.has(u.id)||(s.add(u.id),o.push(u));}catch(c){throw new _("DB_ERROR","Failed to find child tasks",c)}finally{a.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
|
|
17
17
|
SELECT
|
|
18
18
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
19
19
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -255,7 +255,7 @@ ${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 wt=class extends U{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=L.join(t?.dbRoot??
|
|
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 wt=class extends U{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=L.join(t?.dbRoot??Gt.homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new lt({dbPath:this.dbPath}),n=process.cwd(),o=fs.existsSync(L.join(n,"crewx.yaml"))||fs.existsSync(L.join(n,"crewx.yml"))?At(n):null,i=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let c=a.callerAgentId??null,l=a.parentTaskId??null,u=a.rootTraceId??a.traceId,g=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});e.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:i,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??o,callerAgentId:c,parentTaskId:l,traceId:u,metadata:g,threadId:a.threadId??null});}catch{}}),t.on("task:output",a=>{try{e.appendLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch{}}),t.on("task:end",a=>{try{let c=typeof a.metadata?.runEpoch=="number"?a.metadata.runEpoch:null;e.finishTask({id:a.traceId,status:a.error?"failed":"success",result:a.result??null,error:a.error?JSON.stringify(a.error):null,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null,runEpoch:c});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var ct=class extends X{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=L.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=L.dirname(e);fs.existsSync(s)||fs.mkdirSync(s,{recursive:true});}else if(!fs.existsSync(e))throw new _("NOT_FOUND","Database not found");let n=b(e);if(t)try{nt(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:Y.id}).from(Y).where(drizzleOrm.eq(Y.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return drizzleOrm.sql.raw(`NOT EXISTS (
|
|
259
259
|
SELECT 1 FROM tasks parent
|
|
260
260
|
WHERE parent.id = ${t}.parent_task_id
|
|
261
261
|
AND parent.thread_id = ${t}.thread_id
|
|
@@ -314,5 +314,5 @@ ${n.join(`
|
|
|
314
314
|
`),l},{behavior:"immediate"})}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save user message",o)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.update(p).set({last_message:e,updated_at:o}).where(drizzleOrm.eq(p.id,t)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save assistant message",o)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(p).set(s).where(drizzleOrm.eq(p.id,t)).run();}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to update thread",s)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let s=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),o=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(s).get();if(!o)return null;let i=o.pinned?0:1,a=o.metadata?JSON.parse(o.metadata):{};if(i){let c=e?drizzleOrm.and(drizzleOrm.eq(p.pinned,1),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.pinned,1),l=n.db.select({metadata:p.metadata}).from(p).where(c).all(),u=0;for(let g of l){let h=g.metadata?JSON.parse(g.metadata):{};typeof h.pinOrder=="number"&&h.pinOrder>u&&(u=h.pinOrder);}a.pinOrder=u+1;}else delete a.pinOrder;return n.db.update(p).set({pinned:i,metadata:Object.keys(a).length>0?JSON.stringify(a):null}).where(s).run(),{pinned:!!i}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to toggle pin",s)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let s=0;s<t.length;s++){let o=e?drizzleOrm.and(drizzleOrm.eq(p.id,t[s]),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t[s]),i=n.db.select({metadata:p.metadata}).from(p).where(o).get();if(!i)continue;let a=i.metadata?JSON.parse(i.metadata):{};a.pinOrder=s+1,n.db.update(p).set({metadata:JSON.stringify(a)}).where(o).run();}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to reorder pins",s)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let s=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t),o=n.db.select({starred:p.starred}).from(p).where(s).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(p).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,s){let i=this.openHandle(true);try{let a=e?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.eq(p.id,t);return i.db.transaction(l=>{let u=l.select({metadata:p.metadata}).from(p).where(a).get();if(!u)return null;let g=u.metadata?JSON.parse(u.metadata):{},h=g.overdrive??{},R=s?.defaultTurns??h.defaultTurns??3,G=s?.updatedBy??"ui",M=new Date().toISOString(),C,v,$,V;switch(n){case "enable-count":{let Q=s?.turns??R,Z=s?.consumeCurrent?Math.max(Q-1,0):Q;C=Z>0?"count":"off",v=Z,$=!0,V="count";break}case "enable-latch":{C="latch",v=0,$=!0,V="latch";break}case "disable":{C="off",v=0,$=!1;break}default:{let Q=h.state??"off",Z=typeof h.remaining=="number"?h.remaining:0;if(Q==="count"&&Z>0){let St=Z-1;St<=0?(C="off",v=0):(C="count",v=St),$=!0,V="count";}else Q==="latch"?(C="latch",v=0,$=!0,V="latch"):(C="off",v=0,$=!1);break}}return g.overdrive={state:C,remaining:v,defaultTurns:R,updatedAt:M,updatedBy:G},l.update(p).set({metadata:JSON.stringify(g),updated_at:M}).where(a).run(),{applied:$,appliedMode:V,state:C,remaining:v}},{behavior:"immediate"})}catch(a){throw a instanceof _?a:new _("DB_ERROR","Failed to resolve overdrive",a)}finally{i.close();}}};function Le(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
315
315
|
`).filter(s=>!(s.startsWith("Loaded ")&&s.includes("layouts from")||s.includes("[dotenv@")||s.includes("[Nest]")&&s.includes("DEBUG")||s.startsWith("Registered custom layout:")||s.startsWith("Updated custom layout:"))).join(`
|
|
316
316
|
`).trim()}function Ie(d){if(!d)return "";let t=d;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(n=>n?.type==="text"&&n?.text).map(n=>n.text).join(`
|
|
317
|
-
`):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=Le(t);}return t}var
|
|
318
|
-
`)[0].slice(0,200)),e.push({id:`${n.id}-assistant`,text:s,isAssistant:true,timestamp:new Date(n.started_at).getTime(),metadata:i});}}return e}};var Et=class extends U{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new
|
|
317
|
+
`):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=Le(t);}return t}var ut=class{dbPath;constructor(t){this.dbPath=t??L.join(Gt.homedir(),".crewx","crewx.db");}getThreadRepo(){return new ct({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,n){let s=this.getThreadRepo(),o=s.findThreadById(t);if(o){if(o.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${o.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return s.ensureThread(t,e,n),{created:true}}async fetchHistory(t,e){let n=e?.limit??100,s=this.getThreadRepo(),o=s.findThreadById(t),i=s.findTopLevelTasks(t,void 0,n),a=new Set(["queued","cancelled"]);i=i.filter(u=>(!u.status||!a.has(u.status))&&(!e?.currentTraceId||u.trace_id!==e.currentTraceId));let c=o?.platform??"cli",l=this.rowsToMessages(i);return {threadId:t,platform:c,messages:l,metadata:{title:o?.title??void 0,firstMessage:o?.first_message??void 0,lastMessage:o?.last_message??void 0,messageCount:o?.message_count??0,updatedAt:o?.updated_at?new Date(o.updated_at).getTime():void 0}}}async saveUserMessage(t,e,n,s){let{firstMessage:o}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:o}}async saveAssistantMessage(t,e,n,s){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}close(){}normalizeStatus(t){if(t&&!["success","completed","done"].includes(t)){if(["failed","error"].includes(t))return "failed";if(t==="running")return "running"}}rowsToMessages(t){let e=[];for(let n of t){n.prompt&&e.push({id:`${n.id}-user`,text:n.prompt,isAssistant:false,timestamp:new Date(n.started_at).getTime(),metadata:{caller_agent_id:n.caller_agent_id}});let s=Ie(n.result),o=this.normalizeStatus(n.status);if(s||o==="running"||o==="failed"){let i={agent_id:n.agent_id,task_id:n.id};o&&(i.status=o),o==="failed"&&n.error&&(i.reason=n.error.split(`
|
|
318
|
+
`)[0].slice(0,200)),e.push({id:`${n.id}-assistant`,text:s,isAssistant:true,timestamp:new Date(n.started_at).getTime(),metadata:i});}}return e}};var Et=class extends U{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new ut(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,n,s){}async afterAssistantMessage(t,e,n){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let n=e.platform??"cli";try{let s=await this._provider.ensureThread(e.threadId,n,e.workspaceId),o=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,o.id,s.created||o.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let n=e.metadata?.threadId;if(!n)return;let s=e.agentRef?.replace(/^@/,"")??"";try{let{id:o}=await this._provider.saveAssistantMessage(n,e.result,s);await this.afterAssistantMessage(n,o,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=Et;exports.FileLoggerPlugin=pt;exports.SqliteTracingPlugin=wt;
|
package/dist/repository/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
'use strict';var Qt=require('fs'),j=require('path'),
|
|
1
|
+
'use strict';var Qt=require('fs'),j=require('path'),we=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Qt__default=/*#__PURE__*/_interopDefault(Qt);var j__namespace=/*#__PURE__*/_interopNamespace(j);var we__default=/*#__PURE__*/_interopDefault(we);var ut=(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 S=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:j.join(we__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return Qt.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=ut("better-sqlite3"),{drizzle:e}=ut("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 Mt=new Set,ke={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 be(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(ke))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${o}`);}var Ee={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Re(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(Qt.readFileSync(j__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=Ee[i.tag];if(!l)continue;let u=j__namespace.default.join(t,`${i.tag}.sql`);if(!Qt.existsSync(u))continue;let c=Qt.readFileSync(u,"utf-8"),_=crypto.createHash("sha256").update(c).digest("hex");if(r.has(_))continue;let m=a.all("PRAGMA table_info(tasks)"),f=new Set(m.map(R=>R.name));for(let[R,q]of Object.entries(l))f.has(R)||(a.run(`ALTER TABLE tasks ADD COLUMN ${R} ${q}`),f.add(R));}}function ye(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(Qt.readFileSync(j__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=j__namespace.default.join(t,`${i.tag}.sql`);if(!Qt.existsSync(l))continue;let u=Qt.readFileSync(l,"utf-8"),c=crypto.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:C})=>a.all(`PRAGMA table_info("${z}")`).some(B=>B.name===C))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function nt(a){let{migrate:t}=ut("drizzle-orm/better-sqlite3/migrator"),{sql:e}=ut("drizzle-orm"),n=[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")],r=n.find(c=>Qt.existsSync(j__namespace.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),we(a,i),o?.cnt&&(Ee(a,r,e),be(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 D(a,t){Mt.has(t)||(nt(a),Mt.add(t));}var h=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var s=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)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>h.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)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at)}));var K=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>K.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")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var F=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>s.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()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var I=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var rt=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")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));var A=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")},a=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var v=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")},a=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));function xt(a){let t=j__namespace.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 Yt(a){let t=xt(a);return crypto.createHash("sha256").update(t).digest("hex")}function mt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var At=class extends S{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?j.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{nt(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=mt(j.basename(n)),i=`${mt(j.basename(j.dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:h.id}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.slug,c),drizzleOrm.ne(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=mt(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:o,updated_at:new Date().toISOString()}).where(drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(h.id,n),drizzleOrm.isNull(h.workspace_path))).run();}registerWorkspace(t){let e=xt(t),n=this.openHandle(true);try{let r=Yt(e),o=j.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?drizzleOrm.eq(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:drizzleOrm.sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(drizzleOrm.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(drizzleOrm.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(drizzleOrm.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(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(drizzleOrm.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),be(a,i),o?.cnt&&(ye(a,r,e),Re(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 D(a,t){Mt.has(t)||(nt(a),Mt.add(t));}var h=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var s=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)},a=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(a.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>h.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)},a=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at)}));var K=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>K.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")},a=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(a.parent_span_id)}));var F=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>s.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()},a=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(a.timestamp)}));var I=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(a.thread_id,a.seq)}));var rt=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")},a=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(a.partition_key)}));var N=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")},a=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var v=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")},a=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));function Tt(a){let t=j__namespace.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 Yt(a){let t=Tt(a);return crypto.createHash("sha256").update(t).digest("hex")}function mt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Nt=class extends S{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?j.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{nt(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=mt(j.basename(n)),i=`${mt(j.basename(j.dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:h.id}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.slug,c),drizzleOrm.ne(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=mt(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:o,updated_at:new Date().toISOString()}).where(drizzleOrm.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(drizzleOrm.and(drizzleOrm.eq(h.id,n),drizzleOrm.isNull(h.workspace_path))).run();}registerWorkspace(t){let e=Tt(t),n=this.openHandle(true);try{let r=Yt(e),o=j.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?drizzleOrm.eq(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:drizzleOrm.sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(drizzleOrm.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(drizzleOrm.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(drizzleOrm.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(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(drizzleOrm.sql`SELECT t.*,
|
|
4
4
|
(SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
|
|
5
5
|
FROM threads t
|
|
6
6
|
WHERE t.workspace_id = ${t}
|
|
7
7
|
ORDER BY t.updated_at DESC
|
|
8
|
-
LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?drizzleOrm.and(drizzleOrm.eq(h.slug,t),drizzleOrm.ne(h.id,e)):drizzleOrm.eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let o=this.openHandle(true);try{let i=new Date().toISOString();o.db.insert(h).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=o.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof d?i:new d("DB_ERROR","Failed to insert workspace",i)}finally{o.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let o=r.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!o)throw new d("NOT_FOUND",`Workspace ${t} not found`);return o}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update workspace",o)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.is_active,1),drizzleOrm.isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let o=r.workspace_path;Qt.existsSync(j.join(o,"crewx.yaml"))||Qt.existsSync(j.join(o,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(drizzleOrm.eq(h.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Zt=[h,s,p,K,F,I,rt];function
|
|
8
|
+
LIMIT ${e.limit} OFFSET ${e.offset}`),total:r?.count??0}}catch(r){throw new d("DB_ERROR","Failed to find threads by project",r)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let r=e?drizzleOrm.and(drizzleOrm.eq(h.slug,t),drizzleOrm.ne(h.id,e)):drizzleOrm.eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let o=this.openHandle(true);try{let i=new Date().toISOString();o.db.insert(h).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=o.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof d?i:new d("DB_ERROR","Failed to insert workspace",i)}finally{o.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let o=r.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!o)throw new d("NOT_FOUND",`Workspace ${t} not found`);return o}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update workspace",o)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.is_active,1),drizzleOrm.isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let o=r.workspace_path;Qt.existsSync(j.join(o,"crewx.yaml"))||Qt.existsSync(j.join(o,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,r.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(drizzleOrm.eq(h.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Zt=[h,s,p,K,F,I,rt];function Qe(){return j__namespace.default.join(we__default.default.homedir(),".crewx","crewx.db")}function Ve(a){if(!Qt__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Qt__default.default.copyFileSync(a,e),e}function te(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Ze(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function tn(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Ze(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function en(a,t){let e=t?.dbPath??Qe(),n=t?.force??false,r=t?.dryRun??false,o=r?null:Ve(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=te(a);if(!r)try{nt(a);}catch(m){let f=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!f.includes("duplicate column"))throw m}let l,u;r?(l=Zt.map(f=>sqliteCore.getTableConfig(f).name).filter(f=>!i.has(f)),u=i):(u=te(a),l=[...u].filter(m=>!i.has(m)));let c=[],_=[];for(let m of Zt){let f=sqliteCore.getTableConfig(m),R=f.name;if(!u.has(R))continue;let q=a.all(`PRAGMA table_info("${R}")`),z=new Set(q.map(y=>y.name)),C=new Set(f.columns.map(y=>y.name));for(let y of f.columns)if(!z.has(y.name)){if(!r){let B=tn(y);a.run(`ALTER TABLE "${R}" ADD COLUMN ${B}`);}c.push({table:R,column:y.name});}for(let y of q)C.has(y.name)||_.push(`${R}.${y.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:_,backupPath:o}}function ee(a){let t=a.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 X="2026-05-09",dn="0.8.9-rc.13",J=10,Q=parseInt(dn.split("rc.")[1]),ln=new Set(["workflow","mcp"]),se=600*1e3,Ct=class extends S{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(s).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:s.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${s.pid})`},setWhere:drizzleOrm.eq(s.status,"running")}).run();}catch(n){throw n instanceof d?n:new d("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=?,
|
|
9
9
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
10
10
|
model=COALESCE(?, model)
|
|
11
|
-
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 d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({logs:s.logs}).from(s).where(drizzleOrm.eq(s.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(e),r.update(s).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(s.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).where(drizzleOrm.eq(s.status,"running")).orderBy(drizzleOrm.desc(s.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).orderBy(drizzleOrm.desc(s.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(s).where(drizzleOrm.eq(s.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:s.id,status:s.status,pid:s.pid}).from(s).where(drizzleOrm.eq(s.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(s.id,t),drizzleOrm.eq(s.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(drizzleOrm.eq(s.status,"running")).all(),n=Date.now(),r=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(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(s.id,i.id),drizzleOrm.eq(s.status,"running"))).run(),o++);continue}if(
|
|
11
|
+
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 d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({logs:s.logs}).from(s).where(drizzleOrm.eq(s.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(e),r.update(s).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(s.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).where(drizzleOrm.eq(s.status,"running")).orderBy(drizzleOrm.desc(s.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).orderBy(drizzleOrm.desc(s.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(s).where(drizzleOrm.eq(s.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:s.id,status:s.status,pid:s.pid}).from(s).where(drizzleOrm.eq(s.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(s.id,t),drizzleOrm.eq(s.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(drizzleOrm.eq(s.status,"running")).all(),n=Date.now(),r=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(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(s.id,i.id),drizzleOrm.eq(s.status,"running"))).run(),o++);continue}if(ln.has(i.platform??"cli"))continue;let l=`${i.id}:${i.run_epoch??0}`;r.add(l);let u=this.pidNullObservedSince.get(l);if(u===void 0){this.pidNullObservedSince.set(l,n);continue}n-u>=se&&(t.db.update(s).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(s.id,i.id),drizzleOrm.eq(s.status,"running"))).run(),o++,this.pidNullObservedSince.delete(l));}for(let i of Array.from(this.pidNullObservedSince.keys()))r.has(i)||this.pidNullObservedSince.delete(i);return o}finally{t.close();}}reapRunningWorkflowTasks(t=se){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let n=new Date(Date.now()-t).toISOString();return e.db.update(s).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(s.status,"running"),drizzleOrm.eq(s.platform,"workflow"),drizzleOrm.isNull(s.pid),drizzleOrm.lt(s.started_at,n))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Qt.existsSync(r))continue;let o=k(r);try{let i=e?drizzleOrm.eq(s.workspace_id,e):void 0,l=i?drizzleOrm.and(drizzleOrm.eq(s.id,t),i):drizzleOrm.eq(s.id,t),u=o.db.select().from(s).where(l).limit(1).get()??void 0;if(!u){let c=drizzleOrm.or(drizzleOrm.eq(s.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(s.thread_id),drizzleOrm.like(s.command,`%--thread=${t}%`))),_=i?drizzleOrm.and(c,i):c;u=o.db.select().from(s).where(_).orderBy(drizzleOrm.desc(s.started_at)).limit(1).get()??void 0;}if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!Qt.existsSync(i))continue;let l=k(i);try{let u=e?drizzleOrm.and(drizzleOrm.eq(s.parent_task_id,t),drizzleOrm.eq(s.workspace_id,e)):drizzleOrm.eq(s.parent_task_id,t),c=l.db.select().from(s).where(u).orderBy(drizzleOrm.asc(s.started_at)).all();for(let _ of c)r.has(_.id)||(r.add(_.id),o.push(_));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
|
|
12
12
|
SELECT
|
|
13
13
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
14
14
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -29,7 +29,7 @@ ${n.join(`
|
|
|
29
29
|
FROM tasks
|
|
30
30
|
GROUP BY workspace_id
|
|
31
31
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
32
|
-
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,o=0,i=0,l=0;for(let u of n){if(!Qt.existsSync(u))continue;let c=
|
|
32
|
+
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,o=0,i=0,l=0;for(let u of n){if(!Qt.existsSync(u))continue;let c=k(u);try{let _=drizzleOrm.or(drizzleOrm.eq(s.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(s.thread_id),drizzleOrm.like(s.command,`%--thread=${t}%`))),m=e?drizzleOrm.and(_,drizzleOrm.eq(s.workspace_id,e)):_,f=c.db.select({id:s.id,input_tokens:s.input_tokens,output_tokens:s.output_tokens,cost_usd:s.cost_usd}).from(s).where(m).all();for(let R of f)r.has(R.id)||(r.add(R.id),o+=R.input_tokens??0,i+=R.output_tokens??0,l+=R.cost_usd??0);}catch(_){throw new d("DB_ERROR","Failed to get thread token usage",_)}finally{c.close();}}return {inputTokens:o,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!Qt.existsSync(i))continue;let l=k(i);try{let u=drizzleOrm.or(drizzleOrm.eq(s.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(s.thread_id),drizzleOrm.like(s.command,`%--thread=${t}%`))),c=e?drizzleOrm.and(u,drizzleOrm.eq(s.workspace_id,e)):u,_=l.db.select().from(s).where(c).orderBy(drizzleOrm.asc(s.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),o.push(m));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return o}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(drizzleOrm.eq(s.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(drizzleOrm.inArray(s.agent_id,r));let o=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;o&&n.push(drizzleOrm.inArray(s.status,o));let i=t.q??t.search;i&&n.push(drizzleOrm.like(s.prompt,`%${i}%`)),t.from&&n.push(drizzleOrm.gte(s.started_at,t.from)),t.to&&n.push(drizzleOrm.lt(s.started_at,t.to));let l=n.length>0?drizzleOrm.and(...n):void 0,u=e.db.select({count:drizzleOrm.sql`count(*)`}).from(s).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?drizzleOrm.asc(s.started_at):drizzleOrm.desc(s.started_at);return {rows:e.db.select().from(s).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?drizzleOrm.sql`
|
|
33
33
|
SELECT
|
|
34
34
|
t.agent_id,
|
|
35
35
|
t.workspace_id,
|
|
@@ -167,7 +167,7 @@ ${n.join(`
|
|
|
167
167
|
AND t.started_at < ${e}
|
|
168
168
|
GROUP BY date(t.started_at), t.agent_id
|
|
169
169
|
ORDER BY date(t.started_at) ASC
|
|
170
|
-
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(o){throw new d("DB_ERROR","Failed to get agent usage trend",o)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(s).where(drizzleOrm.and(drizzleOrm.eq(s.id,t),drizzleOrm.eq(s.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString(),i=n?drizzleOrm.and(drizzleOrm.eq(s.id,t),drizzleOrm.eq(s.status,"running"),drizzleOrm.eq(s.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(s.id,t),drizzleOrm.eq(s.status,"running"));r.db.update(s).set({status:"failed",error:e,completed_at:o}).where(i).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to mark task failed",o)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!Qt.existsSync(i))continue;let l=
|
|
170
|
+
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(o){throw new d("DB_ERROR","Failed to get agent usage trend",o)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(s).where(drizzleOrm.and(drizzleOrm.eq(s.id,t),drizzleOrm.eq(s.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString(),i=n?drizzleOrm.and(drizzleOrm.eq(s.id,t),drizzleOrm.eq(s.status,"running"),drizzleOrm.eq(s.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(s.id,t),drizzleOrm.eq(s.status,"running"));r.db.update(s).set({status:"failed",error:e,completed_at:o}).where(i).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to mark task failed",o)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!Qt.existsSync(i))continue;let l=k(i);try{let u=e?drizzleOrm.and(drizzleOrm.like(s.prompt,`%${t}%`),drizzleOrm.eq(s.workspace_id,e)):drizzleOrm.like(s.prompt,`%${t}%`),c=l.db.select().from(s).where(u).orderBy(drizzleOrm.asc(s.started_at)).all();for(let _ of c)r.has(_.id)||(r.add(_.id),o.push(_));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return o}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=drizzleOrm.sql`
|
|
171
171
|
CASE
|
|
172
172
|
WHEN ${s.model} LIKE 'claude-%' OR ${s.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
173
173
|
WHEN ${s.model} LIKE 'gpt-%' OR ${s.model} LIKE 'codex-%' THEN 'codex'
|
|
@@ -250,11 +250,11 @@ ${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 vt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=
|
|
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 vt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return drizzleOrm.sql.raw(`NOT EXISTS (
|
|
254
254
|
SELECT 1 FROM tasks parent
|
|
255
255
|
WHERE parent.id = ${t}.parent_task_id
|
|
256
256
|
AND parent.thread_id = ${t}.thread_id
|
|
257
|
-
)`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let o of e){if(!Qt.existsSync(o))continue;let i=
|
|
257
|
+
)`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let o of e){if(!Qt.existsSync(o))continue;let i=k(o);try{let l=t?drizzleOrm.eq(p.workspace_id,t):void 0,u=i.db.select().from(p).where(l).orderBy(drizzleOrm.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(!Qt.existsSync(r))continue;let o=k(r);try{let i=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(i,drizzleOrm.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(!Qt.existsSync(r))continue;let o=k(r);try{let i=drizzleOrm.eq(p.id,t),l=e?drizzleOrm.and(i,drizzleOrm.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(!Qt.existsSync(_))continue;let m=k(_);try{let f=m.db.get(drizzleOrm.sql`
|
|
258
258
|
SELECT
|
|
259
259
|
count(*) AS cnt,
|
|
260
260
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -271,7 +271,7 @@ ${n.join(`
|
|
|
271
271
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
272
272
|
AND ${this.topLevelTaskPredicateSql()}
|
|
273
273
|
${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
|
|
274
|
-
`);for(let q of R)c.add(q.agent_id);}catch(f){throw new d("DB_ERROR","Failed to aggregate task stats",f)}finally{m.close();}}return {taskCount:r,inputTokens:o,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),o=new Set,i=[];for(let l of r){if(!Qt.existsSync(l))continue;let u=
|
|
274
|
+
`);for(let q of R)c.add(q.agent_id);}catch(f){throw new d("DB_ERROR","Failed to aggregate task stats",f)}finally{m.close();}}return {taskCount:r,inputTokens:o,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),o=new Set,i=[];for(let l of r){if(!Qt.existsSync(l))continue;let u=k(l);try{let c;n!==void 0?c=u.db.all(drizzleOrm.sql`
|
|
275
275
|
SELECT * FROM (
|
|
276
276
|
SELECT child.*,
|
|
277
277
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -288,7 +288,7 @@ ${n.join(`
|
|
|
288
288
|
AND ${this.topLevelTaskPredicateSql()}
|
|
289
289
|
${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
|
|
290
290
|
ORDER BY child.started_at ASC
|
|
291
|
-
`);for(let _ of c)o.has(_.id)||(o.add(_.id),i.push(_));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&r.length>1){let l=new Map;for(let u of i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,_)=>(_.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,n));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!Qt.existsSync(i))continue;let l=
|
|
291
|
+
`);for(let _ of c)o.has(_.id)||(o.add(_.id),i.push(_));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&r.length>1){let l=new Map;for(let u of i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,_)=>(_.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,n));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!Qt.existsSync(i))continue;let l=k(i);try{let u=drizzleOrm.eq(s.thread_id,t),c=e?drizzleOrm.and(u,drizzleOrm.eq(s.workspace_id,e)):u,_=l.db.select().from(s).where(c).orderBy(drizzleOrm.asc(s.started_at)).all();for(let m of _)r.has(m.id)||(r.add(m.id),o.push(m));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return o}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let o of r){if(!Qt.existsSync(o))continue;let i=k(o);try{let l=drizzleOrm.and(drizzleOrm.eq(s.id,e),drizzleOrm.eq(s.thread_id,t)),u=n?drizzleOrm.and(l,drizzleOrm.eq(s.workspace_id,n)):l,c=i.db.select().from(s).where(u).limit(1).get();if(!c)continue;let _=i.db.select().from(s).where(drizzleOrm.eq(s.parent_task_id,c.id)).orderBy(drizzleOrm.asc(s.started_at)).all();return {task:c,children:_}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasksQuery(t,e){return drizzleOrm.sql`
|
|
292
292
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
293
293
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
294
294
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -298,7 +298,7 @@ ${n.join(`
|
|
|
298
298
|
AND ${this.topLevelTaskPredicateSql()}
|
|
299
299
|
${e?drizzleOrm.sql`AND child.workspace_id = ${e}`:drizzleOrm.sql``}
|
|
300
300
|
ORDER BY child.started_at ASC
|
|
301
|
-
`}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let o of r){if(!Qt.existsSync(o))continue;let i=
|
|
301
|
+
`}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let o of r){if(!Qt.existsSync(o))continue;let i=k(o);try{let l=i.db.all(this.batchFetchTasksQuery(t,e));for(let u of l){let c=u.thread_id;n.has(c)||n.set(c,[]),n.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}explainBatchFetchTasksPlan(t,e){let n=this.resolveDbPaths();for(let r of n){if(!Qt.existsSync(r))continue;let o=k(r);try{return o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,e)}`).map(l=>l.detail)}finally{o.close();}}return []}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=drizzleOrm.eq(p.id,t),i=n?drizzleOrm.and(o,drizzleOrm.eq(p.workspace_id,n)):o;if(!r.db.select({id:p.id}).from(p).where(i).limit(1).get())return;r.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(p.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update thread title",o)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,o=new Date().toISOString();if(n.db.select({id:p.id,message_count:p.message_count}).from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get()){let l={updated_at:o};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(p).set(l).where(drizzleOrm.eq(p.id,t)).run();}else n.db.insert(p).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:o,updated_at:o}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let o=n?this.validateWorkspaceId(r,n):null,i=r.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get();if(i){o&&!i.workspace_id&&r.db.update(p).set({workspace_id:o}).where(drizzleOrm.eq(p.id,t)).run();return}let l=new Date().toISOString();r.db.insert(p).values({id:t,platform:e,workspace_id:o,message_count:0,created_at:l,updated_at:l}).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to ensure thread",o)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let o=new Date().toISOString();return {firstMessage:r.db.transaction(l=>{let c=l.select({message_count:p.message_count}).from(p).where(drizzleOrm.eq(p.id,t)).limit(1).get()?.message_count===0;return l.run(drizzleOrm.sql`
|
|
302
302
|
UPDATE threads
|
|
303
303
|
SET first_message = COALESCE(first_message, ${e}),
|
|
304
304
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
|
|
@@ -306,4 +306,4 @@ ${n.join(`
|
|
|
306
306
|
message_count = message_count + 1,
|
|
307
307
|
updated_at = ${o}
|
|
308
308
|
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(drizzleOrm.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(drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.pinned,1),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.id,t[r]),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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??{},R=r?.defaultTurns??f.defaultTurns??3,q=r?.updatedBy??"ui",z=new Date().toISOString(),C,y,B,ot;switch(n){case "enable-count":{let it=r?.turns??R,at=r?.consumeCurrent?Math.max(it-1,0):it;C=at>0?"count":"off",y=at,B=!0,ot="count";break}case "enable-latch":{C="latch",y=0,B=!0,ot="latch";break}case "disable":{C="off",y=0,B=!1;break}default:{let it=f.state??"off",at=typeof f.remaining=="number"?f.remaining:0;if(it==="count"&&at>0){let Ht=at-1;Ht<=0?(C="off",y=0):(C="count",y=Ht),B=!0,ot="count";}else it==="latch"?(C="latch",y=0,B=!0,ot="latch"):(C="off",y=0,B=!1);break}}return m.overdrive={state:C,remaining:y,defaultTurns:R,updatedAt:z,updatedBy:q},c.update(p).set({metadata:JSON.stringify(m),updated_at:z}).where(l).run(),{applied:B,appliedMode:ot,state:C,remaining:y}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Lt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(K).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(K).where(drizzleOrm.eq(K.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(K).where(drizzleOrm.eq(K.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 S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(F).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(F).where(drizzleOrm.eq(F.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:F.tool_name,count:drizzleOrm.sql`count(*)`}).from(F).where(drizzleOrm.eq(F.task_id,t)).groupBy(F.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 $t=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get())throw new 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(I).where(drizzleOrm.eq(I.thread_id,t)).orderBy(drizzleOrm.asc(I.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(I).where(drizzleOrm.and(drizzleOrm.eq(I.id,e),drizzleOrm.eq(I.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(I).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(I).where(drizzleOrm.eq(I.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 It=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(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(rt).values({id:crypto.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(rt).orderBy(drizzleOrm.desc(rt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function ue(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Bt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=ue(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(A).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:[A.provider,A.account_ref,A.limit_window,A.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:A.provider,bucket_start:A.bucket_start,used_percent:A.used_percent,remaining_percent:A.remaining_percent,resets_at:A.resets_at}).from(A).where(drizzleOrm.and(drizzleOrm.eq(A.limit_window,t.window),drizzleOrm.gte(A.bucket_start,t.fromIso),drizzleOrm.lte(A.bucket_start,t.toIso))).orderBy(drizzleOrm.asc(A.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 Ut=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(v).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:[v.workspace_id,v.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(v).where(drizzleOrm.and(drizzleOrm.eq(v.workspace_id,t.workspaceId),drizzleOrm.eq(v.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(v).where(drizzleOrm.and(drizzleOrm.eq(v.workspace_id,t),drizzleOrm.eq(v.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(v).where(drizzleOrm.eq(v.workspace_id,t)).orderBy(drizzleOrm.desc(v.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};exports.BaseSqliteRepository=S;exports.RepositoryError=d;exports.RequestLogRepository=It;exports.SpanRepository=Lt;exports.TaskRepository=Ct;exports.ThreadBoxRepository=$t;exports.ThreadRepository=vt;exports.ToolCallRepository=Pt;exports.UsageLimitSnapshotRepository=Bt;exports.UsageReportRepository=Ut;exports.WorkspaceRepository=At;exports.calcBucketStart=ue;exports.openDrizzleDb=w;exports.pushSchema=Ze;exports.runMigrations=nt;exports.runMigrationsOnce=D;exports.tasks=s;
|
|
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(drizzleOrm.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(drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.pinned,1),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.id,t[r]),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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?drizzleOrm.and(drizzleOrm.eq(p.id,t),drizzleOrm.eq(p.workspace_id,e)):drizzleOrm.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??{},R=r?.defaultTurns??f.defaultTurns??3,q=r?.updatedBy??"ui",z=new Date().toISOString(),C,y,B,ot;switch(n){case "enable-count":{let it=r?.turns??R,at=r?.consumeCurrent?Math.max(it-1,0):it;C=at>0?"count":"off",y=at,B=!0,ot="count";break}case "enable-latch":{C="latch",y=0,B=!0,ot="latch";break}case "disable":{C="off",y=0,B=!1;break}default:{let it=f.state??"off",at=typeof f.remaining=="number"?f.remaining:0;if(it==="count"&&at>0){let Ht=at-1;Ht<=0?(C="off",y=0):(C="count",y=Ht),B=!0,ot="count";}else it==="latch"?(C="latch",y=0,B=!0,ot="latch"):(C="off",y=0,B=!1);break}}return m.overdrive={state:C,remaining:y,defaultTurns:R,updatedAt:z,updatedBy:q},c.update(p).set({metadata:JSON.stringify(m),updated_at:z}).where(l).run(),{applied:B,appliedMode:ot,state:C,remaining:y}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var Lt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(K).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(K).where(drizzleOrm.eq(K.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(K).where(drizzleOrm.eq(K.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 S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(F).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(F).where(drizzleOrm.eq(F.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:F.tool_name,count:drizzleOrm.sql`count(*)`}).from(F).where(drizzleOrm.eq(F.task_id,t)).groupBy(F.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 $t=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(drizzleOrm.eq(p.id,e)).limit(1).get())throw new 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(I).where(drizzleOrm.eq(I.thread_id,t)).orderBy(drizzleOrm.asc(I.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(I).where(drizzleOrm.and(drizzleOrm.eq(I.id,e),drizzleOrm.eq(I.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(I).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(I).where(drizzleOrm.eq(I.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 It=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(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(rt).values({id:crypto.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(rt).orderBy(drizzleOrm.desc(rt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function _e(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Bt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=_e(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(drizzleOrm.and(drizzleOrm.eq(N.limit_window,t.window),drizzleOrm.gte(N.bucket_start,t.fromIso),drizzleOrm.lte(N.bucket_start,t.toIso))).orderBy(drizzleOrm.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 Ut=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=j.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=j.dirname(e);Qt.existsSync(r)||Qt.mkdirSync(r,{recursive:true});}else if(!Qt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(v).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:[v.workspace_id,v.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(v).where(drizzleOrm.and(drizzleOrm.eq(v.workspace_id,t.workspaceId),drizzleOrm.eq(v.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(v).where(drizzleOrm.and(drizzleOrm.eq(v.workspace_id,t),drizzleOrm.eq(v.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(v).where(drizzleOrm.eq(v.workspace_id,t)).orderBy(drizzleOrm.desc(v.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};exports.BaseSqliteRepository=S;exports.RepositoryError=d;exports.RequestLogRepository=It;exports.SpanRepository=Lt;exports.TaskRepository=Ct;exports.ThreadBoxRepository=$t;exports.ThreadRepository=vt;exports.ToolCallRepository=Pt;exports.UsageLimitSnapshotRepository=Bt;exports.UsageReportRepository=Ut;exports.WorkspaceRepository=Nt;exports.calcBucketStart=_e;exports.openDrizzleDb=k;exports.pushSchema=en;exports.runMigrations=nt;exports.runMigrationsOnce=D;exports.tasks=s;
|
|
@@ -112,6 +112,7 @@ export declare class TaskRepository extends BaseSqliteRepository {
|
|
|
112
112
|
pid?: number;
|
|
113
113
|
};
|
|
114
114
|
reapOrphanedTasks(): number;
|
|
115
|
+
reapRunningWorkflowTasks(graceMs?: number): number;
|
|
115
116
|
findTaskStatus(taskId: string, workspaceId?: string): TaskRow | undefined;
|
|
116
117
|
findChildTasks(parentTaskId: string, workspaceId?: string): TaskRow[];
|
|
117
118
|
getWorkspaceUsageSummary(workspaceId?: string): Array<{
|