@crewx/sdk 0.8.8-rc.35 → 0.8.8-rc.37
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
CHANGED
|
@@ -53,7 +53,7 @@ ${i.message}`)}let s=mt(o);if(s.documents&&typeof s.documents=="object"){let i={
|
|
|
53
53
|
${r.join(`
|
|
54
54
|
`)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Bi(n,i),s?.cnt&&Wi(n,o,t),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let c=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${d} migration${d>1?"s":""} applied).`);}}function $t(n,e){Qn.has(e)||(zi(n),Qn.add(e));}l();var M=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};l();l();var eo=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});l();var w=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},n=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));l();var ro=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>eo.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id)}));l();var Me=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>w.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Me.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));l();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>w.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));l();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>ro.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));l();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));var qr=class extends Be{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new M("NOT_FOUND","Database not found");let r=ye(t);if(e)try{$t(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(w).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoNothing().run();}catch(r){throw r instanceof M?r:new M("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
55
55
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
56
|
-
model=COALESCE(?, model) WHERE id=?`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id]);}catch(r){throw r instanceof M?r:new M("DB_ERROR","Failed to finish task",r)}finally{t.close();}}appendLog(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{let s=o.select({logs:w.logs}).from(w).where(eq(w.id,e)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(t),o.update(w).set({logs:JSON.stringify(i)}).where(eq(w.id,e)).run();},{behavior:"immediate"});}catch(o){throw o instanceof M?o:new M("DB_ERROR","Failed to append log",o)}finally{r.close();}}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(w).where(eq(w.status,"running")).orderBy(desc(w.started_at)).all()}catch(t){throw new M("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(w).orderBy(desc(w.started_at)).limit(100).all()}catch(t){throw new M("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(w).where(eq(w.id,e)).limit(1).get()??void 0}catch(r){throw new M("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:w.id,status:w.status,pid:w.pid}).from(w).where(eq(w.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(w).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(w.id,e),eq(w.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof M?r:new M("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:w.id,pid:w.pid}).from(w).where(eq(w.status,"running")).all(),r=0;for(let o of t){let s=!1;
|
|
56
|
+
model=COALESCE(?, model) WHERE id=?`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id]);}catch(r){throw r instanceof M?r:new M("DB_ERROR","Failed to finish task",r)}finally{t.close();}}appendLog(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{let s=o.select({logs:w.logs}).from(w).where(eq(w.id,e)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(t),o.update(w).set({logs:JSON.stringify(i)}).where(eq(w.id,e)).run();},{behavior:"immediate"});}catch(o){throw o instanceof M?o:new M("DB_ERROR","Failed to append log",o)}finally{r.close();}}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(w).where(eq(w.status,"running")).orderBy(desc(w.started_at)).all()}catch(t){throw new M("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(w).orderBy(desc(w.started_at)).limit(100).all()}catch(t){throw new M("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(w).where(eq(w.id,e)).limit(1).get()??void 0}catch(r){throw new M("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:w.id,status:w.status,pid:w.pid}).from(w).where(eq(w.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(w).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(w.id,e),eq(w.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof M?r:new M("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:w.id,pid:w.pid}).from(w).where(eq(w.status,"running")).all(),r=0;for(let o of t){if(!o.pid)continue;let s=!1;try{process.kill(o.pid,0),s=!0;}catch{}s||(e.db.update(w).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(w.id,o.id),eq(w.status,"running"))).run(),r++);}return r}finally{e.close();}}findTaskStatus(e,t){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=ye(o);try{let i=t?eq(w.workspace_id,t):void 0,a=i?and(eq(w.id,e),i):eq(w.id,e),d=s.db.select().from(w).where(a).limit(1).get()??void 0;if(!d){let c=or$1(eq(w.thread_id,e),and(isNull(w.thread_id),like(w.command,`%--thread=${e}%`))),u=i?and(c,i):c;d=s.db.select().from(w).where(u).orderBy(desc(w.started_at)).limit(1).get()??void 0;}if(d)return d}catch(i){throw new M("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let a=ye(i);try{let d=t?and(eq(w.parent_task_id,e),eq(w.workspace_id,t)):eq(w.parent_task_id,e),c=a.db.select().from(w).where(d).orderBy(asc(w.started_at)).all();for(let u of c)o.has(u.id)||(o.add(u.id),s.push(u));}catch(d){throw new M("DB_ERROR","Failed to find child tasks",d)}finally{a.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?sql`
|
|
57
57
|
SELECT
|
|
58
58
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
59
59
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -12,7 +12,7 @@ Message: ${e.message}
|
|
|
12
12
|
${s.join(`
|
|
13
13
|
`)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),zt(d,i),r?.cnt&&qt(d,n,e),t(d,{migrationsFolder:n});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${c} migration${c>1?"s":""} applied).`);}}function W(d,t){gt.has(t)||(Ht(d),gt.add(t));}var u=class extends Error{code;cause;constructor(t,e,s){super(e),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var z=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var l=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>z.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var Vt=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Vt.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>l.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));var V=class extends B{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new u("NOT_FOUND","Database not found");let s=b(e);if(t)try{W(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
14
14
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
15
|
-
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),n.update(o).set({logs:JSON.stringify(i)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new u("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(desc(o.started_at)).limit(100).all()}catch(e){throw new u("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new u("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(eq(o.status,"running")).all(),s=0;for(let n of e){let r=!1;
|
|
15
|
+
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),n.update(o).set({logs:JSON.stringify(i)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new u("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(desc(o.started_at)).limit(100).all()}catch(e){throw new u("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new u("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(eq(o.status,"running")).all(),s=0;for(let n of e){if(!n.pid)continue;let r=!1;try{process.kill(n.pid,0),r=!0;}catch{}r||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,n.id),eq(o.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=b(n);try{let i=e?eq(o.workspace_id,e):void 0,a=i?and(eq(o.id,t),i):eq(o.id,t),c=r.db.select().from(o).where(a).limit(1).get()??void 0;if(!c){let p=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),m=i?and(p,i):p;c=r.db.select().from(o).where(m).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new u("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!existsSync(i))continue;let a=b(i);try{let c=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),p=a.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let m of p)n.has(m.id)||(n.add(m.id),r.push(m));}catch(c){throw new u("DB_ERROR","Failed to find child tasks",c)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
16
16
|
SELECT
|
|
17
17
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
18
18
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -7,7 +7,7 @@ ${n.join(`
|
|
|
7
7
|
ORDER BY t.updated_at DESC
|
|
8
8
|
LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new d("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(f).where(eq(f.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 s=e?and(eq(f.slug,t),ne$1(f.id,e)):eq(f.slug,t);return !!n.db.select({id:f.id}).from(f).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(f).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(f).where(eq(f.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(f).where(eq(f.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:f.id,workspace_path:f.workspace_path}).from(f).where(and(eq(f.is_active,1),isNotNull(f.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))||(t.db.update(f).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(f.id,s.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(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(f).where(eq(f.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Ht=[f,i,c,H,z,N,K];function Te(){return $__default.join(te.homedir(),".crewx","crewx.db")}function Oe(a){if(!qt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return qt.copyFileSync(a,e),e}function Mt(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 Ce(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 Ae(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Ce(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Pe(a,t){let e=t?.dbPath??Te(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Oe(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Mt(a);if(!s)try{Y(a);}catch(m){let y=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!y.includes("duplicate column"))throw m}let l,u;s?(l=Ht.map(y=>getTableConfig(y).name).filter(y=>!o.has(y)),u=o):(u=Mt(a),l=[...u].filter(m=>!o.has(m)));let p=[],h=[];for(let m of Ht){let y=getTableConfig(m),S=y.name;if(!u.has(S))continue;let v=a.all(`PRAGMA table_info("${S}")`),q=new Set(v.map(B=>B.name)),V=new Set(y.columns.map(B=>B.name));for(let B of y.columns)if(!q.has(B.name)){if(!s){let ct=Ae(B);a.run(`ALTER TABLE "${S}" ADD COLUMN ${ct}`);}p.push({table:S,column:B.name});}for(let B of v)V.has(B.name)||h.push(`${S}.${B.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:h,backupPath:r}}var wt=class extends E{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(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{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
|
-
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(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(s=>{let r=s.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("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(i).where(eq(i.status,"running")).orderBy(desc(i.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(i).orderBy(desc(i.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(i).where(eq(i.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:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.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(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,t),eq(i.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:i.id,pid:i.pid}).from(i).where(eq(i.status,"running")).all(),n=0;for(let s of e){let r=!1;
|
|
10
|
+
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(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(s=>{let r=s.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("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(i).where(eq(i.status,"running")).orderBy(desc(i.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(i).orderBy(desc(i.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(i).where(eq(i.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:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.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(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,t),eq(i.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:i.id,pid:i.pid}).from(i).where(eq(i.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,s.id),eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=w(s);try{let o=e?eq(i.workspace_id,e):void 0,l=o?and(eq(i.id,t),o):eq(i.id,t),u=r.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let p=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),h=o?and(p,o):p;u=r.db.select().from(i).where(h).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=w(o);try{let u=e?and(eq(i.parent_task_id,t),eq(i.workspace_id,e)):eq(i.parent_task_id,t),p=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of p)s.has(h.id)||(s.add(h.id),r.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
11
11
|
SELECT
|
|
12
12
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
13
13
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
package/dist/index.js
CHANGED
|
@@ -53,7 +53,7 @@ ${i.message}`)}let s=gt(o);if(s.documents&&typeof s.documents=="object"){let i={
|
|
|
53
53
|
${r.join(`
|
|
54
54
|
`)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ji(n,i),s?.cnt&&Ui(n,o,t),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let c=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${d} migration${d>1?"s":""} applied).`);}}function Dt(n,e){Gn.has(e)||(Fi(n),Gn.add(e));}l();var O=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};l();l();var Qn=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()});l();var h=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)},n=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(n.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));l();var eo=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Qn.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(n.workspace_id)}));l();var Oe=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>h.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")},n=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(n.parent_span_id)}));l();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>h.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},n=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(n.timestamp)}));l();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>eo.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(n.thread_id,n.seq)}));l();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},n=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(n.partition_key)}));var Hr=class extends qe{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=W.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=W.dirname(t);fs$1.existsSync(o)||fs$1.mkdirSync(o,{recursive:true});}else if(!fs$1.existsSync(t))throw new O("NOT_FOUND","Database not found");let r=fe(t);if(e)try{Dt(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(h).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoNothing().run();}catch(r){throw r instanceof O?r:new O("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
55
55
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
56
|
-
model=COALESCE(?, model) WHERE id=?`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id]);}catch(r){throw r instanceof O?r:new O("DB_ERROR","Failed to finish task",r)}finally{t.close();}}appendLog(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{let s=o.select({logs:h.logs}).from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(t),o.update(h).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(h.id,e)).run();},{behavior:"immediate"});}catch(o){throw o instanceof O?o:new O("DB_ERROR","Failed to append log",o)}finally{r.close();}}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.status,"running")).orderBy(drizzleOrm.desc(h.started_at)).all()}catch(t){throw new O("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(h).orderBy(drizzleOrm.desc(h.started_at)).limit(100).all()}catch(t){throw new O("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get()??void 0}catch(r){throw new O("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:h.id,status:h.status,pid:h.pid}).from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(h).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(h.id,e),drizzleOrm.eq(h.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof O?r:new O("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:h.id,pid:h.pid}).from(h).where(drizzleOrm.eq(h.status,"running")).all(),r=0;for(let o of t){let s=!1;
|
|
56
|
+
model=COALESCE(?, model) WHERE id=?`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id]);}catch(r){throw r instanceof O?r:new O("DB_ERROR","Failed to finish task",r)}finally{t.close();}}appendLog(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{let s=o.select({logs:h.logs}).from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(t),o.update(h).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(h.id,e)).run();},{behavior:"immediate"});}catch(o){throw o instanceof O?o:new O("DB_ERROR","Failed to append log",o)}finally{r.close();}}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.status,"running")).orderBy(drizzleOrm.desc(h.started_at)).all()}catch(t){throw new O("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(h).orderBy(drizzleOrm.desc(h.started_at)).limit(100).all()}catch(t){throw new O("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get()??void 0}catch(r){throw new O("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:h.id,status:h.status,pid:h.pid}).from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(h).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(h.id,e),drizzleOrm.eq(h.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof O?r:new O("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:h.id,pid:h.pid}).from(h).where(drizzleOrm.eq(h.status,"running")).all(),r=0;for(let o of t){if(!o.pid)continue;let s=!1;try{process.kill(o.pid,0),s=!0;}catch{}s||(e.db.update(h).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(h.id,o.id),drizzleOrm.eq(h.status,"running"))).run(),r++);}return r}finally{e.close();}}findTaskStatus(e,t){let r=this.resolveDbPaths();for(let o of r){if(!fs$1.existsSync(o))continue;let s=fe(o);try{let i=t?drizzleOrm.eq(h.workspace_id,t):void 0,a=i?drizzleOrm.and(drizzleOrm.eq(h.id,e),i):drizzleOrm.eq(h.id,e),d=s.db.select().from(h).where(a).limit(1).get()??void 0;if(!d){let c=drizzleOrm.or(drizzleOrm.eq(h.thread_id,e),drizzleOrm.and(drizzleOrm.isNull(h.thread_id),drizzleOrm.like(h.command,`%--thread=${e}%`))),u=i?drizzleOrm.and(c,i):c;d=s.db.select().from(h).where(u).orderBy(drizzleOrm.desc(h.started_at)).limit(1).get()??void 0;}if(d)return d}catch(i){throw new O("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!fs$1.existsSync(i))continue;let a=fe(i);try{let d=t?drizzleOrm.and(drizzleOrm.eq(h.parent_task_id,e),drizzleOrm.eq(h.workspace_id,t)):drizzleOrm.eq(h.parent_task_id,e),c=a.db.select().from(h).where(d).orderBy(drizzleOrm.asc(h.started_at)).all();for(let u of c)o.has(u.id)||(o.add(u.id),s.push(u));}catch(d){throw new O("DB_ERROR","Failed to find child tasks",d)}finally{a.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?drizzleOrm.sql`
|
|
57
57
|
SELECT
|
|
58
58
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
59
59
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
package/dist/plugins/index.js
CHANGED
|
@@ -12,7 +12,7 @@ Message: ${e.message}
|
|
|
12
12
|
${s.join(`
|
|
13
13
|
`)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),It(d,i),r?.cnt&&Ut(d,n,e),t(d,{migrationsFolder:n});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${c} migration${c>1?"s":""} applied).`);}}function j(d,t){ht.has(t)||($t(d),ht.add(t));}var u=class extends Error{code;cause;constructor(t,e,s){super(e),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var B=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 o=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)},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 l=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>B.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)}));var Xt=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Xt.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(()=>o.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(()=>l.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)}));var K=class extends F{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 n=L.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new u("NOT_FOUND","Database not found");let s=w(e);if(t)try{j(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
14
14
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
15
|
-
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),n.update(o).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.started_at)).all()}catch(e){throw new u("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(drizzleOrm.desc(o.started_at)).limit(100).all()}catch(e){throw new u("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new u("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(drizzleOrm.eq(o.status,"running")).all(),s=0;for(let n of e){let r=!1;
|
|
15
|
+
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),n.update(o).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.started_at)).all()}catch(e){throw new u("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(drizzleOrm.desc(o.started_at)).limit(100).all()}catch(e){throw new u("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new u("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(drizzleOrm.eq(o.status,"running")).all(),s=0;for(let n of e){if(!n.pid)continue;let r=!1;try{process.kill(n.pid,0),r=!0;}catch{}r||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,n.id),drizzleOrm.eq(o.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=w(n);try{let i=e?drizzleOrm.eq(o.workspace_id,e):void 0,a=i?drizzleOrm.and(drizzleOrm.eq(o.id,t),i):drizzleOrm.eq(o.id,t),c=r.db.select().from(o).where(a).limit(1).get()??void 0;if(!c){let p=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),m=i?drizzleOrm.and(p,i):p;c=r.db.select().from(o).where(m).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new u("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!fs.existsSync(i))continue;let a=w(i);try{let c=e?drizzleOrm.and(drizzleOrm.eq(o.parent_task_id,t),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.eq(o.parent_task_id,t),p=a.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let m of p)n.has(m.id)||(n.add(m.id),r.push(m));}catch(c){throw new u("DB_ERROR","Failed to find child tasks",c)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
|
|
16
16
|
SELECT
|
|
17
17
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
18
18
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
package/dist/repository/index.js
CHANGED
|
@@ -7,7 +7,7 @@ ${n.join(`
|
|
|
7
7
|
ORDER BY t.updated_at DESC
|
|
8
8
|
LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new d("DB_ERROR","Failed to find threads by project",s)}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 s=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(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(h).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.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(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.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 s of e){let r=s.workspace_path;Lt.existsSync($.join(r,"crewx.yaml"))||Lt.existsSync($.join(r,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,s.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 Ft=[h,i,c,F,v,P,G];function Re(){return $__namespace.default.join(Kt__default.default.homedir(),".crewx","crewx.db")}function Ee(a){if(!Lt__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Lt__default.default.copyFileSync(a,e),e}function Ht(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 xe(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 De(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=xe(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Se(a,t){let e=t?.dbPath??Re(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Ee(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Ht(a);if(!s)try{X(a);}catch(m){let b=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!b.includes("duplicate column"))throw m}let l,u;s?(l=Ft.map(b=>sqliteCore.getTableConfig(b).name).filter(b=>!o.has(b)),u=o):(u=Ht(a),l=[...u].filter(m=>!o.has(m)));let p=[],f=[];for(let m of Ft){let b=sqliteCore.getTableConfig(m),D=b.name;if(!u.has(D))continue;let B=a.all(`PRAGMA table_info("${D}")`),L=new Set(B.map(N=>N.name)),J=new Set(b.columns.map(N=>N.name));for(let N of b.columns)if(!L.has(N.name)){if(!s){let lt=De(N);a.run(`ALTER TABLE "${D}" ADD COLUMN ${lt}`);}p.push({table:D,column:N.name});}for(let N of B)J.has(N.name)||f.push(`${D}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:f,backupPath:r}}var gt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=$.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=$.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(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{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
|
-
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(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(s=>{let r=s.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("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(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.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(i).orderBy(drizzleOrm.desc(i.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(i).where(drizzleOrm.eq(i.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:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.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(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.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:i.id,pid:i.pid}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=0;for(let s of e){let r=!1;
|
|
10
|
+
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(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(s=>{let r=s.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("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(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.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(i).orderBy(drizzleOrm.desc(i.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(i).where(drizzleOrm.eq(i.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:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.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(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.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:i.id,pid:i.pid}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,s.id),drizzleOrm.eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Lt.existsSync(s))continue;let r=w(s);try{let o=e?drizzleOrm.eq(i.workspace_id,e):void 0,l=o?drizzleOrm.and(drizzleOrm.eq(i.id,t),o):drizzleOrm.eq(i.id,t),u=r.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let p=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),f=o?drizzleOrm.and(p,o):p;u=r.db.select().from(i).where(f).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=e?drizzleOrm.and(drizzleOrm.eq(i.parent_task_id,t),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.eq(i.parent_task_id,t),p=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let f of p)s.has(f.id)||(s.add(f.id),r.push(f));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
|
|
11
11
|
SELECT
|
|
12
12
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
13
13
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|