@crewx/sdk 0.8.9 → 0.9.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,14 @@
1
- import*as H from'path';import H__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import zt,{existsSync,mkdirSync,readFileSync}from'fs';import se from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,getTableConfig}from'drizzle-orm/sqlite-core';var nt=(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 Zt=()=>fileURLToPath(import.meta.url),te=()=>H__default.dirname(Zt()),b=te();var T=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(se.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=nt("better-sqlite3"),{drizzle:e}=nt("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:(s,r=[])=>n.prepare(s).run(...r),close:()=>n.close()}}var At=new Set,re={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function ht(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function oe(a,t){if(t>0||!ht(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(s=>s.name));for(let[s,r]of Object.entries(re))n.has(s)||a.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}var ie={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ae(a,t,e){if(!ht(a,"__drizzle_migrations")||!ht(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=ie[o.tag];if(!l)continue;let u=H__default.join(t,`${o.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),h=createHash("sha256").update(c).digest("hex");if(s.has(h))continue;let m=a.all("PRAGMA table_info(tasks)"),w=new Set(m.map(y=>y.name));for(let[y,q]of Object.entries(l))w.has(y)||(a.run(`ALTER TABLE tasks ADD COLUMN ${y} ${q}`),w.add(y));}}function de(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=H__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(s.has(c))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],w;for(;(w=h.exec(u))!==null;)m.push({table:w[1],column:w[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(F=>F.trim()).filter(Boolean).every(F=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(F)))continue;m.every(({table:F,column:pt})=>a.all(`PRAGMA table_info("${F}")`).some(_t=>_t.name===pt))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function J(a){let{migrate:t}=nt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=nt("drizzle-orm"),n=[H__default.join(b,"../migrations"),H__default.join(b,"migrations"),H__default.join(b,"../../../../drizzle/migrations"),H__default.join(process.cwd(),"drizzle/migrations")],s=n.find(c=>existsSync(H__default.join(c,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
1
+ import*as H from'path';import H__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import zt,{existsSync,mkdirSync,readFileSync}from'fs';import se from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt}from'drizzle-orm';import {randomUUID,createHash}from'crypto';import {sqliteTable,text,integer,real,index,unique,getTableConfig}from'drizzle-orm/sqlite-core';var nt=(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 Zt=()=>fileURLToPath(import.meta.url),te=()=>H__default.dirname(Zt()),b=te();var T=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(se.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=nt("better-sqlite3"),{drizzle:e}=nt("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:(s,r=[])=>n.prepare(s).run(...r),close:()=>n.close()}}var At=new Set,re={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function ht(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function oe(a,t){if(t>0||!ht(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(s=>s.name));for(let[s,r]of Object.entries(re))n.has(s)||a.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}var ie={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function ae(a,t,e){if(!ht(a,"__drizzle_migrations")||!ht(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=ie[o.tag];if(!l)continue;let u=H__default.join(t,`${o.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),h=createHash("sha256").update(c).digest("hex");if(s.has(h))continue;let m=a.all("PRAGMA table_info(tasks)"),w=new Set(m.map(y=>y.name));for(let[y,q]of Object.entries(l))w.has(y)||(a.run(`ALTER TABLE tasks ADD COLUMN ${y} ${q}`),w.add(y));}}function de(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),s=new Set(n.map(o=>o.hash)),r=JSON.parse(readFileSync(H__default.join(t,"meta/_journal.json"),"utf-8"));for(let o of r.entries){let l=H__default.join(t,`${o.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(s.has(c))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,m=[],w;for(;(w=h.exec(u))!==null;)m.push({table:w[1],column:w[2]});if(m.length===0||!u.split(/-->\s*statement-breakpoint/).map(F=>F.trim()).filter(Boolean).every(F=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(F)))continue;m.every(({table:F,column:pt})=>a.all(`PRAGMA table_info("${F}")`).some(_t=>_t.name===pt))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${o.when})`);}}function V(a){let{migrate:t}=nt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=nt("drizzle-orm"),n=[H__default.join(b,"../migrations"),H__default.join(b,"migrations"),H__default.join(b,"../../../../drizzle/migrations"),H__default.join(process.cwd(),"drizzle/migrations")],s=n.find(c=>existsSync(H__default.join(c,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
3
- `)}`);let r=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;r?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),oe(a,o),r?.cnt&&(de(a,s,e),ae(a,s,e)),t(a,{migrationsFolder:s});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function O(a,t){At.has(t)||(J(a),At.add(t));}var _=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)},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(()=>_.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 U=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(()=>U.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 $=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 L=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 Q=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)}));function wt(a){let t=H.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 Bt(a){let t=wt(a);return createHash("sha256").update(t).digest("hex")}function at(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Et=class extends T{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{J(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=at(basename(n)),o=`${at(basename(dirname(n)))}-${s}`,l=[s,o];try{let u=c=>t.select({id:_.id}).from(_).where(and(eq(_.slug,c),ne(_.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 h=`${o}-${c}`;if(!u(h))return h}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,slug:_.slug}).from(_).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=at(s.slug.replace(/\//g,"-"));t.db.update(_).set({slug:r,updated_at:new Date().toISOString()}).where(eq(_.id,s.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:s,name:r,workspacePath:o}=e,l=new Date().toISOString();t.insert(_).values({id:n,slug:s,name:r,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(_).set({workspace_path:o,updated_at:l}).where(and(eq(_.id,n),isNull(_.workspace_path))).run();}registerWorkspace(t){let e=wt(t),n=this.openHandle(true);try{let s=Bt(e),r=basename(e),o=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:o,name:r,workspacePath:e}),{id:s,slug:o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to register workspace",s)}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(_.is_active,t.isActive?1:0):void 0,s=e.db.select({count:sql`count(*)`}).from(_).where(n).get();return {rows:e.db.select().from(_).where(n).orderBy(desc(_.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.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(_).where(eq(_.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(s=>s.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 s=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
3
+ `)}`);let r=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),o=0;r?.cnt&&(o=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),oe(a,o),r?.cnt&&(de(a,s,e),ae(a,s,e)),t(a,{migrationsFolder:s});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-o;if(u>0){let c=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function O(a,t){At.has(t)||(V(a),At.add(t));}var _=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(()=>_.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 U=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(()=>U.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 $=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 L=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 Q=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)}));function wt(a){let t=H.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 Bt(a){let t=wt(a);return createHash("sha256").update(t).digest("hex")}function at(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Et=class extends T{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 s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{V(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=at(basename(n)),o=`${at(basename(dirname(n)))}-${s}`,l=[s,o];try{let u=c=>t.select({id:_.id}).from(_).where(and(eq(_.slug,c),ne(_.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 h=`${o}-${c}`;if(!u(h))return h}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,slug:_.slug}).from(_).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=at(s.slug.replace(/\//g,"-"));t.db.update(_).set({slug:r,updated_at:new Date().toISOString()}).where(eq(_.id,s.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:s,name:r,workspacePath:o}=e,l=new Date().toISOString();t.insert(_).values({id:n,slug:s,name:r,workspace_path:o,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(_).set({workspace_path:o,updated_at:l}).where(and(eq(_.id,n),isNull(_.workspace_path))).run();}registerWorkspace(t){let e=wt(t),n=this.openHandle(true);try{let s=Bt(e),r=basename(e),o=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:o,name:r,workspacePath:e}),{id:s,slug:o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to register workspace",s)}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(_.is_active,t.isActive?1:0):void 0,s=e.db.select({count:sql`count(*)`}).from(_).where(n).get();return {rows:e.db.select().from(_).where(n).orderBy(desc(_.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.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(_).where(eq(_.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(s=>s.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 s=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:s?.count??0}}catch(s){throw new d("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?and(eq(_.slug,t),ne(_.id,e)):eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(_).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(and(eq(_.is_active,1),isNotNull(_.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(_.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Mt=[_,i,p,U,$,L,Q];function Ne(){return H__default.join(se.homedir(),".crewx","crewx.db")}function Ce(a){if(!zt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return zt.copyFileSync(a,e),e}function qt(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 Le(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 ve(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Le(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Pe(a,t){let e=t?.dbPath??Ne(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Ce(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=qt(a);if(!s)try{J(a);}catch(m){let w=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!w.includes("duplicate column"))throw m}let l,u;s?(l=Mt.map(w=>getTableConfig(w).name).filter(w=>!o.has(w)),u=o):(u=qt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Mt){let w=getTableConfig(m),y=w.name;if(!u.has(y))continue;let q=a.all(`PRAGMA table_info("${y}")`),F=new Set(q.map(P=>P.name)),pt=new Set(w.columns.map(P=>P.name));for(let P of w.columns)if(!F.has(P.name)){if(!s){let _t=ve(P);a.run(`ALTER TABLE "${y}" ADD COLUMN ${_t}`);}c.push({table:y,column:P.name});}for(let P of q)pt.has(P.name)||h.push(`${y}.${P.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:r}}var G="2026-05-09",Ue="0.8.9-rc.13",Y=10,X=parseInt(Ue.split("rc.")[1]),yt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
8
+ LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new d("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(_).where(eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?and(eq(_.slug,t),ne(_.id,e)):eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(_).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(and(eq(_.is_active,1),isNotNull(_.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(_.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Mt=[_,i,p,U,$,L,Q];function Ne(){return H__default.join(se.homedir(),".crewx","crewx.db")}function Ce(a){if(!zt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return zt.copyFileSync(a,e),e}function qt(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 Le(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 ve(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Le(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Pe(a,t){let e=t?.dbPath??Ne(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Ce(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=qt(a);if(!s)try{V(a);}catch(m){let w=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!w.includes("duplicate column"))throw m}let l,u;s?(l=Mt.map(w=>getTableConfig(w).name).filter(w=>!o.has(w)),u=o):(u=qt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Mt){let w=getTableConfig(m),y=w.name;if(!u.has(y))continue;let q=a.all(`PRAGMA table_info("${y}")`),F=new Set(q.map(P=>P.name)),pt=new Set(w.columns.map(P=>P.name));for(let P of w.columns)if(!F.has(P.name)){if(!s){let _t=ve(P);a.run(`ALTER TABLE "${y}" ADD COLUMN ${_t}`);}c.push({table:y,column:P.name});}for(let P of q)pt.has(P.name)||h.push(`${y}.${P.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:r}}var Y="2026-05-09",Ue="0.8.9-rc.13",X=10,J=parseInt(Ue.split("rc.")[1]),yt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{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
- model=COALESCE(?, model) WHERE id=? AND status='running'`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,t),eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(eq(i.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,s.id),eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=k(s);try{let o=e?eq(i.workspace_id,e):void 0,l=o?and(eq(i.id,t),o):eq(i.id,t),u=r.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),h=o?and(c,o):c;u=r.db.select().from(i).where(h).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=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 h of c)s.has(h.id)||(s.add(h.id),r.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
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(s=>{let r=s.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,t),eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(eq(i.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,s.id),eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=k(s);try{let o=e?eq(i.workspace_id,e):void 0,l=o?and(eq(i.id,t),o):eq(i.id,t),u=r.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),h=o?and(c,o):c;u=r.db.select().from(i).where(h).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=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 h of c)s.has(h.id)||(s.add(h.id),r.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
11
12
  SELECT
12
13
  COALESCE(workspace_id, 'unknown') AS workspace_id,
13
14
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -36,11 +37,11 @@ ${n.join(`
36
37
  COALESCE(SUM(
37
38
  COALESCE(t.input_tokens, 0)
38
39
  + CASE
39
- WHEN t.started_at >= ${G}
40
+ WHEN t.started_at >= ${Y}
40
41
  AND (
41
42
  t.crewx_version IS NULL
42
43
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
43
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
44
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
44
45
  )
45
46
  THEN COALESCE(t.cached_input_tokens, 0)
46
47
  ELSE 0
@@ -59,11 +60,11 @@ ${n.join(`
59
60
  COALESCE(SUM(
60
61
  COALESCE(t.input_tokens, 0)
61
62
  + CASE
62
- WHEN t.started_at >= ${G}
63
+ WHEN t.started_at >= ${Y}
63
64
  AND (
64
65
  t.crewx_version IS NULL
65
66
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
66
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
67
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
67
68
  )
68
69
  THEN COALESCE(t.cached_input_tokens, 0)
69
70
  ELSE 0
@@ -79,11 +80,11 @@ ${n.join(`
79
80
  COALESCE(SUM(
80
81
  COALESCE(t.input_tokens, 0)
81
82
  + CASE
82
- WHEN t.started_at >= ${G}
83
+ WHEN t.started_at >= ${Y}
83
84
  AND (
84
85
  t.crewx_version IS NULL
85
86
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
86
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
87
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
87
88
  )
88
89
  THEN COALESCE(t.cached_input_tokens, 0)
89
90
  ELSE 0
@@ -101,11 +102,11 @@ ${n.join(`
101
102
  COALESCE(SUM(
102
103
  COALESCE(t.input_tokens, 0)
103
104
  + CASE
104
- WHEN t.started_at >= ${G}
105
+ WHEN t.started_at >= ${Y}
105
106
  AND (
106
107
  t.crewx_version IS NULL
107
108
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
108
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
109
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
109
110
  )
110
111
  THEN COALESCE(t.cached_input_tokens, 0)
111
112
  ELSE 0
@@ -120,11 +121,11 @@ ${n.join(`
120
121
  COALESCE(SUM(
121
122
  COALESCE(t.input_tokens, 0)
122
123
  + CASE
123
- WHEN t.started_at >= ${G}
124
+ WHEN t.started_at >= ${Y}
124
125
  AND (
125
126
  t.crewx_version IS NULL
126
127
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
127
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
128
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
128
129
  )
129
130
  THEN COALESCE(t.cached_input_tokens, 0)
130
131
  ELSE 0
@@ -147,11 +148,11 @@ ${n.join(`
147
148
  COALESCE(SUM(
148
149
  COALESCE(t.input_tokens, 0)
149
150
  + CASE
150
- WHEN t.started_at >= ${G}
151
+ WHEN t.started_at >= ${Y}
151
152
  AND (
152
153
  t.crewx_version IS NULL
153
154
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
154
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Y}) AS INTEGER) < ${X})
155
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${X}) AS INTEGER) < ${J})
155
156
  )
156
157
  THEN COALESCE(t.cached_input_tokens, 0)
157
158
  ELSE 0
@@ -179,11 +180,11 @@ ${n.join(`
179
180
  `,o=sql`
180
181
  COALESCE(${i.input_tokens}, 0)
181
182
  + CASE
182
- WHEN ${i.started_at} >= ${G}
183
+ WHEN ${i.started_at} >= ${Y}
183
184
  AND (
184
185
  ${i.crewx_version} IS NULL
185
186
  OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
186
- OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Y}) AS INTEGER) < ${X})
187
+ OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${X}) AS INTEGER) < ${J})
187
188
  )
188
189
  THEN COALESCE(${i.cached_input_tokens}, 0)
189
190
  ELSE 0
@@ -258,4 +259,4 @@ ${n.join(`
258
259
  message_count = message_count + 1,
259
260
  updated_at = ${r}
260
261
  WHERE id = ${t}
261
- `),c},{behavior:"immediate"})}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save user message",r)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.update(p).set({last_message:e,updated_at:r}).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save assistant message",r)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(p).set(s).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread",s)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let s=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),r=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(s).get();if(!r)return null;let o=r.pinned?0:1,l=r.metadata?JSON.parse(r.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(),h=0;for(let m of c){let w=m.metadata?JSON.parse(m.metadata):{};typeof w.pinOrder=="number"&&w.pinOrder>h&&(h=w.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(s).run(),{pinned:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle pin",s)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let s=0;s<t.length;s++){let r=e?and(eq(p.id,t[s]),eq(p.workspace_id,e)):eq(p.id,t[s]),o=n.db.select({metadata:p.metadata}).from(p).where(r).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=s+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(r).run();}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to reorder pins",s)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let s=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),r=n.db.select({starred:p.starred}).from(p).where(s).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(p).set({starred:o}).where(s).run(),{starred:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}};var Tt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(U).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(U).where(eq(U.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(U).where(eq(U.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 Dt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert($).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($).where(eq($.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:$.tool_name,count:sql`count(*)`}).from($).where(eq($.task_id,t)).groupBy($.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 xt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}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(L).where(eq(L.thread_id,t)).orderBy(asc(L.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(L).where(and(eq(L.id,e),eq(L.thread_id,t))).limit(1).get()??void 0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(L).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(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(L).where(eq(L.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 Ot=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let r of t)s.insert(Q).values({id:randomUUID(),path:r.path,method:r.method,status_code:r.statusCode,duration_ms:r.durationMs,ip:r.ip??null,request_headers:r.requestHeaders??null,response_headers:r.responseHeaders??null,request_body:r.requestBody??null,response_body:r.responseBody??null,query:r.query??null,user_id:r.userId??null,project_id:r.projectId??null,partition_key:r.partitionKey??"default",timestamp:n,metadata:r.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(Q).orderBy(desc(Q.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};export{T as BaseSqliteRepository,d as RepositoryError,Ot as RequestLogRepository,Tt as SpanRepository,yt as TaskRepository,xt as ThreadBoxRepository,St as ThreadRepository,Dt as ToolCallRepository,Et as WorkspaceRepository,k as openDrizzleDb,Pe as pushSchema,J as runMigrations,O as runMigrationsOnce};
262
+ `),c},{behavior:"immediate"})}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save user message",r)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.update(p).set({last_message:e,updated_at:r}).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save assistant message",r)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(p).set(s).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread",s)}finally{n.close();}}togglePin(t,e){let n=this.openHandle(true);try{let s=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),r=n.db.select({pinned:p.pinned,metadata:p.metadata}).from(p).where(s).get();if(!r)return null;let o=r.pinned?0:1,l=r.metadata?JSON.parse(r.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(),h=0;for(let m of c){let w=m.metadata?JSON.parse(m.metadata):{};typeof w.pinOrder=="number"&&w.pinOrder>h&&(h=w.pinOrder);}l.pinOrder=h+1;}else delete l.pinOrder;return n.db.update(p).set({pinned:o,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(s).run(),{pinned:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle pin",s)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let s=0;s<t.length;s++){let r=e?and(eq(p.id,t[s]),eq(p.workspace_id,e)):eq(p.id,t[s]),o=n.db.select({metadata:p.metadata}).from(p).where(r).get();if(!o)continue;let l=o.metadata?JSON.parse(o.metadata):{};l.pinOrder=s+1,n.db.update(p).set({metadata:JSON.stringify(l)}).where(r).run();}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to reorder pins",s)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let s=e?and(eq(p.id,t),eq(p.workspace_id,e)):eq(p.id,t),r=n.db.select({starred:p.starred}).from(p).where(s).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(p).set({starred:o}).where(s).run(),{starred:!!o}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to toggle star",s)}finally{n.close();}}};var Tt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(U).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(U).where(eq(U.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(U).where(eq(U.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 Dt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert($).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($).where(eq($.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:$.tool_name,count:sql`count(*)`}).from($).where(eq($.task_id,t)).groupBy($.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 xt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}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(L).where(eq(L.thread_id,t)).orderBy(asc(L.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(L).where(and(eq(L.id,e),eq(L.thread_id,t))).limit(1).get()??void 0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(L).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(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(L).where(eq(L.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 Ot=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let r of t)s.insert(Q).values({id:randomUUID(),path:r.path,method:r.method,status_code:r.statusCode,duration_ms:r.durationMs,ip:r.ip??null,request_headers:r.requestHeaders??null,response_headers:r.responseHeaders??null,request_body:r.requestBody??null,response_body:r.responseBody??null,query:r.query??null,user_id:r.userId??null,project_id:r.projectId??null,partition_key:r.partitionKey??"default",timestamp:n,metadata:r.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(Q).orderBy(desc(Q.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};export{T as BaseSqliteRepository,d as RepositoryError,Ot as RequestLogRepository,Tt as SpanRepository,yt as TaskRepository,xt as ThreadBoxRepository,St as ThreadRepository,Dt as ToolCallRepository,Et as WorkspaceRepository,k as openDrizzleDb,Pe as pushSchema,V as runMigrations,O as runMigrationsOnce,i as tasks};
@@ -1,2 +1,2 @@
1
1
  import {load}from'js-yaml';import {z}from'zod';var m=class extends Error{constructor(e,r){let t=r.length>0?` Available: ${r.join(", ")}`:"";super(`Agent not found: "${e}".${t}`),this.name="AgentNotFoundError";}},D={claude:{id:"claude",provider:"cli/claude"},copilot:{id:"copilot",provider:"cli/copilot"},codex:{id:"codex",provider:"cli/codex"}};function w(s,e){let r=s.startsWith("@")?s.slice(1):s,t=e.find(o=>o.id===r);if(t)return t;let i=D[r];if(i)return i;throw new m(s,e.map(o=>o.id))}var u=class extends Error{constructor(r,t,i){super(r);this.providerStr=t;this.name="ProviderError",this.code=i?.code??"UNKNOWN",this.kind=i?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=i?.retryAfterMs;}providerStr;code;kind;retryAfterMs};var I=new Map;function P(s,e){I.set(s,e);}function x(s){let e=s.split("/");if(e.length!==2)throw new u(`Invalid provider format: "${s}". Expected namespace/id (e.g., api/webllm)`,s);let[r,t]=e,i=I.get(r);if(i)return i(t,s);throw new u(`Unsupported provider namespace: "${r}". Register a factory with registerProviderFactory('${r}', factory).`,s)}var j=new Function("u","return import(u)"),A=class s{_agents;_config;_tools=new Map;_apiProviders=new Map;constructor(e,r){this._agents=new Map(e.map(t=>[t.id,t])),this._config=r;}static async fromConfig(e,r){let t=new s(e.agents??[],e),i=e.agents??[],o=a=>Array.isArray(a.provider)?a.provider[0]:a.provider,p=i.filter(a=>o(a)==="api/webllm"),c=i.filter(a=>o(a)==="api/openrouter");if(p.length>0&&await t._initWebLLM(p,r?.onProgress),c.length>0){if(!r?.openrouterApiKey)throw new Error("openrouterApiKey is required when using api/openrouter provider");t._initOpenRouter(c,r.openrouterApiKey);}return t._apiProviders.size>0&&P("api",(a,g)=>{let d=t._apiProviders.get(a);if(!d)throw new u(`Unknown api provider: ${a}`,g);return d}),t}async _initWebLLM(e,r){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not available. Chrome 113+ or Edge 113+ required.");let t=await j("https://esm.run/@mlc-ai/web-llm"),i=e[0]?.inline?.model??"gemma-2-2b-it-q4f16_1-MLC",o=await t.CreateMLCEngine(i,{initProgressCallback:r?c=>r(c):void 0}),p=[];this._apiProviders.set("webllm",{async query(c,a){let g=[];a?.systemPrompt&&g.push({role:"system",content:a.systemPrompt}),g.push(...p),g.push({role:"user",content:c});let d="",l=await o.chat.completions.create({messages:g,stream:true,temperature:.7,max_tokens:4096});for await(let y of l){let v=y.choices?.[0]?.delta?.content??"";d+=v,a?.onOutput&&a.onOutput(d,"stdout");}return p.push({role:"user",content:c}),p.push({role:"assistant",content:d}),d},async execute(c,a){return this.query(c,a)}});}_initOpenRouter(e,r){let t=e[0]?.inline?.model??"google/gemma-2-2b-it",i=[];this._apiProviders.set("openrouter",{async query(o,p){let c=[];p?.systemPrompt&&c.push({role:"system",content:p.systemPrompt}),c.push(...i),c.push({role:"user",content:o});let a=await fetch("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({model:p?.model||t,messages:c,stream:true})});if(!a.ok){let v=await a.text();throw new Error(`OpenRouter API error (${a.status}): ${v}`)}let g=a.body.getReader(),d=new TextDecoder,l="",y="";for(;;){let{done:v,value:T}=await g.read();if(v)break;y+=d.decode(T,{stream:true});let O=y.split(`
2
- `);y=O.pop();for(let M of O){let h=M.trim();if(!h||!h.startsWith("data: "))continue;let k=h.slice(6);if(k!=="[DONE]")try{let b=JSON.parse(k).choices?.[0]?.delta?.content??"";l+=b,b&&p?.onOutput&&p.onOutput(l,"stdout");}catch{}}}return i.push({role:"user",content:o}),i.push({role:"assistant",content:l}),l},async execute(o,p){return this.query(o,p)}});}get agents(){return this._agents}get config(){return this._config}get tools(){return this._tools}registerTool(e,r){this._tools.set(e,{name:e,...r});}async query(e,r,t){let i=Date.now(),o;try{o=w(e,Array.from(this._agents.values()));}catch(d){if(d instanceof m)return {ok:false,data:"",error:{code:"AGENT_NOT_FOUND",message:d.message},meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:Date.now()-i}};throw d}let p=Array.isArray(o.provider)?o.provider[0]??"api/default":o.provider,c=t?.provider??p,a=t?.model??o.inline?.model,g;try{g=x(c);}catch(d){return {ok:false,data:"",error:{code:"PROVIDER_ERROR",message:d.message},meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}try{return {ok:!0,data:await g.query(r,{model:a,context:t?.context,systemPrompt:o.inline?.system_prompt??o.inline?.prompt,onOutput:t?.onOutput?l=>t.onOutput(l):void 0}),meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}catch(d){return {ok:false,data:"",error:{code:"QUERY_FAILED",message:d.message},meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}}async execute(e,r,t){let i=Date.now(),o;try{o=w(e,Array.from(this._agents.values()));}catch(d){if(d instanceof m)return {ok:false,data:"",error:{code:"AGENT_NOT_FOUND",message:d.message},meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:Date.now()-i}};throw d}let p=Array.isArray(o.provider)?o.provider[0]??"api/default":o.provider,c=t?.provider??p,a=t?.model??o.inline?.model,g;try{g=x(c);}catch(d){return {ok:false,data:"",error:{code:"PROVIDER_ERROR",message:d.message},meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}try{return {ok:!0,data:await g.execute(r,{model:a,context:t?.context,systemPrompt:o.inline?.system_prompt??o.inline?.prompt}),meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}catch(d){return {ok:false,data:"",error:{code:"EXECUTE_FAILED",message:d.message},meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}}};var F=z.object({model:z.string().optional(),system_prompt:z.string().optional(),prompt:z.string().optional(),layout:z.union([z.string(),z.object({id:z.string(),props:z.record(z.unknown()).optional()}),z.object({props:z.record(z.unknown())}),z.object({template:z.string()})]).optional()}).catchall(z.unknown()),U=z.object({include:z.array(z.string()).optional()}).optional(),N=z.object({id:z.string(),name:z.string().optional(),role:z.string().optional(),team:z.string().optional(),provider:z.union([z.string(),z.array(z.string())]),working_directory:z.string().optional(),description:z.string().optional(),tags:z.array(z.string()).optional(),inline:F.optional(),skills:U}).catchall(z.unknown()),_=z.object({agents:z.array(N).optional(),hooks:z.array(z.unknown()).optional(),settings:z.record(z.unknown()).optional(),skills:z.unknown().optional(),layouts:z.record(z.unknown()).optional(),documents:z.record(z.unknown()).optional()}).catchall(z.unknown());var f=class extends Error{constructor(r,t){super(r);this.cause=t;this.name="ConfigLoadError";}cause};function Q(s){if(!s||typeof s!="string"||!s.trim())throw new f("YAML content must be a non-empty string");let e;try{e=load(s);}catch(i){throw new f(`YAML parse error: ${i.message}`,i)}let r=K(e),t=_.safeParse(r);if(!t.success)throw new f(`Config validation error: ${t.error.message}`);return t.data}function K(s){if(!s||typeof s!="object")return {agents:[]};let e=s;if(e.agents&&typeof e.agents=="object"&&!Array.isArray(e.agents)){let r=e.agents,t=Object.entries(r).map(([i,o])=>({id:i,...o&&typeof o=="object"?o:{}}));return {...e,agents:t}}return e.agents?e:{...e,agents:[]}}var $="crewx:fs:",E=class{prefix;store;constructor(e){this.prefix=e?.prefix??$,this.store=e?.storage??new Map;}async readFile(e){let r=this.toKey(e),t=this.store.get(r);if(t===void 0)throw new Error(`BrowserFsAdapter: file not found: ${e}`);return t}async exists(e){return this.store.has(this.toKey(e))}resolvePath(...e){let r=e.map(p=>p.replace(/\\/g,"/")).join("/").replace(/\/+/g,"/"),t=r.split("/"),i=[];for(let p of t)p==="."||p===""||(p===".."?i.pop():i.push(p));let o=i.join("/");return r.startsWith("/")?`/${o}`:o}isAbsolute(e){return e.startsWith("/")}setItem(e,r){this.store.set(this.toKey(e),r);}removeItem(e){this.store.delete(this.toKey(e));}keys(){return Array.from(this.store.keys()).filter(e=>e.startsWith(this.prefix)).map(e=>e.slice(this.prefix.length))}async readdir(e){let r=e.replace(/\\/g,"/").replace(/\/$/,""),t=this.toKey(r+"/"),i=[];for(let o of this.store.keys())if(o.startsWith(t)){let c=o.slice(t.length).split("/")[0];c&&!i.includes(c)&&i.push(c);}return i}toKey(e){return `${this.prefix}${e.replace(/\\/g,"/")}`}};var C=["codex","claude","opencode","antigravity","copilot"];function S(s){let e=s.indexOf("/");return e===-1?s:s.slice(e+1)}function R(s){let e=S(s),r=C.indexOf(e);return r===-1?C.length:r}function B(s,e){return R(s)-R(e)}export{E as BrowserFsAdapter,f as ConfigLoadError,A as Crewx,C as PROVIDER_ORDER,u as ProviderError,B as compareProviders,x as createProvider,Q as parseYamlContent,R as providerRank,P as registerProviderFactory};
2
+ `);y=O.pop();for(let M of O){let h=M.trim();if(!h||!h.startsWith("data: "))continue;let k=h.slice(6);if(k!=="[DONE]")try{let b=JSON.parse(k).choices?.[0]?.delta?.content??"";l+=b,b&&p?.onOutput&&p.onOutput(l,"stdout");}catch{}}}return i.push({role:"user",content:o}),i.push({role:"assistant",content:l}),l},async execute(o,p){return this.query(o,p)}});}get agents(){return this._agents}get config(){return this._config}get tools(){return this._tools}registerTool(e,r){this._tools.set(e,{name:e,...r});}async query(e,r,t){let i=Date.now(),o;try{o=w(e,Array.from(this._agents.values()));}catch(d){if(d instanceof m)return {ok:false,data:"",error:{code:"AGENT_NOT_FOUND",message:d.message},meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:Date.now()-i}};throw d}let p=Array.isArray(o.provider)?o.provider[0]??"api/default":o.provider,c=t?.provider??p,a=t?.model??o.inline?.model,g;try{g=x(c);}catch(d){return {ok:false,data:"",error:{code:"PROVIDER_ERROR",message:d.message},meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}try{return {ok:!0,data:await g.query(r,{model:a,context:t?.context,systemPrompt:o.inline?.system_prompt??o.inline?.prompt,onOutput:t?.onOutput?l=>t.onOutput(l):void 0}),meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}catch(d){return {ok:false,data:"",error:{code:"QUERY_FAILED",message:d.message},meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}}async execute(e,r,t){let i=Date.now(),o;try{o=w(e,Array.from(this._agents.values()));}catch(d){if(d instanceof m)return {ok:false,data:"",error:{code:"AGENT_NOT_FOUND",message:d.message},meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:Date.now()-i}};throw d}let p=Array.isArray(o.provider)?o.provider[0]??"api/default":o.provider,c=t?.provider??p,a=t?.model??o.inline?.model,g;try{g=x(c);}catch(d){return {ok:false,data:"",error:{code:"PROVIDER_ERROR",message:d.message},meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}try{return {ok:!0,data:await g.execute(r,{model:a,context:t?.context,systemPrompt:o.inline?.system_prompt??o.inline?.prompt}),meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}catch(d){return {ok:false,data:"",error:{code:"EXECUTE_FAILED",message:d.message},meta:{agentId:o.id,provider:c,model:a,durationMs:Date.now()-i}}}}};var F=z.object({model:z.string().optional(),system_prompt:z.string().optional(),prompt:z.string().optional(),layout:z.union([z.string(),z.object({id:z.string(),props:z.record(z.unknown()).optional()}),z.object({props:z.record(z.unknown())}),z.object({template:z.string()})]).optional()}).catchall(z.unknown()),U=z.object({include:z.array(z.string()).optional()}).optional(),N=z.object({id:z.string(),name:z.string().optional(),role:z.string().optional(),team:z.string().optional(),provider:z.union([z.string(),z.array(z.string())]),working_directory:z.string().optional(),description:z.string().optional(),tags:z.array(z.string()).optional(),inline:F.optional(),skills:U}).catchall(z.unknown()),_=z.object({agents:z.array(N).optional(),hooks:z.array(z.unknown()).optional(),settings:z.record(z.unknown()).optional(),skills:z.unknown().optional(),layouts:z.record(z.unknown()).optional(),documents:z.record(z.unknown()).optional()}).catchall(z.unknown());var f=class extends Error{constructor(r,t){super(r);this.cause=t;this.name="ConfigLoadError";}cause};function Q(s){if(!s||typeof s!="string"||!s.trim())throw new f("YAML content must be a non-empty string");let e;try{e=load(s);}catch(i){throw new f(`YAML parse error: ${i.message}`,i)}let r=S(e),t=_.safeParse(r);if(!t.success)throw new f(`Config validation error: ${t.error.message}`);return t.data}function S(s){if(!s||typeof s!="object")return {agents:[]};let e=s;if(e.agents&&typeof e.agents=="object"&&!Array.isArray(e.agents)){let r=e.agents,t=Object.entries(r).map(([i,o])=>({id:i,...o&&typeof o=="object"?o:{}}));return {...e,agents:t}}return e.agents?e:{...e,agents:[]}}var K="crewx:fs:",E=class{prefix;store;constructor(e){this.prefix=e?.prefix??K,this.store=e?.storage??new Map;}async readFile(e){let r=this.toKey(e),t=this.store.get(r);if(t===void 0)throw new Error(`BrowserFsAdapter: file not found: ${e}`);return t}async exists(e){return this.store.has(this.toKey(e))}resolvePath(...e){let r=e.map(p=>p.replace(/\\/g,"/")).join("/").replace(/\/+/g,"/"),t=r.split("/"),i=[];for(let p of t)p==="."||p===""||(p===".."?i.pop():i.push(p));let o=i.join("/");return r.startsWith("/")?`/${o}`:o}isAbsolute(e){return e.startsWith("/")}setItem(e,r){this.store.set(this.toKey(e),r);}removeItem(e){this.store.delete(this.toKey(e));}keys(){return Array.from(this.store.keys()).filter(e=>e.startsWith(this.prefix)).map(e=>e.slice(this.prefix.length))}async readdir(e){let r=e.replace(/\\/g,"/").replace(/\/$/,""),t=this.toKey(r+"/"),i=[];for(let o of this.store.keys())if(o.startsWith(t)){let c=o.slice(t.length).split("/")[0];c&&!i.includes(c)&&i.push(c);}return i}toKey(e){return `${this.prefix}${e.replace(/\\/g,"/")}`}};var C=["codex","claude","opencode","antigravity","copilot"];function $(s){let e=s.indexOf("/");return e===-1?s:s.slice(e+1)}function R(s){let e=$(s),r=C.indexOf(e);return r===-1?C.length:r}function B(s,e){return R(s)-R(e)}export{E as BrowserFsAdapter,f as ConfigLoadError,A as Crewx,C as PROVIDER_ORDER,u as ProviderError,B as compareProviders,x as createProvider,Q as parseYamlContent,R as providerRank,P as registerProviderFactory};