@crewx/sdk 0.9.0-rc.10 → 0.9.0-rc.11
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/config/pricing.d.ts +1 -2
- package/dist/esm/index.js +58 -58
- package/dist/esm/plugins/index.js +39 -39
- package/dist/esm/repository/index.js +5 -5
- package/dist/esm/testing/index.js +1 -1
- package/dist/facade/Crewx.d.ts +3 -0
- package/dist/index.js +59 -59
- package/dist/plugins/index.js +39 -39
- package/dist/provider/bridge.d.ts +1 -0
- package/dist/repository/index.js +5 -5
- package/dist/repository/task.repository.d.ts +2 -0
- package/dist/testing/index.js +1 -1
- package/package.json +1 -1
|
@@ -6,14 +6,14 @@ Started: ${e.timestamp.toLocaleString()}
|
|
|
6
6
|
Message: ${e.message}
|
|
7
7
|
|
|
8
8
|
`;writeFileSync(n,r,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toISOString();appendFileSync(s,`[${n}] STDOUT: ${e.output}
|
|
9
|
-
`,"utf8");}catch{}}),t.on("task:end",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toLocaleString(),r=e.error?`failed: ${e.error.message}`:"completed successfully",
|
|
9
|
+
`,"utf8");}catch{}}),t.on("task:end",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toLocaleString(),r=e.error?`failed: ${e.error.message}`:"completed successfully",o=`[${n}] INFO: Task ${r} in ${e.durationMs}ms
|
|
10
10
|
[${n}] INFO: Process closed with exit code: ${e.error?1:0}
|
|
11
|
-
`;appendFileSync(s,
|
|
11
|
+
`;appendFileSync(s,o,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function jt(d){let t=$.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function yt(d){let t=jt(d);return 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:join(Xt.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};function T(d){let t=tt("better-sqlite3"),{drizzle:e}=tt("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),{db:e(s),runRaw:(n,r=[])=>s.prepare(n).run(...r),close:()=>s.close()}}var xt=new Set,Yt={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 pt(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Jt(d,t){if(t>0||!pt(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),s=new Set(e.map(n=>n.name));for(let[n,r]of Object.entries(Yt))s.has(n)||d.run(`ALTER TABLE tasks ADD COLUMN ${n} ${r}`);}var Vt={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function Qt(d,t,e){if(!pt(d,"__drizzle_migrations")||!pt(d,"tasks"))return;let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(o=>o.hash)),r=JSON.parse(readFileSync($__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let a=Vt[o.tag];if(!a)continue;let l=$__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let c=readFileSync(l,"utf-8"),_=createHash("sha256").update(c).digest("hex");if(n.has(_))continue;let f=d.all("PRAGMA table_info(tasks)"),g=new Set(f.map(b=>b.name));for(let[b,G]of Object.entries(a))g.has(b)||(d.run(`ALTER TABLE tasks ADD COLUMN ${b} ${G}`),g.add(b));}}function Zt(d,t,e){let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(o=>o.hash)),r=JSON.parse(readFileSync($__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let a=$__default.join(t,`${o.tag}.sql`);if(!existsSync(a))continue;let l=readFileSync(a,"utf-8"),c=createHash("sha256").update(l).digest("hex");if(n.has(c))continue;let _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],g;for(;(g=_.exec(l))!==null;)f.push({table:g[1],column:g[2]});if(f.length===0||!l.split(/-->\s*statement-breakpoint/).map(M=>M.trim()).filter(Boolean).every(M=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(M)))continue;f.every(({table:M,column:O})=>d.all(`PRAGMA table_info("${M}")`).some(L=>L.name===O))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function te(d){let{migrate:t}=tt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=tt("drizzle-orm"),s=[$__default.join(k,"../migrations"),$__default.join(k,"migrations"),$__default.join(k,"../../../../drizzle/migrations"),$__default.join(process.cwd(),"drizzle/migrations")],n=s.find(c=>existsSync($__default.join(c,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
|
|
12
12
|
${s.join(`
|
|
13
|
-
`)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),
|
|
13
|
+
`)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;r?.cnt&&(o=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Jt(d,o),r?.cnt&&(Zt(d,n,e),Qt(d,n,e)),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(l>0){let c=r?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function st(d,t){xt.has(t)||(te(d),xt.add(t));}var p=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 Y=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 i=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var u=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Y.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 de=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>de.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(()=>i.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(()=>u.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},d=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(d.provider,d.account_ref,d.limit_window,d.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(d.limit_window,d.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(d.provider,d.limit_window,d.bucket_start)}));var W="2026-05-09",be="0.8.9-rc.13",j=10,K=parseInt(be.split("rc.")[1]),Te=new Set(["workflow","mcp"]),Re=600*1e3,dt=class extends X{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new p("NOT_FOUND","Database not found");let s=T(e);if(t)try{st(s.db,e);}catch(n){throw s.close(),n}return s}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}).onConflictDoUpdate({target:i.id,set:{pid:sql`COALESCE(excluded.pid, ${i.pid})`},setWhere:eq(i.status,"running")}).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let s=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
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,s]);}catch(s){throw s instanceof
|
|
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,s]);}catch(s){throw s instanceof p?s:new p("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:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),n.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof p?n:new p("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(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all()}catch(e){throw new p("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 p("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(s){throw new p("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:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.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(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:s.pid??void 0}}catch(s){throw s instanceof p?s:new p("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:i.id,pid:i.pid,platform:i.platform,run_epoch:i.run_epoch}).from(i).where(eq(i.status,"running")).all(),s=Date.now(),n=new Set,r=0;for(let o of e){if(o.pid){let c=!1;try{process.kill(o.pid,0),c=!0;}catch{}c||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,o.id),eq(i.status,"running"))).run(),r++);continue}if(Te.has(o.platform??"cli"))continue;let a=`${o.id}:${o.run_epoch??0}`;n.add(a);let l=this.pidNullObservedSince.get(a);if(l===void 0){this.pidNullObservedSince.set(a,s);continue}s-l>=Re&&(t.db.update(i).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(i.id,o.id),eq(i.status,"running"))).run(),r++,this.pidNullObservedSince.delete(a));}for(let o of Array.from(this.pidNullObservedSince.keys()))n.has(o)||this.pidNullObservedSince.delete(o);return r}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=T(n);try{let o=e?eq(i.workspace_id,e):void 0,a=o?and(eq(i.id,t),o):eq(i.id,t),l=r.db.select().from(i).where(a).limit(1).get()??void 0;if(!l){let c=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),_=o?and(c,o):c;l=r.db.select().from(i).where(_).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(l)return l}catch(o){throw new p("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let a=T(o);try{let l=e?and(eq(i.parent_task_id,t),eq(i.workspace_id,e)):eq(i.parent_task_id,t),c=a.db.select().from(i).where(l).orderBy(asc(i.started_at)).all();for(let _ of c)n.has(_.id)||(n.add(_.id),r.push(_));}catch(l){throw new p("DB_ERROR","Failed to find child tasks",l)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
17
17
|
SELECT
|
|
18
18
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
19
19
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -34,7 +34,7 @@ ${s.join(`
|
|
|
34
34
|
FROM tasks
|
|
35
35
|
GROUP BY workspace_id
|
|
36
36
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
37
|
-
`)}catch(s){throw new
|
|
37
|
+
`)}catch(s){throw new p("DB_ERROR","Failed to get workspace usage summary",s)}finally{e.close();}}getThreadTokenUsage(t,e){let s=this.resolveDbPaths(),n=new Set,r=0,o=0,a=0;for(let l of s){if(!existsSync(l))continue;let c=T(l);try{let _=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),f=e?and(_,eq(i.workspace_id,e)):_,g=c.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(f).all();for(let b of g)n.has(b.id)||(n.add(b.id),r+=b.input_tokens??0,o+=b.output_tokens??0,a+=b.cost_usd??0);}catch(_){throw new p("DB_ERROR","Failed to get thread token usage",_)}finally{c.close();}}return {inputTokens:r,outputTokens:o,costUsd:a}}findTasksByThread(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let a=T(o);try{let l=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),c=e?and(l,eq(i.workspace_id,e)):l,_=a.db.select().from(i).where(c).orderBy(asc(i.started_at)).all();for(let f of _)n.has(f.id)||(n.add(f.id),r.push(f));}catch(l){throw new p("DB_ERROR","Failed to find tasks by thread",l)}finally{a.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(i.workspace_id,t.workspaceId));let n=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;n&&s.push(inArray(i.agent_id,n));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&s.push(inArray(i.status,r));let o=t.q??t.search;o&&s.push(like(i.prompt,`%${o}%`)),t.from&&s.push(gte(i.started_at,t.from)),t.to&&s.push(lt$1(i.started_at,t.to));let a=s.length>0?and(...s):void 0,l=e.db.select({count:sql`count(*)`}).from(i).where(a).get(),c=(t.sortDir??"DESC")==="ASC"?asc(i.started_at):desc(i.started_at);return {rows:e.db.select().from(i).where(a).orderBy(c).limit(t.limit).offset(t.offset).all(),total:l?.count??0}}catch(s){throw new p("DB_ERROR","Failed to find all tasks",s)}finally{e.close();}}getAgentUsage(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
|
|
38
38
|
SELECT
|
|
39
39
|
t.agent_id,
|
|
40
40
|
t.workspace_id,
|
|
@@ -119,7 +119,7 @@ ${s.join(`
|
|
|
119
119
|
), 0)
|
|
120
120
|
+ COALESCE(SUM(t.output_tokens), 0)
|
|
121
121
|
) DESC
|
|
122
|
-
`).map(
|
|
122
|
+
`).map(o=>({agentId:o.agent_id,workspaceId:o.workspace_id??null,totalTasks:o.total_tasks,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(r){throw new p("DB_ERROR","Failed to get agent usage",r)}finally{n.close();}}getAgentUsageTrendRaw(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(s?sql`
|
|
123
123
|
SELECT
|
|
124
124
|
date(t.started_at) AS date,
|
|
125
125
|
t.agent_id,
|
|
@@ -172,43 +172,43 @@ ${s.join(`
|
|
|
172
172
|
AND t.started_at < ${e}
|
|
173
173
|
GROUP BY date(t.started_at), t.agent_id
|
|
174
174
|
ORDER BY date(t.started_at) ASC
|
|
175
|
-
`).map(
|
|
175
|
+
`).map(o=>({date:o.date,agentId:o.agent_id,inputTokens:o.input_tokens,outputTokens:o.output_tokens,cachedInputTokens:o.cached_input_tokens,costUsd:o.cost_usd,totalTokens:o.input_tokens+o.output_tokens}))}catch(r){throw new p("DB_ERROR","Failed to get agent usage trend",r)}finally{n.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(i).where(and(eq(i.id,t),eq(i.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new p("DB_ERROR","Failed to find task for stop",n)}finally{s.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString(),o=s?and(eq(i.id,t),eq(i.status,"running"),eq(i.workspace_id,s)):and(eq(i.id,t),eq(i.status,"running"));n.db.update(i).set({status:"failed",error:e,completed_at:r}).where(o).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let a=T(o);try{let l=e?and(like(i.prompt,`%${t}%`),eq(i.workspace_id,e)):like(i.prompt,`%${t}%`),c=a.db.select().from(i).where(l).orderBy(asc(i.started_at)).all();for(let _ of c)n.has(_.id)||(n.add(_.id),r.push(_));}catch(l){throw new p("DB_ERROR","Failed to find tasks by prompt hint",l)}finally{a.close();}}return r}getProviderUsage(t,e,s){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=sql`
|
|
176
176
|
CASE
|
|
177
|
-
WHEN ${
|
|
178
|
-
WHEN ${
|
|
179
|
-
WHEN ${
|
|
180
|
-
WHEN ${
|
|
181
|
-
WHEN ${
|
|
182
|
-
WHEN ${
|
|
177
|
+
WHEN ${i.model} LIKE 'claude-%' OR ${i.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
178
|
+
WHEN ${i.model} LIKE 'gpt-%' OR ${i.model} LIKE 'codex-%' THEN 'codex'
|
|
179
|
+
WHEN ${i.model} LIKE 'gemini-%' THEN 'gemini'
|
|
180
|
+
WHEN ${i.model} LIKE 'zai-%' OR ${i.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
181
|
+
WHEN ${i.model} LIKE 'minimax/%' THEN 'minimax'
|
|
182
|
+
WHEN ${i.model} LIKE 'qwen%' THEN 'qwen'
|
|
183
183
|
ELSE 'unknown'
|
|
184
184
|
END
|
|
185
|
-
`,
|
|
186
|
-
COALESCE(${
|
|
185
|
+
`,o=sql`
|
|
186
|
+
COALESCE(${i.input_tokens}, 0)
|
|
187
187
|
+ CASE
|
|
188
|
-
WHEN ${
|
|
188
|
+
WHEN ${i.started_at} >= ${W}
|
|
189
189
|
AND (
|
|
190
|
-
${
|
|
191
|
-
OR (${
|
|
192
|
-
OR (${
|
|
190
|
+
${i.crewx_version} IS NULL
|
|
191
|
+
OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
|
|
192
|
+
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${j}) AS INTEGER) < ${K})
|
|
193
193
|
)
|
|
194
|
-
THEN COALESCE(${
|
|
194
|
+
THEN COALESCE(${i.cached_input_tokens}, 0)
|
|
195
195
|
ELSE 0
|
|
196
196
|
END
|
|
197
|
-
`,a=s?sql`WHERE ${
|
|
197
|
+
`,a=s?sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${t} AND ${i.started_at} < ${e} AND ${i.workspace_id} = ${s}`:sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${t} AND ${i.started_at} < ${e}`;return n.db.all(sql`
|
|
198
198
|
SELECT
|
|
199
199
|
${r} AS provider,
|
|
200
200
|
COUNT(*) AS total_tasks,
|
|
201
|
-
COALESCE(SUM(${
|
|
202
|
-
COALESCE(SUM(${
|
|
203
|
-
COALESCE(SUM(${
|
|
204
|
-
COALESCE(SUM(${
|
|
205
|
-
COALESCE(SUM(${
|
|
206
|
-
MAX(${
|
|
207
|
-
FROM ${
|
|
201
|
+
COALESCE(SUM(${o}), 0) AS input_tokens,
|
|
202
|
+
COALESCE(SUM(${i.output_tokens}), 0) AS output_tokens,
|
|
203
|
+
COALESCE(SUM(${i.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
204
|
+
COALESCE(SUM(${i.cost_usd}), 0) AS cost_usd,
|
|
205
|
+
COALESCE(SUM(${i.duration_ms}), 0) AS active_duration_ms,
|
|
206
|
+
MAX(${i.completed_at}) AS last_active_at
|
|
207
|
+
FROM ${i}
|
|
208
208
|
${a}
|
|
209
209
|
GROUP BY provider
|
|
210
|
-
ORDER BY (COALESCE(SUM(${
|
|
211
|
-
`).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(r){throw new
|
|
210
|
+
ORDER BY (COALESCE(SUM(${o}), 0) + COALESCE(SUM(${i.output_tokens}), 0)) DESC
|
|
211
|
+
`).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(r){throw new p("DB_ERROR","Failed to get provider usage",r)}finally{n.close();}}};var kt=class extends U{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new dt({dbPath:this.dbPath}),s=process.cwd(),r=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?yt(s):null,o=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let l=a.callerAgentId??null,c=a.parentTaskId??null,_=a.rootTraceId??a.traceId,f=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});e.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:o,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??r,callerAgentId:l,parentTaskId:c,traceId:_,metadata:f,threadId:a.threadId??null});}catch{}}),t.on("task:output",a=>{try{e.appendLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch{}}),t.on("task:end",a=>{try{let l=typeof a.metadata?.runEpoch=="number"?a.metadata.runEpoch:null;e.finishTask({id:a.traceId,status:a.error?"failed":"success",result:a.result??null,error:a.error?JSON.stringify(a.error):null,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null,runEpoch:l});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var lt=class extends X{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new p("NOT_FOUND","Database not found");let s=T(e);if(t)try{st(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:Y.id}).from(Y).where(eq(Y.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
|
|
212
212
|
${t}.parent_task_id IS NULL
|
|
213
213
|
OR ${t}.parent_task_id = ''
|
|
214
214
|
OR NOT EXISTS (
|
|
@@ -216,7 +216,7 @@ ${s.join(`
|
|
|
216
216
|
WHERE parent.id = ${t}.parent_task_id
|
|
217
217
|
AND parent.thread_id = ${t}.thread_id
|
|
218
218
|
)
|
|
219
|
-
)`)}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!existsSync(r))continue;let
|
|
219
|
+
)`)}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!existsSync(r))continue;let o=T(r);try{let a=t?eq(u.workspace_id,t):void 0,l=o.db.select().from(u).where(a).orderBy(desc(u.updated_at)).all();for(let c of l)s.has(c.id)||(s.add(c.id),n.push(c));}catch(a){throw new p("DB_ERROR","Failed to find all threads",a)}finally{o.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=T(n);try{let o=eq(u.id,t),a=e?and(o,eq(u.workspace_id,e)):o,l=r.db.select().from(u).where(a).limit(1).get()??void 0;if(l)return l}catch(o){throw new p("DB_ERROR","Failed to find thread by id",o)}finally{r.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=T(n);try{let o=eq(u.id,t),a=e?and(o,eq(u.workspace_id,e)):o;if(r.db.select({id:u.id}).from(u).where(a).limit(1).get())return !0}catch(o){throw new p("DB_ERROR","Failed to check thread existence",o)}finally{r.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),n=0,r=0,o=0,a=0,l=0,c=new Set;for(let _ of s){if(!existsSync(_))continue;let f=T(_);try{let g=f.db.get(sql`
|
|
220
220
|
SELECT
|
|
221
221
|
count(*) AS cnt,
|
|
222
222
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -227,13 +227,13 @@ ${s.join(`
|
|
|
227
227
|
WHERE child.thread_id = ${t}
|
|
228
228
|
AND ${this.topLevelTaskPredicateSql()}
|
|
229
229
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
230
|
-
`);g&&(n+=g.cnt,r+=g.total_input,
|
|
230
|
+
`);g&&(n+=g.cnt,r+=g.total_input,o+=g.total_output,a+=g.total_cached,l+=g.total_cost);let b=f.db.all(sql`
|
|
231
231
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
232
232
|
WHERE child.thread_id = ${t}
|
|
233
233
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
234
234
|
AND ${this.topLevelTaskPredicateSql()}
|
|
235
235
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
236
|
-
`);for(let G of b)c.add(G.agent_id);}catch(g){throw new
|
|
236
|
+
`);for(let G of b)c.add(G.agent_id);}catch(g){throw new p("DB_ERROR","Failed to aggregate task stats",g)}finally{f.close();}}return {taskCount:n,inputTokens:r,outputTokens:o,cachedInputTokens:a,costUsd:l,agentIds:Array.from(c)}}findTopLevelTasks(t,e,s){let n=this.resolveDbPaths(),r=new Set,o=[];for(let a of n){if(!existsSync(a))continue;let l=T(a);try{let c;s!==void 0?c=l.db.all(sql`
|
|
237
237
|
SELECT * FROM (
|
|
238
238
|
SELECT child.*,
|
|
239
239
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -250,13 +250,13 @@ ${s.join(`
|
|
|
250
250
|
AND ${this.topLevelTaskPredicateSql()}
|
|
251
251
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
252
252
|
ORDER BY child.started_at ASC
|
|
253
|
-
`);for(let
|
|
253
|
+
`);for(let _ of c)r.has(_.id)||(r.add(_.id),o.push(_));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}if(s!==void 0&&n.length>1){let a=new Map;for(let l of o){let c=l.agent_id??"";a.has(c)||a.set(c,[]),a.get(c).push(l);}o=[];for(let l of a.values())l.sort((c,_)=>(_.started_at??"").localeCompare(c.started_at??"")),o.push(...l.slice(0,s));o.sort((l,c)=>(l.started_at??"").localeCompare(c.started_at??""));}return o}findAllTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let o of s){if(!existsSync(o))continue;let a=T(o);try{let l=eq(i.thread_id,t),c=e?and(l,eq(i.workspace_id,e)):l,_=a.db.select().from(i).where(c).orderBy(asc(i.started_at)).all();for(let f of _)n.has(f.id)||(n.add(f.id),r.push(f));}catch(l){throw new p("DB_ERROR","Failed to find all tasks for thread",l)}finally{a.close();}}return r}findTaskById(t,e,s){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=T(r);try{let a=and(eq(i.id,e),eq(i.thread_id,t)),l=s?and(a,eq(i.workspace_id,s)):a,c=o.db.select().from(i).where(l).limit(1).get();if(!c)continue;let _=o.db.select().from(i).where(eq(i.parent_task_id,c.id)).orderBy(asc(i.started_at)).all();return {task:c,children:_}}catch(a){throw new p("DB_ERROR","Failed to find task by id",a)}finally{o.close();}}}batchFetchTasks(t,e){let s=new Map;if(t.length===0)return s;let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=T(r);try{let a=o.db.all(sql`
|
|
254
254
|
SELECT child.* FROM tasks child
|
|
255
255
|
WHERE child.thread_id IN (${sql.join(t.map(l=>sql`${l}`),sql`, `)})
|
|
256
256
|
AND ${this.topLevelTaskPredicateSql()}
|
|
257
257
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
258
258
|
ORDER BY child.started_at ASC
|
|
259
|
-
`);for(let l of a){let c=l.thread_id;s.has(c)||s.set(c,[]),s.get(c).push(l);}}catch(a){throw new
|
|
259
|
+
`);for(let l of a){let c=l.thread_id;s.has(c)||s.set(c,[]),s.get(c).push(l);}}catch(a){throw new p("DB_ERROR","Failed to batch fetch tasks",a)}finally{o.close();}}return s}updateThreadTitle(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=eq(u.id,t),o=s?and(r,eq(u.workspace_id,s)):r;if(!n.db.select({id:u.id}).from(u).where(o).limit(1).get())return;n.db.update(u).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(u.id,t)).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to update thread title",r)}finally{n.close();}}upsertThread(t,e){let s=this.openHandle(true);try{let n=e.workspaceId?this.validateWorkspaceId(s,e.workspaceId):null,r=new Date().toISOString();if(s.db.select({id:u.id,message_count:u.message_count}).from(u).where(eq(u.id,t)).limit(1).get()){let a={updated_at:r};e.title!==void 0&&(a.title=e.title),e.titleLocked!==void 0&&(a.title_locked=e.titleLocked?1:0),s.db.update(u).set(a).where(eq(u.id,t)).run();}else s.db.insert(u).values({id:t,platform:e.platform,workspace_id:n,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to upsert thread",n)}finally{s.close();}}ensureThread(t,e,s){let n=this.openHandle(true);try{let r=s?this.validateWorkspaceId(n,s):null,o=n.db.select({id:u.id,platform:u.platform,workspace_id:u.workspace_id}).from(u).where(eq(u.id,t)).limit(1).get();if(o){r&&!o.workspace_id&&n.db.update(u).set({workspace_id:r}).where(eq(u.id,t)).run();return}let a=new Date().toISOString();n.db.insert(u).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:a,updated_at:a}).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to ensure thread",r)}finally{n.close();}}saveUserMessage(t,e,s){if(!this.dbExists())return {firstMessage:false};let n=this.openHandle(true);try{let r=new Date().toISOString();return {firstMessage:n.db.transaction(a=>{let c=a.select({message_count:u.message_count}).from(u).where(eq(u.id,t)).limit(1).get()?.message_count===0;return a.run(sql`
|
|
260
260
|
UPDATE threads
|
|
261
261
|
SET first_message = COALESCE(first_message, ${e}),
|
|
262
262
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
|
|
@@ -264,8 +264,8 @@ ${s.join(`
|
|
|
264
264
|
message_count = message_count + 1,
|
|
265
265
|
updated_at = ${r}
|
|
266
266
|
WHERE id = ${t}
|
|
267
|
-
`),c},{behavior:"immediate"})}}catch(r){throw r instanceof
|
|
267
|
+
`),c},{behavior:"immediate"})}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to save user message",r)}finally{n.close();}}saveAssistantMessage(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString();n.db.update(u).set({last_message:e,updated_at:r}).where(eq(u.id,t)).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to save assistant message",r)}finally{n.close();}}updateThread(t,e){if(!this.dbExists())return;let s=this.openHandle(true);try{let n={updated_at:new Date().toISOString()};e.title!==void 0&&(n.title=e.title,n.title_locked=1),e.titleLocked!==void 0&&(n.title_locked=e.titleLocked?1:0),s.db.update(u).set(n).where(eq(u.id,t)).run();}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to update thread",n)}finally{s.close();}}togglePin(t,e){let s=this.openHandle(true);try{let n=e?and(eq(u.id,t),eq(u.workspace_id,e)):eq(u.id,t),r=s.db.select({pinned:u.pinned,metadata:u.metadata}).from(u).where(n).get();if(!r)return null;let o=r.pinned?0:1,a=r.metadata?JSON.parse(r.metadata):{};if(o){let l=e?and(eq(u.pinned,1),eq(u.workspace_id,e)):eq(u.pinned,1),c=s.db.select({metadata:u.metadata}).from(u).where(l).all(),_=0;for(let f of c){let g=f.metadata?JSON.parse(f.metadata):{};typeof g.pinOrder=="number"&&g.pinOrder>_&&(_=g.pinOrder);}a.pinOrder=_+1;}else delete a.pinOrder;return s.db.update(u).set({pinned:o,metadata:Object.keys(a).length>0?JSON.stringify(a):null}).where(n).run(),{pinned:!!o}}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to toggle pin",n)}finally{s.close();}}reorderPins(t,e){let s=this.openHandle(true);try{for(let n=0;n<t.length;n++){let r=e?and(eq(u.id,t[n]),eq(u.workspace_id,e)):eq(u.id,t[n]),o=s.db.select({metadata:u.metadata}).from(u).where(r).get();if(!o)continue;let a=o.metadata?JSON.parse(o.metadata):{};a.pinOrder=n+1,s.db.update(u).set({metadata:JSON.stringify(a)}).where(r).run();}}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to reorder pins",n)}finally{s.close();}}toggleStar(t,e){let s=this.openHandle(true);try{let n=e?and(eq(u.id,t),eq(u.workspace_id,e)):eq(u.id,t),r=s.db.select({starred:u.starred}).from(u).where(n).get();if(!r)return null;let o=r.starred?0:1;return s.db.update(u).set({starred:o}).where(n).run(),{starred:!!o}}catch(n){throw n instanceof p?n:new p("DB_ERROR","Failed to toggle star",n)}finally{s.close();}}resolveOverdriveForRequest(t,e,s,n){let o=this.openHandle(true);try{let a=e?and(eq(u.id,t),eq(u.workspace_id,e)):eq(u.id,t);return o.db.transaction(c=>{let _=c.select({metadata:u.metadata}).from(u).where(a).get();if(!_)return null;let f=_.metadata?JSON.parse(_.metadata):{},g=f.overdrive??{},b=n?.defaultTurns??g.defaultTurns??3,G=n?.updatedBy??"ui",M=new Date().toISOString(),O,N,L,V;switch(s){case "enable-count":{let Q=n?.turns??b,Z=n?.consumeCurrent?Math.max(Q-1,0):Q;O=Z>0?"count":"off",N=Z,L=!0,V="count";break}case "enable-latch":{O="latch",N=0,L=!0,V="latch";break}case "disable":{O="off",N=0,L=!1;break}default:{let Q=g.state??"off",Z=typeof g.remaining=="number"?g.remaining:0;if(Q==="count"&&Z>0){let Et=Z-1;Et<=0?(O="off",N=0):(O="count",N=Et),L=!0,V="count";}else Q==="latch"?(O="latch",N=0,L=!0,V="latch"):(O="off",N=0,L=!1);break}}return f.overdrive={state:O,remaining:N,defaultTurns:b,updatedAt:M,updatedBy:G},c.update(u).set({metadata:JSON.stringify(f),updated_at:M}).where(a).run(),{applied:L,appliedMode:V,state:O,remaining:N}},{behavior:"immediate"})}catch(a){throw a instanceof p?a:new p("DB_ERROR","Failed to resolve overdrive",a)}finally{o.close();}}};function ve(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
268
268
|
`).filter(n=>!(n.startsWith("Loaded ")&&n.includes("layouts from")||n.includes("[dotenv@")||n.includes("[Nest]")&&n.includes("DEBUG")||n.startsWith("Registered custom layout:")||n.startsWith("Updated custom layout:"))).join(`
|
|
269
|
-
`).trim()}function
|
|
270
|
-
`):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=
|
|
271
|
-
`)[0].slice(0,200)),e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:
|
|
269
|
+
`).trim()}function Le(d){if(!d)return "";let t=d;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
|
|
270
|
+
`):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=ve(t);}return t}var ct=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new lt({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let n=this.getThreadRepo(),r=n.findThreadById(t);if(r){if(r.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${r.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return n.ensureThread(t,e,s),{created:true}}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),o=n.findTopLevelTasks(t,void 0,s),a=new Set(["queued","cancelled"]);o=o.filter(_=>(!_.status||!a.has(_.status))&&(!e?.currentTraceId||_.trace_id!==e.currentTraceId));let l=r?.platform??"cli",c=this.rowsToMessages(o);return {threadId:t,platform:l,messages:c,metadata:{title:r?.title??void 0,firstMessage:r?.first_message??void 0,lastMessage:r?.last_message??void 0,messageCount:r?.message_count??0,updatedAt:r?.updated_at?new Date(r.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,n){let{firstMessage:r}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:r}}async saveAssistantMessage(t,e,s,n){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}close(){}normalizeStatus(t){if(t&&!["success","completed","done"].includes(t)){if(["failed","error"].includes(t))return "failed";if(t==="running")return "running"}}rowsToMessages(t){let e=[];for(let s of t){s.prompt&&e.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime(),metadata:{caller_agent_id:s.caller_agent_id}});let n=Le(s.result),r=this.normalizeStatus(s.status);if(n||r==="running"||r==="failed"){let o={agent_id:s.agent_id,task_id:s.id};r&&(o.status=r),r==="failed"&&s.error&&(o.reason=s.error.split(`
|
|
271
|
+
`)[0].slice(0,200)),e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:o});}}return e}};var wt=class extends U{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new ct(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,s,n){}async afterAssistantMessage(t,e,s){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{let n=await this._provider.ensureThread(e.threadId,s,e.workspaceId),r=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,r.id,n.created||r.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let n=e.agentRef?.replace(/^@/,"")??"";try{let{id:r}=await this._provider.saveAssistantMessage(s,e.result,n);await this.afterAssistantMessage(s,r,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{wt as ConversationPlugin,ut as FileLoggerPlugin,kt as SqliteTracingPlugin};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import*as F from'path';import F__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import Yt,{existsSync,mkdirSync,readFileSync}from'fs';import he from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt as lt$1,lte}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,getTableConfig}from'drizzle-orm/sqlite-core';var lt=(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 ce=()=>fileURLToPath(import.meta.url),ue=()=>F__default.dirname(ce()),b=ue();var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(he.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(t,e,n){super(e),this.name="RepositoryError",this.code=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};function k(a){let t=lt("better-sqlite3"),{drizzle:e}=lt("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(r,s=[])=>n.prepare(r).run(...s),close:()=>n.close()}}var Bt=new Set,fe={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 kt(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function me(a,t){if(t>0||!kt(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,s]of Object.entries(fe))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${s}`);}var ge={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function we(a,t,e){if(!kt(a,"__drizzle_migrations")||!kt(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(readFileSync(F__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=ge[o.tag];if(!l)continue;let u=F__default.join(t,`${o.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),_=createHash("sha256").update(c).digest("hex");if(r.has(_))continue;let m=a.all("PRAGMA table_info(tasks)"),g=new Set(m.map(R=>R.name));for(let[R,q]of Object.entries(l))g.has(R)||(a.run(`ALTER TABLE tasks ADD COLUMN ${R} ${q}`),g.add(R));}}function ke(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(o=>o.hash)),s=JSON.parse(readFileSync(F__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of s.entries){let l=F__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let _=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],g;for(;(g=_.exec(u))!==null;)m.push({table:g[1],column:g[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(H=>H.trim()).filter(Boolean).every(H=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(H)))continue;m.every(({table:H,column:C})=>a.all(`PRAGMA table_info("${H}")`).some(I=>I.name===C))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function et(a){let{migrate:t}=lt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=lt("drizzle-orm"),n=[F__default.join(b,"../migrations"),F__default.join(b,"migrations"),F__default.join(b,"../../../../drizzle/migrations"),F__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(F__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${n.join(`
|
|
3
|
-
`)}`);let s=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;s?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),me(a,o),s?.cnt&&(ke(a,r,e),we(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function O(a,t){Bt.has(t)||(et(a),Bt.add(t));}var h=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var i=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>h.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id)}));var W=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>W.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var z=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var B=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var nt=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var D=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));function Rt(a){let t=F.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 Wt(a){let t=Rt(a);return createHash("sha256").update(t).digest("hex")}function ht(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Tt=class extends x{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{et(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=ht(basename(n)),o=`${ht(basename(dirname(n)))}-${r}`,l=[r,o];try{let u=c=>t.select({id:h.id}).from(h).where(and(eq(h.slug,c),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 _=`${o}-${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 s=ht(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:s,updated_at:new Date().toISOString()}).where(eq(h.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:o}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:s,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:o,updated_at:l}).where(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(t){let e=Rt(t),n=this.openHandle(true);try{let r=Wt(e),s=basename(e),o=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:o,name:s,workspacePath:e}),{id:r,slug:o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
|
|
3
|
+
`)}`);let s=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;s?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),me(a,o),s?.cnt&&(ke(a,r,e),we(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function A(a,t){Bt.has(t)||(et(a),Bt.add(t));}var h=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var i=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>h.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id)}));var W=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>W.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var z=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var B=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var nt=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var D=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));function Rt(a){let t=F.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 Wt(a){let t=Rt(a);return createHash("sha256").update(t).digest("hex")}function ht(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Tt=class extends x{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{et(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=ht(basename(n)),o=`${ht(basename(dirname(n)))}-${r}`,l=[r,o];try{let u=c=>t.select({id:h.id}).from(h).where(and(eq(h.slug,c),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 _=`${o}-${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 s=ht(r.slug.replace(/\//g,"-"));t.db.update(h).set({slug:s,updated_at:new Date().toISOString()}).where(eq(h.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:s,workspacePath:o}=e,l=new Date().toISOString();t.insert(h).values({id:n,slug:r,name:s,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(h).set({workspace_path:o,updated_at:l}).where(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(t){let e=Rt(t),n=this.openHandle(true);try{let r=Wt(e),s=basename(e),o=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:o,name:s,workspacePath:e}),{id:r,slug:o}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(h.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:e.db.select().from(h).where(n).orderBy(desc(h.updated_at)).limit(t.limit).offset(t.offset).all(),total:r?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(eq(h.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
|
|
4
4
|
(SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
|
|
5
5
|
FROM threads t
|
|
6
6
|
WHERE t.workspace_id = ${t}
|
|
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(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?and(eq(h.slug,t),ne(h.id,e)):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 s=this.openHandle(true);try{let o=new Date().toISOString();s.db.insert(h).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:o,updated_at:o}).run();let l=s.db.select().from(h).where(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{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}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(and(eq(h.is_active,1),isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(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(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(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 Jt=[h,i,p,W,z,B,nt];function Fe(){return F__default.join(he.homedir(),".crewx","crewx.db")}function je(a){if(!Yt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Yt.copyFileSync(a,e),e}function Vt(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 We(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 Ke(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=We(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Ge(a,t){let e=t?.dbPath??Fe(),n=t?.force??false,r=t?.dryRun??false,s=r?null:je(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Vt(a);if(!r)try{et(a);}catch(m){let g=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw m}let l,u;r?(l=Jt.map(g=>getTableConfig(g).name).filter(g=>!o.has(g)),u=o):(u=Vt(a),l=[...u].filter(m=>!o.has(m)));let c=[],_=[];for(let m of Jt){let g=getTableConfig(m),R=g.name;if(!u.has(R))continue;let q=a.all(`PRAGMA table_info("${R}")`),H=new Set(q.map(S=>S.name)),C=new Set(g.columns.map(S=>S.name));for(let S of g.columns)if(!H.has(S.name)){if(!r){let I=Ke(S);a.run(`ALTER TABLE "${R}" ADD COLUMN ${I}`);}c.push({table:R,column:S.name});}for(let S of q)C.has(S.name)||_.push(`${R}.${S.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:_,backupPath:s}}var Q="2026-05-09",Ze="0.8.9-rc.13",Z=10,tt=parseInt(Ze.split("rc.")[1]),Ot=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{
|
|
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(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?and(eq(h.slug,t),ne(h.id,e)):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 s=this.openHandle(true);try{let o=new Date().toISOString();s.db.insert(h).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:o,updated_at:o}).run();let l=s.db.select().from(h).where(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{s.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let s=r.db.select().from(h).where(eq(h.id,t)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${t} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}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(and(eq(h.is_active,1),isNotNull(h.workspace_path))).all(),n=0;for(let r of e){let s=r.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(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(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(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 Jt=[h,i,p,W,z,B,nt];function Fe(){return F__default.join(he.homedir(),".crewx","crewx.db")}function je(a){if(!Yt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Yt.copyFileSync(a,e),e}function Vt(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 We(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 Ke(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=We(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Ge(a,t){let e=t?.dbPath??Fe(),n=t?.force??false,r=t?.dryRun??false,s=r?null:je(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Vt(a);if(!r)try{et(a);}catch(m){let g=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw m}let l,u;r?(l=Jt.map(g=>getTableConfig(g).name).filter(g=>!o.has(g)),u=o):(u=Vt(a),l=[...u].filter(m=>!o.has(m)));let c=[],_=[];for(let m of Jt){let g=getTableConfig(m),R=g.name;if(!u.has(R))continue;let q=a.all(`PRAGMA table_info("${R}")`),H=new Set(q.map(S=>S.name)),C=new Set(g.columns.map(S=>S.name));for(let S of g.columns)if(!H.has(S.name)){if(!r){let I=Ke(S);a.run(`ALTER TABLE "${R}" ADD COLUMN ${I}`);}c.push({table:R,column:S.name});}for(let S of q)C.has(S.name)||_.push(`${R}.${S.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:_,backupPath:s}}var Q="2026-05-09",Ze="0.8.9-rc.13",Z=10,tt=parseInt(Ze.split("rc.")[1]),tn=new Set(["workflow","mcp"]),en=600*1e3,Ot=class extends x{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}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}).onConflictDoUpdate({target:i.id,set:{pid:sql`COALESCE(excluded.pid, ${i.pid})`},setWhere:eq(i.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 s=r.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=s?.logs?JSON.parse(s.logs):[];o.push(e),r.update(i).set({logs:JSON.stringify(o)}).where(eq(i.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(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
|
|
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 s=r.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=s?.logs?JSON.parse(s.logs):[];o.push(e),r.update(i).set({logs:JSON.stringify(o)}).where(eq(i.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(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,platform:i.platform,run_epoch:i.run_epoch}).from(i).where(eq(i.status,"running")).all(),n=Date.now(),r=new Set,s=0;for(let o of e){if(o.pid){let c=!1;try{process.kill(o.pid,0),c=!0;}catch{}c||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,o.id),eq(i.status,"running"))).run(),s++);continue}if(tn.has(o.platform??"cli"))continue;let l=`${o.id}:${o.run_epoch??0}`;r.add(l);let u=this.pidNullObservedSince.get(l);if(u===void 0){this.pidNullObservedSince.set(l,n);continue}n-u>=en&&(t.db.update(i).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(i.id,o.id),eq(i.status,"running"))).run(),s++,this.pidNullObservedSince.delete(l));}for(let o of Array.from(this.pidNullObservedSince.keys()))r.has(o)||this.pidNullObservedSince.delete(o);return s}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let s=k(r);try{let o=e?eq(i.workspace_id,e):void 0,l=o?and(eq(i.id,t),o):eq(i.id,t),u=s.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),_=o?and(c,o):c;u=s.db.select().from(i).where(_).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{s.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=e?and(eq(i.parent_task_id,t),eq(i.workspace_id,e)):eq(i.parent_task_id,t),c=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let _ of c)r.has(_.id)||(r.add(_.id),s.push(_));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return s}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
12
12
|
SELECT
|
|
13
13
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
14
14
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -203,7 +203,7 @@ ${n.join(`
|
|
|
203
203
|
${l}
|
|
204
204
|
GROUP BY provider
|
|
205
205
|
ORDER BY (COALESCE(SUM(${o}), 0) + COALESCE(SUM(${i.output_tokens}), 0)) DESC
|
|
206
|
-
`).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}};var At=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{
|
|
206
|
+
`).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{r.close();}}};var At=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:h.id}).from(h).where(eq(h.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`(
|
|
207
207
|
${t}.parent_task_id IS NULL
|
|
208
208
|
OR ${t}.parent_task_id = ''
|
|
209
209
|
OR NOT EXISTS (
|
|
@@ -259,4 +259,4 @@ ${n.join(`
|
|
|
259
259
|
message_count = message_count + 1,
|
|
260
260
|
updated_at = ${s}
|
|
261
261
|
WHERE id = ${t}
|
|
262
|
-
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:s}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!s)return null;let o=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(o){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),_=0;for(let m of c){let g=m.metadata?JSON.parse(m.metadata):{};typeof g.pinOrder=="number"&&g.pinOrder>_&&(_=g.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!o}}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 s=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),o=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({starred:p.starred}).from(p).where(r).get();if(!s)return null;let o=s.starred?0:1;return n.db.update(p).set({starred:o}).where(r).run(),{starred:!!o}}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 o=this.openHandle(true);try{let l=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return o.db.transaction(c=>{let _=c.select({metadata:p.metadata}).from(p).where(l).get();if(!_)return null;let m=_.metadata?JSON.parse(_.metadata):{},g=m.overdrive??{},R=r?.defaultTurns??g.defaultTurns??3,q=r?.updatedBy??"ui",H=new Date().toISOString(),C,S,I,st;switch(n){case "enable-count":{let ot=r?.turns??R,it=r?.consumeCurrent?Math.max(ot-1,0):ot;C=it>0?"count":"off",S=it,I=!0,st="count";break}case "enable-latch":{C="latch",S=0,I=!0,st="latch";break}case "disable":{C="off",S=0,I=!1;break}default:{let ot=g.state??"off",it=typeof g.remaining=="number"?g.remaining:0;if(ot==="count"&&it>0){let $t=it-1;$t<=0?(C="off",S=0):(C="count",S=$t),I=!0,st="count";}else ot==="latch"?(C="latch",S=0,I=!0,st="latch"):(C="off",S=0,I=!1);break}}return m.overdrive={state:C,remaining:S,defaultTurns:R,updatedAt:H,updatedBy:q},c.update(p).set({metadata:JSON.stringify(m),updated_at:H}).where(l).run(),{applied:I,appliedMode:st,state:C,remaining:S}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{o.close();}}};var Nt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(W).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(W).where(eq(W.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(W).where(eq(W.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 Ct=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(z).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(z).where(eq(z.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:z.tool_name,count:sql`count(*)`}).from(z).where(eq(z.task_id,t)).groupBy(z.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 vt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(B).where(eq(B.thread_id,t)).orderBy(asc(B.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(B).where(and(eq(B.id,e),eq(B.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(B).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(B).where(eq(B.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Lt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(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 s of t)r.insert(nt).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.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(nt).orderBy(desc(nt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function ae(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Pt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=ae(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(D).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:[D.provider,D.account_ref,D.limit_window,D.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:D.provider,bucket_start:D.bucket_start,used_percent:D.used_percent,remaining_percent:D.remaining_percent,resets_at:D.resets_at}).from(D).where(and(eq(D.limit_window,t.window),gte(D.bucket_start,t.fromIso),lte(D.bucket_start,t.toIso))).orderBy(asc(D.bucket_start)).all(),r=new Map;for(let s of n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,o])=>({provider:s,points:o}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};export{x as BaseSqliteRepository,d as RepositoryError,Lt as RequestLogRepository,Nt as SpanRepository,Ot as TaskRepository,vt as ThreadBoxRepository,At as ThreadRepository,Ct as ToolCallRepository,Pt as UsageLimitSnapshotRepository,Tt as WorkspaceRepository,ae as calcBucketStart,k as openDrizzleDb,Ge as pushSchema,et as runMigrations,O as runMigrationsOnce,i as tasks};
|
|
262
|
+
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s=new Date().toISOString();r.db.update(p).set({last_message:e,updated_at:s}).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(p).set(r).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread",r)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(r).get();if(!s)return null;let o=s.pinned?0:1,l=s.metadata?JSON.parse(s.metadata):{};if(o){let u=e?and(eq(p.pinned,1),eq(p.workspace_id,e)):eq(p.pinned,1),c=n.db.select({metadata:p.metadata}).from(p).where(u).all(),_=0;for(let m of c){let g=m.metadata?JSON.parse(m.metadata):{};typeof g.pinOrder=="number"&&g.pinOrder>_&&(_=g.pinOrder);}l.pinOrder=_+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!o}}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 s=e?and(eq(p.id,t[r]),eq(p.workspace_id,e)):eq(p.id,t[r]),o=n.db.select({metadata:p.metadata}).from(p).where(s).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=r+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(s).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),s=n.db.select({starred:p.starred}).from(p).where(r).get();if(!s)return null;let o=s.starred?0:1;return n.db.update(p).set({starred:o}).where(r).run(),{starred:!!o}}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 o=this.openHandle(true);try{let l=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t);return o.db.transaction(c=>{let _=c.select({metadata:p.metadata}).from(p).where(l).get();if(!_)return null;let m=_.metadata?JSON.parse(_.metadata):{},g=m.overdrive??{},R=r?.defaultTurns??g.defaultTurns??3,q=r?.updatedBy??"ui",H=new Date().toISOString(),C,S,I,st;switch(n){case "enable-count":{let ot=r?.turns??R,it=r?.consumeCurrent?Math.max(ot-1,0):ot;C=it>0?"count":"off",S=it,I=!0,st="count";break}case "enable-latch":{C="latch",S=0,I=!0,st="latch";break}case "disable":{C="off",S=0,I=!1;break}default:{let ot=g.state??"off",it=typeof g.remaining=="number"?g.remaining:0;if(ot==="count"&&it>0){let $t=it-1;$t<=0?(C="off",S=0):(C="count",S=$t),I=!0,st="count";}else ot==="latch"?(C="latch",S=0,I=!0,st="latch"):(C="off",S=0,I=!1);break}}return m.overdrive={state:C,remaining:S,defaultTurns:R,updatedAt:H,updatedBy:q},c.update(p).set({metadata:JSON.stringify(m),updated_at:H}).where(l).run(),{applied:I,appliedMode:st,state:C,remaining:S}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{o.close();}}};var Nt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(W).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(W).where(eq(W.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(W).where(eq(W.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 Ct=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(z).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(z).where(eq(z.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:z.tool_name,count:sql`count(*)`}).from(z).where(eq(z.task_id,t)).groupBy(z.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 vt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(B).where(eq(B.thread_id,t)).orderBy(asc(B.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{e.close();}}findById(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(B).where(and(eq(B.id,e),eq(B.thread_id,t))).limit(1).get()??void 0}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to find box by id",r)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(B).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(r){throw r instanceof Error&&/UNIQUE constraint failed/i.test(r.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,r):r}let n=e.db.select().from(B).where(eq(B.id,t.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{e.close();}}};var Lt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let s of t)r.insert(nt).values({id:randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.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(nt).orderBy(desc(nt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function ae(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Pt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{A(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=ae(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(D).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:[D.provider,D.account_ref,D.limit_window,D.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:D.provider,bucket_start:D.bucket_start,used_percent:D.used_percent,remaining_percent:D.remaining_percent,resets_at:D.resets_at}).from(D).where(and(eq(D.limit_window,t.window),gte(D.bucket_start,t.fromIso),lte(D.bucket_start,t.toIso))).orderBy(asc(D.bucket_start)).all(),r=new Map;for(let s of n)r.has(s.provider)||r.set(s.provider,[]),r.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(r.entries()).map(([s,o])=>({provider:s,points:o}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};export{x as BaseSqliteRepository,d as RepositoryError,Lt as RequestLogRepository,Nt as SpanRepository,Ot as TaskRepository,vt as ThreadBoxRepository,At as ThreadRepository,Ct as ToolCallRepository,Pt as UsageLimitSnapshotRepository,Tt as WorkspaceRepository,ae as calcBucketStart,k as openDrizzleDb,Ge as pushSchema,et as runMigrations,A as runMigrationsOnce,i as tasks};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function f(){let e=[];return {events:e,async log(t,r){e.push({event:t,payload:r});}}}function y(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,r){e.debug.push({msg:t,meta:r});},info(t,r){e.info.push({msg:t,meta:r});},warn(t,r){e.warn.push({msg:t,meta:r});},error(t,r){e.error.push({msg:t,meta:r});}}}function S(){let e=200,t,r,n={},o={status(i){return e=i,o},set(i,
|
|
1
|
+
function f(){let e=[];return {events:e,async log(t,r){e.push({event:t,payload:r});}}}function y(){let e={debug:[],info:[],warn:[],error:[]};return {entries:e,debug(t,r){e.debug.push({msg:t,meta:r});},info(t,r){e.info.push({msg:t,meta:r});},warn(t,r){e.warn.push({msg:t,meta:r});},error(t,r){e.error.push({msg:t,meta:r});}}}function S(){let e=200,t,r,n={},o={status(i){return e=i,o},set(i,a){return n[i]=a,o},send(i){return r=i,o},json(i){return t=i,o},end(){return o},getStatusCode:()=>e,getJsonBody:()=>t,getSentBody:()=>r,getHeaders:()=>({...n})};return o}function M(){let e=[];return {routes:e,registerRoute(r,n,o){e.push({path:r,handler:n,opts:o});},async simulate(r,n,o=Buffer.alloc(0),i={},a={},p={}){let g=e.find(m=>m.path===n);if(!g)return {status:404,body:{error:"Not found"},headers:{}};let l={method:r,url:n,headers:i,body:o,params:a,query:p},c=S();return await g.handler(l,c),{status:c.getStatusCode(),body:c.getJsonBody()??c.getSentBody(),headers:c.getHeaders()}}}}function P(e){let t=new Map,r=n=>n.startsWith(`${e}::`)?n:`${e}::${n}`;return {async get(n){let o=t.get(r(n));return o?o.value:void 0},async set(n,o){t.set(r(n),{value:o});},async delete(n){return t.delete(r(n))},async list(n){let o=n?r(n):`${e}::`,i=[];for(let a of t.keys())a.startsWith(o)&&i.push(a.slice(e.length+2));return i}}}function x(e){return P(e)}function R(){let e=new Map;return {blobs:e,async put(t,r,n){return e.set(t,{data:r,contentType:n}),t},async get(t){let r=e.get(t);return r?r.data:void 0},async delete(t){return e.delete(t)}}}function I(e){let t=e.instanceId??"mock-instance",r=f(),n=y(),o=M(),i=x(t),a=R(),p=[],g=[],l=[],c={run:async()=>({output:""}),...e.agentRunner},m=new AbortController,C=async u=>(p.push(u),{accepted:true}),k=async u=>(g.push(u),{accepted:true}),h=async(u,A)=>{l.push({messageId:u,patch:A});},E=async u=>({userId:u,displayName:u}),b=async()=>{},O=async()=>({messageId:"mock-proactive",sentAt:Date.now()});return {instanceId:t,installationId:e.installationId,config:e.config,capabilities:new Set(e.capabilities??[]),log:n,agentRunner:c,db:i,storage:a,audit:r,abortSignal:e.abortSignal??m.signal,httpRouter:o,router:o,inbound:C,emitEvent:k,updateMessage:h,resolveUser:E,respondSync:b,proactive:O,inboundCalls:p,emittedEvents:g,sentMessages:l}}function G(){}var v={claude:{models:[{id:"claude-fable-5",name:"Claude Fable 5"},{id:"claude-sonnet-5",name:"Claude Sonnet 5"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8 (Extended)"},{id:"claude-opus-4-8",name:"Claude Opus 4.8"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7 (Extended)"},{id:"claude-opus-4-7",name:"Claude Opus 4.7"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6 (Extended)"},{id:"claude-opus-4-6",name:"Claude Opus 4.6"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6 (Extended)"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5"}],modes:[{id:"default",name:"Default"},{id:"acceptEdits",name:"Accept Edits"},{id:"plan",name:"Plan"},{id:"auto",name:"Auto"},{id:"dontAsk",name:"Don't Ask"},{id:"bypassPermissions",name:"Bypass Permissions"}],effort:[],modelOverrides:{}},codex:{models:[{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark"}],modes:[{id:"agent",name:"Agent"},{id:"read-only",name:"Read Only"},{id:"plan",name:"Plan"},{id:"agent-full-access",name:"Agent Full Access"},{id:"yolo",name:"YOLO"}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-5.5":{effort:["minimal","low","medium","high","xhigh"],defaultEffort:"high"}}},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6"},{id:"gpt-5.5",name:"GPT-5.5"},{id:"gpt-5.4",name:"GPT-5.4"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro"}],modes:[{id:"interactive",name:"Interactive"},{id:"plan",name:"Plan"},{id:"autopilot",name:"Autopilot"}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{}},antigravity:{models:[{id:"Gemini 3.5 Flash (Medium)",name:"Gemini 3.5 Flash (Medium)"},{id:"Gemini 3.5 Flash (High)",name:"Gemini 3.5 Flash (High)"},{id:"Gemini 3.5 Flash (Low)",name:"Gemini 3.5 Flash (Low)"},{id:"Gemini 3.1 Pro (Low)",name:"Gemini 3.1 Pro (Low)"},{id:"Gemini 3.1 Pro (High)",name:"Gemini 3.1 Pro (High)"},{id:"Claude Sonnet 4.6 (Thinking)",name:"Claude Sonnet 4.6 (Thinking)"},{id:"Claude Opus 4.6 (Thinking)",name:"Claude Opus 4.6 (Thinking)"},{id:"GPT-OSS 120B (Medium)",name:"GPT-OSS 120B (Medium)"}],modes:[],effort:[],modelOverrides:{}}};Object.fromEntries(Object.entries(v).map(([e,t])=>[e,t.models]));function B(){}export{f as createMockAudit,I as createMockContext,y as createMockLogger,M as createMockRouter,R as createMockStorage,x as createMockStore,B as resetModelsOverride,G as resetPricingOverride};
|