@crewx/sdk 0.9.0-rc.30 → 0.9.0-rc.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +62 -62
- package/dist/esm/plugins/index.js +33 -33
- package/dist/esm/repository/index.js +30 -30
- package/dist/index.browser.js +2 -2
- package/dist/index.js +63 -63
- package/dist/internal/windows-spawn.d.ts +10 -0
- package/dist/migrations/0012_blue_turbo.sql +23 -0
- package/dist/migrations/0013_hesitant_adam_destine.sql +15 -0
- package/dist/migrations/meta/0012_snapshot.json +1494 -0
- package/dist/migrations/meta/0013_snapshot.json +1592 -0
- package/dist/migrations/meta/_journal.json +14 -0
- package/dist/plugin/types.d.ts +1 -0
- package/dist/plugins/index.js +29 -29
- package/dist/repository/agent-suggestion.repository.d.ts +31 -0
- package/dist/repository/index.d.ts +4 -0
- package/dist/repository/index.js +30 -30
- package/dist/repository/notification.repository.d.ts +58 -0
- package/dist/schema/agent-suggestions.d.ts +199 -0
- package/dist/schema/index.d.ts +2 -0
- package/dist/schema/notifications.d.ts +303 -0
- package/dist/types/index.d.ts +28 -3
- package/dist/utils/id.d.ts +1 -1
- package/package.json +1 -1
- package/templates/agents/default.yaml +28 -1
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as Q from'path';import Q__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import _e,{existsSync,mkdirSync,readFileSync}from'fs';import Je from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,lt,or,like,asc,inArray,gte,lte}from'drizzle-orm';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var Rt=(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 Ke=()=>fileURLToPath(import.meta.url),Ge=()=>Q__default.dirname(Ke()),b=Ge();var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Je.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 g(a){let t=Rt("better-sqlite3"),{drizzle:e}=Rt("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:e(n),runRaw:(r,o=[])=>n.prepare(r).run(...o),close:()=>n.close()}}var te=new Set,Qe={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 It(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Ve(a,t){if(t>0||!It(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(r=>r.name));for(let[r,o]of Object.entries(Qe))n.has(r)||a.run(`ALTER TABLE tasks ADD COLUMN ${r} ${o}`);}var Ze={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"}};function tn(a,t,e){if(!It(a,"__drizzle_migrations")||!It(a,"tasks"))return;let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(Q__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=Ze[i.tag];if(!l)continue;let u=Q__default.join(t,`${i.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),p=createHash("sha256").update(c).digest("hex");if(r.has(p))continue;let f=a.all("PRAGMA table_info(tasks)"),h=new Set(f.map(S=>S.name));for(let[S,P]of Object.entries(l))h.has(S)||(a.run(`ALTER TABLE tasks ADD COLUMN ${S} ${P}`),h.add(S));}}function en(a,t,e){let n=a.all(e`SELECT hash FROM __drizzle_migrations`),r=new Set(n.map(i=>i.hash)),o=JSON.parse(readFileSync(Q__default.join(t,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let l=Q__default.join(t,`${i.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],h;for(;(h=p.exec(u))!==null;)f.push({table:h[1],column:h[2]});if(f.length===0||!u.split(/-->\s*statement-breakpoint/).map($=>$.trim()).filter(Boolean).every($=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test($)))continue;f.every(({table:$,column:H})=>a.all(`PRAGMA table_info("${$}")`).some(G=>G.name===H))&&a.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function ut(a){let{migrate:t}=Rt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=Rt("drizzle-orm"),n=[Q__default.join(b,"../migrations"),Q__default.join(b,"migrations"),Q__default.join(b,"../../../../drizzle/migrations"),Q__default.join(process.cwd(),"drizzle/migrations")],r=n.find(c=>existsSync(Q__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${n.join(`
|
|
3
|
-
`)}`);let o=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),De(a,i),o?.cnt&&(Ne(a,r,e),Oe(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function O(a,t){Ft.has(t)||(st(a),Ft.add(t));}var m=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var s=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>m.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at),idx_threads_title:index("idx_threads_title").on(a.title)}));var G=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>G.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},a=>({idx_spans_task_id:index("idx_spans_task_id").on(a.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(a.parent_span_id)}));var j=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var M=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.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 ot=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));var N=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var $=sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},a=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));function Dt(a){let t=W.resolve(a);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,n)=>`${n.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Jt(a){let t=Dt(a);return createHash("sha256").update(t).digest("hex")}function kt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Nt=class extends x{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{st(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=kt(basename(n)),i=`${kt(basename(dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:m.id}).from(m).where(and(eq(m.slug,c),ne$1(m.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 p=`${i}-${c}`;if(!u(p))return p}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:m.id,slug:m.slug}).from(m).all(),n=0;for(let r of e)if(r.slug.includes("/")){let o=kt(r.slug.replace(/\//g,"-"));t.db.update(m).set({slug:o,updated_at:new Date().toISOString()}).where(eq(m.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:o,workspacePath:i}=e,l=new Date().toISOString();t.insert(m).values({id:n,slug:r,name:o,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(m).set({workspace_path:i,updated_at:l}).where(and(eq(m.id,n),isNull(m.workspace_path))).run();}registerWorkspace(t){let e=Dt(t),n=this.openHandle(true);try{let r=Jt(e),o=basename(e),i=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:i,name:o,workspacePath:e}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(m.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(m).where(n).get();return {rows:e.db.select().from(m).where(n).orderBy(desc(m.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(m).where(eq(m.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(r=>r.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
|
|
3
|
+
`)}`);let o=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ve(a,i),o?.cnt&&(en(a,r,e),tn(a,r,e)),t(a,{migrationsFolder:r});let u=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let c=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function D(a,t){te.has(t)||(ut(a),te.add(t));}var m=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var s=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>m.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(a.workspace_id,a.updated_at),idx_threads_title:index("idx_threads_title").on(a.title)}));var Z=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Z.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 X=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>s.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},a=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(a.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(a.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(a.timestamp)}));var j=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.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 pt=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 I=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},a=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(a.provider,a.account_ref,a.limit_window,a.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(a.limit_window,a.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(a.provider,a.limit_window,a.bucket_start)}));var M=sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},a=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(a.workspace_id,a.month)}));var w=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},a=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(a.workspace_id,sql`${a.created_at} DESC`)})),v=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},a=>({pk:primaryKey({columns:[a.notification_id,a.user_id]})}));var C=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},a=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(a.workspace_id,a.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(a.workspace_id,a.created_at)}));function $t(a){let t=Q.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 ce(a){let t=$t(a);return createHash("sha256").update(t).digest("hex")}function Dt(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Ht=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=g(e);if(t)try{ut(n.db);}catch(r){throw n.close(),r}return n}resolveSlug(t,e,n){let r=Dt(basename(n)),i=`${Dt(basename(dirname(n)))}-${r}`,l=[r,i];try{let u=c=>t.select({id:m.id}).from(m).where(and(eq(m.slug,c),ne(m.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 p=`${i}-${c}`;if(!u(p))return p}}catch{}return r}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:m.id,slug:m.slug}).from(m).all(),n=0;for(let r of e)if(r.slug.includes("/")){let o=Dt(r.slug.replace(/\//g,"-"));t.db.update(m).set({slug:o,updated_at:new Date().toISOString()}).where(eq(m.id,r.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:r,name:o,workspacePath:i}=e,l=new Date().toISOString();t.insert(m).values({id:n,slug:r,name:o,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(m).set({workspace_path:i,updated_at:l}).where(and(eq(m.id,n),isNull(m.workspace_path))).run();}registerWorkspace(t){let e=$t(t),n=this.openHandle(true);try{let r=ce(e),o=basename(e),i=this.resolveSlug(n.db,r,e);return this.ensureRow(n.db,{id:r,slug:i,name:o,workspacePath:e}),{id:r,slug:i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to register workspace",r)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(m.is_active,t.isActive?1:0):void 0,r=e.db.select({count:sql`count(*)`}).from(m).where(n).get();return {rows:e.db.select().from(m).where(n).orderBy(desc(m.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(m).where(eq(m.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(m).where(eq(m.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(m.slug,t),ne
|
|
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(m).where(eq(m.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(m.slug,t),ne(m.id,e)):eq(m.slug,t);return !!n.db.select({id:m.id}).from(m).where(r).limit(1).get()}catch(r){throw new d("DB_ERROR","Failed to check slug",r)}finally{n.close();}}insert(t,e,n,r){let o=this.openHandle(true);try{let i=new Date().toISOString();o.db.insert(m).values({id:t,slug:e,name:n,workspace_path:r,is_active:1,created_at:i,updated_at:i}).run();let l=o.db.select().from(m).where(eq(m.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(i){throw i instanceof d?i:new d("DB_ERROR","Failed to insert workspace",i)}finally{o.close();}}update(t,e,n){let r=this.openHandle(true);try{r.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let o=r.db.select().from(m).where(eq(m.id,t)).limit(1).get();if(!o)throw new d("NOT_FOUND",`Workspace ${t} not found`);return o}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update workspace",o)}finally{r.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:m.id,workspace_path:m.workspace_path}).from(m).where(and(eq(m.is_active,1),isNotNull(m.workspace_path))).all(),n=0;for(let r of e){let o=r.workspace_path;existsSync(join(o,"crewx.yaml"))||existsSync(join(o,"crewx.yml"))||(t.db.update(m).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(m.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(m).where(eq(m.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var he=[m,s,_,Z,X,j,pt];function Pn(){return Q__default.join(Je.homedir(),".crewx","crewx.db")}function Ln(a){if(!_e.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return _e.copyFileSync(a,e),e}function me(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 $n(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 Bn(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=$n(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Un(a,t){let e=t?.dbPath??Pn(),n=t?.force??false,r=t?.dryRun??false,o=r?null:Ln(e);if(n&&!r)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=me(a);if(!r)try{ut(a);}catch(f){let h=f instanceof Error?`${f.message} ${f.cause?.message??""}`:"";if(!n||!h.includes("duplicate column"))throw f}let l,u;r?(l=he.map(h=>getTableConfig(h).name).filter(h=>!i.has(h)),u=i):(u=me(a),l=[...u].filter(f=>!i.has(f)));let c=[],p=[];for(let f of he){let h=getTableConfig(f),S=h.name;if(!u.has(S))continue;let P=a.all(`PRAGMA table_info("${S}")`),$=new Set(P.map(T=>T.name)),H=new Set(h.columns.map(T=>T.name));for(let T of h.columns)if(!$.has(T.name)){if(!r){let G=Bn(T);a.run(`ALTER TABLE "${S}" ADD COLUMN ${G}`);}c.push({table:S,column:T.name});}for(let T of P)H.has(T.name)||p.push(`${S}.${T.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:p,backupPath:o}}function ge(a){let t=a.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}var ot="2026-05-09",jn="0.8.9-rc.13",st=10,it=parseInt(jn.split("rc.")[1]),Wn=new Set(["workflow","mcp"]),ke=600*1e3,Ft=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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(s).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:s.id,set:{pid:sql`COALESCE(excluded.pid, ${s.pid})`},setWhere:eq(s.status,"running")}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{let n=t.runEpoch??null;e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
9
9
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
10
10
|
model=COALESCE(?, model)
|
|
11
|
-
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({logs:s.logs}).from(s).where(eq(s.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(e),r.update(s).set({logs:JSON.stringify(i)}).where(eq(s.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).where(eq(s.status,"running")).orderBy(desc(s.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).orderBy(desc(s.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(s).where(eq(s.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:s.id,status:s.status,pid:s.pid}).from(s).where(eq(s.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(s.id,t),eq(s.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(eq(s.status,"running")).all(),n=Date.now(),r=new Set,o=0;for(let i of e){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(t.db.update(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(s.id,i.id),eq(s.status,"running"))).run(),o++);continue}if(
|
|
11
|
+
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({logs:s.logs}).from(s).where(eq(s.id,t)).limit(1).get(),i=o?.logs?JSON.parse(o.logs):[];i.push(e),r.update(s).set({logs:JSON.stringify(i)}).where(eq(s.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to append log",r)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).where(eq(s.status,"running")).orderBy(desc(s.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(s).orderBy(desc(s.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(s).where(eq(s.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:s.id,status:s.status,pid:s.pid}).from(s).where(eq(s.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(s).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(s.id,t),eq(s.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:s.id,pid:s.pid,platform:s.platform,run_epoch:s.run_epoch}).from(s).where(eq(s.status,"running")).all(),n=Date.now(),r=new Set,o=0;for(let i of e){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(t.db.update(s).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(s.id,i.id),eq(s.status,"running"))).run(),o++);continue}if(Wn.has(i.platform??"cli"))continue;let l=`${i.id}:${i.run_epoch??0}`;r.add(l);let u=this.pidNullObservedSince.get(l);if(u===void 0){this.pidNullObservedSince.set(l,n);continue}n-u>=ke&&(t.db.update(s).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(s.id,i.id),eq(s.status,"running"))).run(),o++,this.pidNullObservedSince.delete(l));}for(let i of Array.from(this.pidNullObservedSince.keys()))r.has(i)||this.pidNullObservedSince.delete(i);return o}finally{t.close();}}reapRunningWorkflowTasks(t=ke){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let n=new Date(Date.now()-t).toISOString();return e.db.update(s).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(s.status,"running"),eq(s.platform,"workflow"),isNull(s.pid),lt(s.started_at,n))).run().changes??0}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=g(r);try{let i=e?eq(s.workspace_id,e):void 0,l=i?and(eq(s.id,t),i):eq(s.id,t),u=o.db.select().from(s).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),p=i?and(c,i):c;u=o.db.select().from(s).where(p).orderBy(desc(s.started_at)).limit(1).get()??void 0;}if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=g(i);try{let u=e?and(eq(s.parent_task_id,t),eq(s.workspace_id,e)):eq(s.parent_task_id,t),c=l.db.select().from(s).where(u).orderBy(asc(s.started_at)).all();for(let p of c)r.has(p.id)||(r.add(p.id),o.push(p));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return o}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
12
12
|
SELECT
|
|
13
13
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
14
14
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -29,7 +29,7 @@ ${n.join(`
|
|
|
29
29
|
FROM tasks
|
|
30
30
|
GROUP BY workspace_id
|
|
31
31
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
32
|
-
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,o=0,i=0,l=0;for(let u of n){if(!existsSync(u))continue;let c=
|
|
32
|
+
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),r=new Set,o=0,i=0,l=0;for(let u of n){if(!existsSync(u))continue;let c=g(u);try{let p=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),f=e?and(p,eq(s.workspace_id,e)):p,h=c.db.select({id:s.id,input_tokens:s.input_tokens,output_tokens:s.output_tokens,cost_usd:s.cost_usd}).from(s).where(f).all();for(let S of h)r.has(S.id)||(r.add(S.id),o+=S.input_tokens??0,i+=S.output_tokens??0,l+=S.cost_usd??0);}catch(p){throw new d("DB_ERROR","Failed to get thread token usage",p)}finally{c.close();}}return {inputTokens:o,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=g(i);try{let u=or(eq(s.thread_id,t),and(isNull(s.thread_id),like(s.command,`%--thread=${t}%`))),c=e?and(u,eq(s.workspace_id,e)):u,p=l.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),o.push(f));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{l.close();}}return o}parseWorkflowCardMetadata(t){if(!t)return {};try{let e=JSON.parse(t);return {kind:typeof e.kind=="string"?e.kind:void 0,workflowRunId:typeof e.workflowRunId=="string"?e.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}batchFetchWorkflowCards(t,e){let n=new Map;if(t.length===0)return n;let r=new Set(t),o=new Map,i=e?eq(s.workspace_id,e):void 0,l=(u,c)=>{if(!u)return;let p=o.get(u);if(p&&c.started_at<=p)return;let f=this.parseWorkflowCardMetadata(c.metadata);f.kind==="workflow_card"&&(o.set(u,c.started_at),n.set(u,{taskId:c.id,workflowRunId:f.workflowRunId,raw:c.result??void 0}));};for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let c=g(u);try{let p=and(inArray(s.thread_id,t),like(s.metadata,'%"kind":"workflow_card"%')),f=c.db.select({id:s.id,thread_id:s.thread_id,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(i?and(p,i):p).all();for(let P of f)l(P.thread_id,P);let h=and(isNull(s.thread_id),like(s.metadata,'%"kind":"workflow_card"%')),S=c.db.select({id:s.id,command:s.command,metadata:s.metadata,result:s.result,started_at:s.started_at}).from(s).where(i?and(h,i):h).all();for(let P of S){let $=this.extractThreadIdFromCommand(P.command);!$||!r.has($)||l($,P);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{c.close();}}return n}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(s.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&n.push(inArray(s.agent_id,r));let o=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;o&&n.push(inArray(s.status,o));let i=t.q??t.search;i&&n.push(like(s.prompt,`%${i}%`)),t.from&&n.push(gte(s.started_at,t.from)),t.to&&n.push(lt(s.started_at,t.to));let l=n.length>0?and(...n):void 0,u=e.db.select({count:sql`count(*)`}).from(s).where(l).get(),c=(t.sortDir??"DESC")==="ASC"?asc(s.started_at):desc(s.started_at);return {rows:e.db.select().from(s).where(l).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{e.close();}}getAgentUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(n?sql`
|
|
33
33
|
SELECT
|
|
34
34
|
t.agent_id,
|
|
35
35
|
t.workspace_id,
|
|
@@ -37,11 +37,11 @@ ${n.join(`
|
|
|
37
37
|
COALESCE(SUM(
|
|
38
38
|
COALESCE(t.input_tokens, 0)
|
|
39
39
|
+ CASE
|
|
40
|
-
WHEN t.started_at >= ${
|
|
40
|
+
WHEN t.started_at >= ${ot}
|
|
41
41
|
AND (
|
|
42
42
|
t.crewx_version IS NULL
|
|
43
43
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
44
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
44
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${st}) AS INTEGER) < ${it})
|
|
45
45
|
)
|
|
46
46
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
47
47
|
ELSE 0
|
|
@@ -60,11 +60,11 @@ ${n.join(`
|
|
|
60
60
|
COALESCE(SUM(
|
|
61
61
|
COALESCE(t.input_tokens, 0)
|
|
62
62
|
+ CASE
|
|
63
|
-
WHEN t.started_at >= ${
|
|
63
|
+
WHEN t.started_at >= ${ot}
|
|
64
64
|
AND (
|
|
65
65
|
t.crewx_version IS NULL
|
|
66
66
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
67
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
67
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${st}) AS INTEGER) < ${it})
|
|
68
68
|
)
|
|
69
69
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
70
70
|
ELSE 0
|
|
@@ -80,11 +80,11 @@ ${n.join(`
|
|
|
80
80
|
COALESCE(SUM(
|
|
81
81
|
COALESCE(t.input_tokens, 0)
|
|
82
82
|
+ CASE
|
|
83
|
-
WHEN t.started_at >= ${
|
|
83
|
+
WHEN t.started_at >= ${ot}
|
|
84
84
|
AND (
|
|
85
85
|
t.crewx_version IS NULL
|
|
86
86
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
87
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
87
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${st}) AS INTEGER) < ${it})
|
|
88
88
|
)
|
|
89
89
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
90
90
|
ELSE 0
|
|
@@ -102,11 +102,11 @@ ${n.join(`
|
|
|
102
102
|
COALESCE(SUM(
|
|
103
103
|
COALESCE(t.input_tokens, 0)
|
|
104
104
|
+ CASE
|
|
105
|
-
WHEN t.started_at >= ${
|
|
105
|
+
WHEN t.started_at >= ${ot}
|
|
106
106
|
AND (
|
|
107
107
|
t.crewx_version IS NULL
|
|
108
108
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
109
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
109
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${st}) AS INTEGER) < ${it})
|
|
110
110
|
)
|
|
111
111
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
112
112
|
ELSE 0
|
|
@@ -121,11 +121,11 @@ ${n.join(`
|
|
|
121
121
|
COALESCE(SUM(
|
|
122
122
|
COALESCE(t.input_tokens, 0)
|
|
123
123
|
+ CASE
|
|
124
|
-
WHEN t.started_at >= ${
|
|
124
|
+
WHEN t.started_at >= ${ot}
|
|
125
125
|
AND (
|
|
126
126
|
t.crewx_version IS NULL
|
|
127
127
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
128
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
128
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${st}) AS INTEGER) < ${it})
|
|
129
129
|
)
|
|
130
130
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
131
131
|
ELSE 0
|
|
@@ -148,11 +148,11 @@ ${n.join(`
|
|
|
148
148
|
COALESCE(SUM(
|
|
149
149
|
COALESCE(t.input_tokens, 0)
|
|
150
150
|
+ CASE
|
|
151
|
-
WHEN t.started_at >= ${
|
|
151
|
+
WHEN t.started_at >= ${ot}
|
|
152
152
|
AND (
|
|
153
153
|
t.crewx_version IS NULL
|
|
154
154
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
155
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
155
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${st}) AS INTEGER) < ${it})
|
|
156
156
|
)
|
|
157
157
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
158
158
|
ELSE 0
|
|
@@ -167,7 +167,7 @@ ${n.join(`
|
|
|
167
167
|
AND t.started_at < ${e}
|
|
168
168
|
GROUP BY date(t.started_at), t.agent_id
|
|
169
169
|
ORDER BY date(t.started_at) ASC
|
|
170
|
-
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(o){throw new d("DB_ERROR","Failed to get agent usage trend",o)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(s).where(and(eq(s.id,t),eq(s.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString(),i=n?and(eq(s.id,t),eq(s.status,"running"),eq(s.workspace_id,n)):and(eq(s.id,t),eq(s.status,"running"));r.db.update(s).set({status:"failed",error:e,completed_at:o}).where(i).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to mark task failed",o)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=
|
|
170
|
+
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(o){throw new d("DB_ERROR","Failed to get agent usage trend",o)}finally{r.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(s).where(and(eq(s.id,t),eq(s.workspace_id,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find task for stop",r)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString(),i=n?and(eq(s.id,t),eq(s.status,"running"),eq(s.workspace_id,n)):and(eq(s.id,t),eq(s.status,"running"));r.db.update(s).set({status:"failed",error:e,completed_at:o}).where(i).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to mark task failed",o)}finally{r.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=g(i);try{let u=e?and(like(s.prompt,`%${t}%`),eq(s.workspace_id,e)):like(s.prompt,`%${t}%`),c=l.db.select().from(s).where(u).orderBy(asc(s.started_at)).all();for(let p of c)r.has(p.id)||(r.add(p.id),o.push(p));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{l.close();}}return o}getProviderUsage(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=sql`
|
|
171
171
|
CASE
|
|
172
172
|
WHEN ${s.model} LIKE 'claude-%' OR ${s.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
173
173
|
WHEN ${s.model} LIKE 'gpt-%' OR ${s.model} LIKE 'codex-%' THEN 'codex'
|
|
@@ -180,11 +180,11 @@ ${n.join(`
|
|
|
180
180
|
`,i=sql`
|
|
181
181
|
COALESCE(${s.input_tokens}, 0)
|
|
182
182
|
+ CASE
|
|
183
|
-
WHEN ${s.started_at} >= ${
|
|
183
|
+
WHEN ${s.started_at} >= ${ot}
|
|
184
184
|
AND (
|
|
185
185
|
${s.crewx_version} IS NULL
|
|
186
186
|
OR (${s.crewx_version} LIKE '0.8.%' AND ${s.crewx_version} NOT LIKE '0.8.9%')
|
|
187
|
-
OR (${s.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${s.crewx_version}, ${
|
|
187
|
+
OR (${s.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${s.crewx_version}, ${st}) AS INTEGER) < ${it})
|
|
188
188
|
)
|
|
189
189
|
THEN COALESCE(${s.cached_input_tokens}, 0)
|
|
190
190
|
ELSE 0
|
|
@@ -216,11 +216,11 @@ ${n.join(`
|
|
|
216
216
|
`,i=sql`
|
|
217
217
|
COALESCE(${s.input_tokens}, 0)
|
|
218
218
|
+ CASE
|
|
219
|
-
WHEN ${s.started_at} >= ${
|
|
219
|
+
WHEN ${s.started_at} >= ${ot}
|
|
220
220
|
AND (
|
|
221
221
|
${s.crewx_version} IS NULL
|
|
222
222
|
OR (${s.crewx_version} LIKE '0.8.%' AND ${s.crewx_version} NOT LIKE '0.8.9%')
|
|
223
|
-
OR (${s.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${s.crewx_version}, ${
|
|
223
|
+
OR (${s.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${s.crewx_version}, ${st}) AS INTEGER) < ${it})
|
|
224
224
|
)
|
|
225
225
|
THEN COALESCE(${s.cached_input_tokens}, 0)
|
|
226
226
|
ELSE 0
|
|
@@ -239,7 +239,7 @@ ${n.join(`
|
|
|
239
239
|
FROM ${s}
|
|
240
240
|
${l}
|
|
241
241
|
GROUP BY ${s.model}
|
|
242
|
-
`),c=new Map;for(let p of u){let
|
|
242
|
+
`),c=new Map;for(let p of u){let f=ge(p.model??""),h=c.get(f);h?(h.totalTasks+=p.total_tasks,h.inputTokens+=p.input_tokens,h.outputTokens+=p.output_tokens,h.cachedInputTokens+=p.cached_input_tokens,h.costUsd+=p.cost_usd,h.totalTokens+=p.input_tokens+p.output_tokens,h.activeDurationMs+=p.active_duration_ms??0,p.last_active_at&&(!h.lastActiveAt||p.last_active_at>h.lastActiveAt)&&(h.lastActiveAt=p.last_active_at)):c.set(f,{model:f,provider:p.provider,totalTasks:p.total_tasks,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null});}return Array.from(c.values()).sort((p,f)=>f.costUsd-p.costUsd)}catch(o){throw new d("DB_ERROR","Failed to get model usage",o)}finally{r.close();}}getTasksForReport(t,e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=n?sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e} AND ${s.workspace_id} = ${n}`:sql`WHERE ${s.started_at} >= ${t} AND ${s.started_at} < ${e}`;return r.db.all(sql`
|
|
243
243
|
SELECT
|
|
244
244
|
${s.thread_id} AS thread_id,
|
|
245
245
|
${s.agent_id} AS agent_id,
|
|
@@ -250,11 +250,11 @@ ${n.join(`
|
|
|
250
250
|
FROM ${s}
|
|
251
251
|
${o}
|
|
252
252
|
ORDER BY ${s.started_at} ASC
|
|
253
|
-
`).map(l=>({threadId:l.thread_id,agentId:l.agent_id,startedAt:l.started_at,status:l.status,error:l.error,exitCode:l.exit_code}))}catch(o){throw new d("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}};var
|
|
253
|
+
`).map(l=>({threadId:l.thread_id,agentId:l.agent_id,startedAt:l.started_at,status:l.status,error:l.error,exitCode:l.exit_code}))}catch(o){throw new d("DB_ERROR","Failed to get tasks for report",o)}finally{r.close();}}};var qt=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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}validateWorkspaceId(t,e){return t.db.select({id:m.id}).from(m).where(eq(m.id,e)).limit(1).get()?e:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
|
|
254
254
|
SELECT 1 FROM tasks parent
|
|
255
255
|
WHERE parent.id = ${t}.parent_task_id
|
|
256
256
|
AND parent.thread_id = ${t}.thread_id
|
|
257
|
-
)`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let o of e){if(!existsSync(o))continue;let i=
|
|
257
|
+
)`)}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,r=[];for(let o of e){if(!existsSync(o))continue;let i=g(o);try{let l=t?eq(_.workspace_id,t):void 0,u=i.db.select().from(_).where(l).orderBy(desc(_.updated_at)).all();for(let c of u)n.has(c.id)||(n.add(c.id),r.push(c));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return r}findThreadsByIdsOrTitles(t,e){if(t.length===0)return [];let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=g(i);try{let u=or(inArray(_.id,t),inArray(_.title,t)),c=e?and(u,eq(_.workspace_id,e)):u,p=l.db.select().from(_).where(c).orderBy(desc(_.updated_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),o.push(f));}catch(u){throw new d("DB_ERROR","Failed to find threads by ids or titles",u)}finally{l.close();}}return o}findThreadById(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=g(r);try{let i=eq(_.id,t),l=e?and(i,eq(_.workspace_id,e)):i,u=o.db.select().from(_).where(l).limit(1).get()??void 0;if(u)return u}catch(i){throw new d("DB_ERROR","Failed to find thread by id",i)}finally{o.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=g(r);try{let i=eq(_.id,t),l=e?and(i,eq(_.workspace_id,e)):i;if(o.db.select({id:_.id}).from(_).where(l).limit(1).get())return !0}catch(i){throw new d("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),r=0,o=0,i=0,l=0,u=0,c=new Set;for(let p of n){if(!existsSync(p))continue;let f=g(p);try{let h=f.db.get(sql`
|
|
258
258
|
SELECT
|
|
259
259
|
count(*) AS cnt,
|
|
260
260
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -265,13 +265,13 @@ ${n.join(`
|
|
|
265
265
|
WHERE child.thread_id = ${t}
|
|
266
266
|
AND ${this.topLevelTaskPredicateSql()}
|
|
267
267
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
268
|
-
`);
|
|
268
|
+
`);h&&(r+=h.cnt,o+=h.total_input,i+=h.total_output,l+=h.total_cached,u+=h.total_cost);let S=f.db.all(sql`
|
|
269
269
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
270
270
|
WHERE child.thread_id = ${t}
|
|
271
271
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
272
272
|
AND ${this.topLevelTaskPredicateSql()}
|
|
273
273
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
274
|
-
`);for(let
|
|
274
|
+
`);for(let P of S)c.add(P.agent_id);}catch(h){throw new d("DB_ERROR","Failed to aggregate task stats",h)}finally{f.close();}}return {taskCount:r,inputTokens:o,outputTokens:i,cachedInputTokens:l,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,e,n){let r=this.resolveDbPaths(),o=new Set,i=[];for(let l of r){if(!existsSync(l))continue;let u=g(l);try{let c;n!==void 0?c=u.db.all(sql`
|
|
275
275
|
SELECT * FROM (
|
|
276
276
|
SELECT child.*,
|
|
277
277
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -288,7 +288,7 @@ ${n.join(`
|
|
|
288
288
|
AND ${this.topLevelTaskPredicateSql()}
|
|
289
289
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
290
290
|
ORDER BY child.started_at ASC
|
|
291
|
-
`);for(let p of c)o.has(p.id)||(o.add(p.id),i.push(p));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&r.length>1){let l=new Map;for(let u of i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,p)=>(p.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,n));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=
|
|
291
|
+
`);for(let p of c)o.has(p.id)||(o.add(p.id),i.push(p));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(n!==void 0&&r.length>1){let l=new Map;for(let u of i){let c=u.agent_id??"";l.has(c)||l.set(c,[]),l.get(c).push(u);}i=[];for(let u of l.values())u.sort((c,p)=>(p.started_at??"").localeCompare(c.started_at??"")),i.push(...u.slice(0,n));i.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(t,e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let i of n){if(!existsSync(i))continue;let l=g(i);try{let u=eq(s.thread_id,t),c=e?and(u,eq(s.workspace_id,e)):u,p=l.db.select().from(s).where(c).orderBy(asc(s.started_at)).all();for(let f of p)r.has(f.id)||(r.add(f.id),o.push(f));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{l.close();}}return o}findTaskById(t,e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let i=g(o);try{let l=and(eq(s.id,e),eq(s.thread_id,t)),u=n?and(l,eq(s.workspace_id,n)):l,c=i.db.select().from(s).where(u).limit(1).get();if(!c)continue;let p=i.db.select().from(s).where(eq(s.parent_task_id,c.id)).orderBy(asc(s.started_at)).all();return {task:c,children:p}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasksQuery(t,e){return sql`
|
|
292
292
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
293
293
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
294
294
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -298,7 +298,7 @@ ${n.join(`
|
|
|
298
298
|
AND ${this.topLevelTaskPredicateSql()}
|
|
299
299
|
${e?sql`AND child.workspace_id = ${e}`:sql``}
|
|
300
300
|
ORDER BY child.started_at ASC
|
|
301
|
-
`}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let i=
|
|
301
|
+
`}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let i=g(o);try{let l=i.db.all(this.batchFetchTasksQuery(t,e));for(let u of l){let c=u.thread_id;n.has(c)||n.set(c,[]),n.get(c).push(u);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}explainBatchFetchTasksPlan(t,e){let n=this.resolveDbPaths();for(let r of n){if(!existsSync(r))continue;let o=g(r);try{return o.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,e)}`).map(l=>l.detail)}finally{o.close();}}return []}updateThreadTitle(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=eq(_.id,t),i=n?and(o,eq(_.workspace_id,n)):o;if(!r.db.select({id:_.id}).from(_).where(i).limit(1).get())return;r.db.update(_).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(_.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update thread title",o)}finally{r.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let r=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,o=new Date().toISOString();if(n.db.select({id:_.id,message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()){let l={updated_at:o};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(_).set(l).where(eq(_.id,t)).run();}else n.db.insert(_).values({id:t,platform:e.platform,workspace_id:r,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:o,updated_at:o}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to upsert thread",r)}finally{n.close();}}ensureThread(t,e,n){let r=this.openHandle(true);try{let o=n?this.validateWorkspaceId(r,n):null,i=r.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(eq(_.id,t)).limit(1).get();if(i){o&&!i.workspace_id&&r.db.update(_).set({workspace_id:o}).where(eq(_.id,t)).run();return}let l=new Date().toISOString();r.db.insert(_).values({id:t,platform:e,workspace_id:o,message_count:0,created_at:l,updated_at:l}).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to ensure thread",o)}finally{r.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let o=new Date().toISOString();return {firstMessage:r.db.transaction(l=>{let c=l.select({message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()?.message_count===0;return l.run(sql`
|
|
302
302
|
UPDATE threads
|
|
303
303
|
SET first_message = COALESCE(first_message, ${e}),
|
|
304
304
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
|
|
@@ -306,4 +306,4 @@ ${n.join(`
|
|
|
306
306
|
message_count = message_count + 1,
|
|
307
307
|
updated_at = ${o}
|
|
308
308
|
WHERE id = ${t}
|
|
309
|
-
`),c},{behavior:"immediate"})}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(_).set({last_message:e,updated_at:o}).where(eq(_.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save assistant message",o)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(_).set(r).where(eq(_.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(_.id,t),eq(_.workspace_id,e)):eq(_.id,t),o=n.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!o)return null;let i=o.pinned?0:1,l=o.metadata?JSON.parse(o.metadata):{};if(i){let u=e?and(eq(_.pinned,1),eq(_.workspace_id,e)):eq(_.pinned,1),c=n.db.select({metadata:_.metadata}).from(_).where(u).all(),p=null;for(let h of c){let f=h.metadata?JSON.parse(h.metadata):{};typeof f.pinOrder=="number"&&(p===null||f.pinOrder<p)&&(p=f.pinOrder);}l.pinOrder=p===null?0:p-1;}else delete l.pinOrder;return n.db.update(_).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let o=e?and(eq(_.id,t[r]),eq(_.workspace_id,e)):eq(_.id,t[r]),i=n.db.select({metadata:_.metadata}).from(_).where(o).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(_).set({metadata:JSON.stringify(l)}).where(o).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(_.id,t),eq(_.workspace_id,e)):eq(_.id,t),o=n.db.select({starred:_.starred}).from(_).where(r).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(_).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let l=e?and(eq(_.id,t),eq(_.workspace_id,e)):eq(_.id,t);return i.db.transaction(c=>{let p=c.select({metadata:_.metadata}).from(_).where(l).get();if(!p)return null;let h=p.metadata?JSON.parse(p.metadata):{},f=h.overdrive??{},y=r?.defaultTurns??f.defaultTurns??3,C=r?.updatedBy??"ui",v=new Date().toISOString(),P,S,F,it;switch(n){case "enable-count":{let at=r?.turns??y,dt=r?.consumeCurrent?Math.max(at-1,0):at;P=dt>0?"count":"off",S=dt,F=!0,it="count";break}case "enable-latch":{P="latch",S=0,F=!0,it="latch";break}case "disable":{P="off",S=0,F=!1;break}default:{let at=f.state??"off",dt=typeof f.remaining=="number"?f.remaining:0;if(at==="count"&&dt>0){let zt=dt-1;zt<=0?(P="off",S=0):(P="count",S=zt),F=!0,it="count";}else at==="latch"?(P="latch",S=0,F=!0,it="latch"):(P="off",S=0,F=!1);break}}return h.overdrive={state:P,remaining:S,defaultTurns:y,updatedAt:v,updatedBy:C},c.update(_).set({metadata:JSON.stringify(h),updated_at:v}).where(l).run(),{applied:F,appliedMode:it,state:P,remaining:S}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var $t=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(G).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(G).where(eq(G.task_id,t)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(G).where(eq(G.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{e.close();}}};var It=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(j).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(j).where(eq(j.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:j.tool_name,count:sql`count(*)`}).from(j).where(eq(j.task_id,t)).groupBy(j.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 Bt=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:_.id}).from(_).where(eq(_.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(M).where(eq(M.thread_id,t)).orderBy(asc(M.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(M).where(and(eq(M.id,e),eq(M.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(M).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(M).where(eq(M.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 Ut=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{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 o of t)r.insert(ot).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:n,metadata:o.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(ot).orderBy(desc(ot.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function me(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Mt=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=me(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(N).values({id:t.id,provider:t.provider,account_ref:r,limit_window:t.limitWindow,bucket_start:n,captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,source:t.source,metadata:t.metadata??null}).onConflictDoUpdate({target:[N.provider,N.account_ref,N.limit_window,N.bucket_start],set:{captured_at:t.capturedAt,used_percent:t.usedPercent,remaining_percent:t.remainingPercent,resets_at:t.resetsAt??null,metadata:t.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{e.close();}}getTrends(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{let n=e.db.select({provider:N.provider,bucket_start:N.bucket_start,used_percent:N.used_percent,remaining_percent:N.remaining_percent,resets_at:N.resets_at}).from(N).where(and(eq(N.limit_window,t.window),gte(N.bucket_start,t.fromIso),lte(N.bucket_start,t.toIso))).orderBy(asc(N.bucket_start)).all(),r=new Map;for(let o of n)r.has(o.provider)||r.set(o.provider,[]),r.get(o.provider).push({bucketStart:o.bucket_start,usedPercent:o.used_percent,remainingPercent:o.remaining_percent,resetsAt:o.resets_at??null});return Array.from(r.entries()).map(([o,i])=>({provider:o,points:i}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var Ht=class extends x{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let r=dirname(e);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert($).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[$.workspace_id,$.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let n=e.db.select().from($).where(and(eq($.workspace_id,t.workspaceId),eq($.month,t.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{e.close();}}findByMonth(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from($).where(and(eq($.workspace_id,t),eq($.month,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{n.close();}}listByWorkspace(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from($).where(eq($.workspace_id,t)).orderBy(desc($.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};export{x as BaseSqliteRepository,d as RepositoryError,Ut as RequestLogRepository,$t as SpanRepository,Lt as TaskRepository,Bt as ThreadBoxRepository,Pt as ThreadRepository,It as ToolCallRepository,Mt as UsageLimitSnapshotRepository,Ht as UsageReportRepository,Nt as WorkspaceRepository,me as calcBucketStart,k as openDrizzleDb,ln as pushSchema,st as runMigrations,O as runMigrationsOnce,s as tasks};
|
|
309
|
+
`),c},{behavior:"immediate"})}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save user message",o)}finally{r.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.update(_).set({last_message:e,updated_at:o}).where(eq(_.id,t)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to save assistant message",o)}finally{r.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};e.title!==void 0&&(r.title=e.title,r.title_locked=1),e.titleLocked!==void 0&&(r.title_locked=e.titleLocked?1:0),n.db.update(_).set(r).where(eq(_.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(_.id,t),eq(_.workspace_id,e)):eq(_.id,t),o=n.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!o)return null;let i=o.pinned?0:1,l=o.metadata?JSON.parse(o.metadata):{};if(i){let u=e?and(eq(_.pinned,1),eq(_.workspace_id,e)):eq(_.pinned,1),c=n.db.select({metadata:_.metadata}).from(_).where(u).all(),p=null;for(let f of c){let h=f.metadata?JSON.parse(f.metadata):{};typeof h.pinOrder=="number"&&(p===null||h.pinOrder<p)&&(p=h.pinOrder);}l.pinOrder=p===null?0:p-1;}else delete l.pinOrder;return n.db.update(_).set({pinned:i,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(r).run(),{pinned:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle pin",r)}finally{n.close();}}reorderPins(t,e){let n=this.openHandle(true);try{for(let r=0;r<t.length;r++){let o=e?and(eq(_.id,t[r]),eq(_.workspace_id,e)):eq(_.id,t[r]),i=n.db.select({metadata:_.metadata}).from(_).where(o).get();if(!i)continue;let l=i.metadata?JSON.parse(i.metadata):{};l.pinOrder=r+1,n.db.update(_).set({metadata:JSON.stringify(l)}).where(o).run();}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to reorder pins",r)}finally{n.close();}}toggleStar(t,e){let n=this.openHandle(true);try{let r=e?and(eq(_.id,t),eq(_.workspace_id,e)):eq(_.id,t),o=n.db.select({starred:_.starred}).from(_).where(r).get();if(!o)return null;let i=o.starred?0:1;return n.db.update(_).set({starred:i}).where(r).run(),{starred:!!i}}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to toggle star",r)}finally{n.close();}}resolveOverdriveForRequest(t,e,n,r){let i=this.openHandle(true);try{let l=e?and(eq(_.id,t),eq(_.workspace_id,e)):eq(_.id,t);return i.db.transaction(c=>{let p=c.select({metadata:_.metadata}).from(_).where(l).get();if(!p)return null;let f=p.metadata?JSON.parse(p.metadata):{},h=f.overdrive??{},S=r?.defaultTurns??h.defaultTurns??3,P=r?.updatedBy??"ui",$=new Date().toISOString(),H,T,G,ft;switch(n){case "enable-count":{let ht=r?.turns??S,mt=r?.consumeCurrent?Math.max(ht-1,0):ht;H=mt>0?"count":"off",T=mt,G=!0,ft="count";break}case "enable-latch":{H="latch",T=0,G=!0,ft="latch";break}case "disable":{H="off",T=0,G=!1;break}default:{let ht=h.state??"off",mt=typeof h.remaining=="number"?h.remaining:0;if(ht==="count"&&mt>0){let Zt=mt-1;Zt<=0?(H="off",T=0):(H="count",T=Zt),G=!0,ft="count";}else ht==="latch"?(H="latch",T=0,G=!0,ft="latch"):(H="off",T=0,G=!1);break}}return f.overdrive={state:H,remaining:T,defaultTurns:S,updatedAt:$,updatedBy:P},c.update(_).set({metadata:JSON.stringify(f),updated_at:$}).where(l).run(),{applied:G,appliedMode:ft,state:H,remaining:T}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to resolve overdrive",l)}finally{i.close();}}};var jt=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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(Z).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(Z).where(eq(Z.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(Z).where(eq(Z.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 Wt=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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(X).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(X).where(eq(X.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:X.tool_name,count:sql`count(*)`}).from(X).where(eq(X.task_id,t)).groupBy(X.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 Kt=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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}ensureThreadExists(t,e){if(!t.db.select({id:_.id}).from(_).where(eq(_.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(j).where(eq(j.thread_id,t)).orderBy(asc(j.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(j).where(and(eq(j.id,e),eq(j.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(j).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(j).where(eq(j.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 Gt=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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(r=>{for(let o of t)r.insert(pt).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:n,metadata:o.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(pt).orderBy(desc(pt.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};function Oe(a){return new Date(Math.floor(a/3e5)*3e5).toISOString()}var Yt=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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}upsert(t){let e=this.openHandle(true);try{let n=Oe(t.bucketStartMs),r=t.accountRef??"default";e.db.insert(I).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:[I.provider,I.account_ref,I.limit_window,I.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:I.provider,bucket_start:I.bucket_start,used_percent:I.used_percent,remaining_percent:I.remaining_percent,resets_at:I.resets_at}).from(I).where(and(eq(I.limit_window,t.window),gte(I.bucket_start,t.fromIso),lte(I.bucket_start,t.toIso))).orderBy(asc(I.bucket_start)).all(),r=new Map;for(let o of n)r.has(o.provider)||r.set(o.provider,[]),r.get(o.provider).push({bucketStart:o.bucket_start,usedPercent:o.used_percent,remainingPercent:o.remaining_percent,resetsAt:o.resets_at??null});return Array.from(r.entries()).map(([o,i])=>({provider:o,points:i}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{e.close();}}};var Xt=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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}publish(t){let e=this.openHandle(true);try{e.db.insert(M).values({id:t.id,workspace_id:t.workspaceId,month:t.month,generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}).onConflictDoUpdate({target:[M.workspace_id,M.month],set:{generated_at:t.generatedAt,source_range:t.sourceRange,tier:t.tier,total_tokens:t.totalTokens,total_cost_usd:t.totalCostUsd,payload:t.payload}}).run();let n=e.db.select().from(M).where(and(eq(M.workspace_id,t.workspaceId),eq(M.month,t.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{e.close();}}findByMonth(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(M).where(and(eq(M.workspace_id,t),eq(M.month,e))).limit(1).get()??void 0}catch(r){throw new d("DB_ERROR","Failed to find usage report",r)}finally{n.close();}}listByWorkspace(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(M).where(eq(M.workspace_id,t)).orderBy(desc(M.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{e.close();}}};var Pe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function xr(a){let t=randomBytes(a*2),e="";for(let n=0;n<t.length&&e.length<a;n++){let r=t[n];r<248&&(e+=Pe[r%62]);}for(;e.length<a;)e+=Pe[randomBytes(1)[0]%62];return e}function Ct(a){return `${a}_${xr(8)}`}var He=500,Me=50,Jt=class extends x{dbPath;cap;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db")),this.cap=t.cap??He;}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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}create(t){let e=this.openHandle(true);try{let n=Ct("ntf"),r=new Date().toISOString();return e.db.insert(w).values({id:n,workspace_id:t.workspaceId,agent_id:t.agentId??null,task_id:t.taskId??null,thread_id:t.threadId??null,source:t.source??"agent",level:t.level??"info",title:t.title,body:t.body??null,target_user_id:t.targetUserId??null,created_at:r,metadata:t.metadata??null}).run(),this.enforceCap(e,t.workspaceId),{id:n}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create notification",n)}finally{e.close();}}enforceCap(t,e){let o=(t.db.select({count:sql`count(*)`}).from(w).where(eq(w.workspace_id,e)).get()?.count??0)-this.cap;if(o<=0)return;let l=t.db.select({id:w.id}).from(w).innerJoin(v,eq(v.notification_id,w.id)).where(eq(w.workspace_id,e)).groupBy(w.id).orderBy(asc(w.created_at)).limit(o).all().map(u=>u.id);l.length!==0&&(t.db.delete(v).where(inArray(v.notification_id,l)).run(),t.db.delete(w).where(inArray(w.id,l)).run());}list(t){if(!this.dbExists())return [];let e=t.limit??Me,n=this.openHandle(false);try{return n.db.select({id:w.id,workspace_id:w.workspace_id,agent_id:w.agent_id,task_id:w.task_id,thread_id:w.thread_id,source:w.source,level:w.level,title:w.title,body:w.body,target_user_id:w.target_user_id,created_at:w.created_at,metadata:w.metadata,read_at:v.read_at}).from(w).leftJoin(v,and(eq(v.notification_id,w.id),eq(v.user_id,t.userId))).where(eq(w.workspace_id,t.workspaceId)).orderBy(desc(w.created_at)).limit(e).all().map(o=>({...o,read_at:o.read_at??null,read:o.read_at!=null}))}catch(r){throw new d("DB_ERROR","Failed to list notifications",r)}finally{n.close();}}unreadCount(t){if(!this.dbExists())return 0;let e=this.openHandle(false);try{return e.db.select({count:sql`count(*)`}).from(w).leftJoin(v,and(eq(v.notification_id,w.id),eq(v.user_id,t.userId))).where(and(eq(w.workspace_id,t.workspaceId),isNull(v.notification_id))).get()?.count??0}catch(n){throw new d("DB_ERROR","Failed to count unread notifications",n)}finally{e.close();}}markRead(t){let e=this.openHandle(true);try{if(!e.db.select({id:w.id}).from(w).where(and(eq(w.id,t.notificationId),eq(w.workspace_id,t.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return e.db.insert(v).values({notification_id:t.notificationId,user_id:t.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark notification read",n)}finally{e.close();}}markAllRead(t){let e=this.openHandle(true);try{let n=e.db.select({id:w.id}).from(w).leftJoin(v,and(eq(v.notification_id,w.id),eq(v.user_id,t.userId))).where(and(eq(w.workspace_id,t.workspaceId),isNull(v.notification_id))).all();if(n.length===0)return 0;let r=new Date().toISOString();return e.db.transaction(o=>{for(let i of n)o.insert(v).values({notification_id:i.id,user_id:t.userId,read_at:r}).onConflictDoNothing().run();}),n.length}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark all notifications read",n)}finally{e.close();}}};var qe=50,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=g(e);if(t)try{D(n.db,e);}catch(r){throw n.close(),r}return n}create(t){let e=this.openHandle(true);try{let n=new Date().toISOString(),r=[],o=t.map(i=>{let l=Ct("sug");return r.push(l),{id:l,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:n,updated_at:n}});return o.length>0&&e.db.insert(C).values(o).run(),{ids:r}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create agent suggestions",n)}finally{e.close();}}findLatestSet(t,e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=n.db.select({task_id:C.task_id}).from(C).where(and(eq(C.workspace_id,t),eq(C.agent_id,e))).orderBy(desc(C.created_at)).limit(1).get();if(!r)return [];let o=r.task_id===null?isNull(C.task_id):eq(C.task_id,r.task_id);return n.db.select().from(C).where(and(eq(C.workspace_id,t),eq(C.agent_id,e),o)).orderBy(asc(C.created_at)).all()}catch(r){throw new d("DB_ERROR","Failed to find latest agent suggestion set",r)}finally{n.close();}}updateStatus(t,e,n){let r=this.openHandle(true);try{let o={status:e,updated_at:new Date().toISOString()};return n!==void 0&&(o.applied_commit_sha=n),r.db.update(C).set(o).where(eq(C.id,t)).run().changes>0}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update agent suggestion status",o)}finally{r.close();}}listByAgent(t,e,n=qe){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(C).where(and(eq(C.workspace_id,t),eq(C.agent_id,e))).orderBy(desc(C.created_at)).limit(n).all()}catch(o){throw new d("DB_ERROR","Failed to list agent suggestions",o)}finally{r.close();}}};export{Vt as AgentSuggestionRepository,x as BaseSqliteRepository,qe as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,He as DEFAULT_NOTIFICATION_CAP,Me as DEFAULT_NOTIFICATION_LIST_LIMIT,Jt as NotificationRepository,d as RepositoryError,Gt as RequestLogRepository,jt as SpanRepository,Ft as TaskRepository,Kt as ThreadBoxRepository,qt as ThreadRepository,Wt as ToolCallRepository,Yt as UsageLimitSnapshotRepository,Xt as UsageReportRepository,Ht as WorkspaceRepository,Oe as calcBucketStart,g as openDrizzleDb,Un as pushSchema,ut as runMigrations,D as runMigrationsOnce,s as tasks};
|
package/dist/index.browser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {load}from'js-yaml';import {z as z$1}from'zod';var m=class extends Error{constructor(e,r){let
|
|
2
|
-
`);y=O.pop();for(let M of O){let h=M.trim();if(!h||!h.startsWith("data: "))continue;let
|
|
1
|
+
import {load}from'js-yaml';import {z as z$1}from'zod';var m=class extends Error{constructor(e,r){let o=r.length>0?` Available: ${r.join(", ")}`:"";super(`Agent not found: "${e}".${o}`),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,o=e.find(n=>n.id===r);if(o)return o;let i=D[r];if(i)return i;throw new m(s,e.map(n=>n.id))}var l=class extends Error{constructor(r,o,i){super(r);this.providerStr=o;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 l(`Invalid provider format: "${s}". Expected namespace/id (e.g., api/webllm)`,s);let[r,o]=e,i=I.get(r);if(i)return i(o,s);throw new l(`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(o=>[o.id,o])),this._config=r;}static async fromConfig(e,r){let o=new s(e.agents??[],e),i=e.agents??[],n=a=>Array.isArray(a.provider)?a.provider[0]:a.provider,d=i.filter(a=>n(a)==="api/webllm"),c=i.filter(a=>n(a)==="api/openrouter");if(d.length>0&&await o._initWebLLM(d,r?.onProgress),c.length>0){if(!r?.openrouterApiKey)throw new Error("openrouterApiKey is required when using api/openrouter provider");o._initOpenRouter(c,r.openrouterApiKey);}return o._apiProviders.size>0&&P("api",(a,g)=>{let p=o._apiProviders.get(a);if(!p)throw new l(`Unknown api provider: ${a}`,g);return p}),o}async _initWebLLM(e,r){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not available. Chrome 113+ or Edge 113+ required.");let o=await j("https://esm.run/@mlc-ai/web-llm"),i=e[0]?.inline?.model??"gemma-2-2b-it-q4f16_1-MLC",n=await o.CreateMLCEngine(i,{initProgressCallback:r?c=>r(c):void 0}),d=[];this._apiProviders.set("webllm",{async query(c,a){let g=[];a?.systemPrompt&&g.push({role:"system",content:a.systemPrompt}),g.push(...d),g.push({role:"user",content:c});let p="",u=await n.chat.completions.create({messages:g,stream:true,temperature:.7,max_tokens:4096});for await(let y of u){let v=y.choices?.[0]?.delta?.content??"";p+=v,a?.onOutput&&a.onOutput(p,"stdout");}return d.push({role:"user",content:c}),d.push({role:"assistant",content:p}),p},async execute(c,a){return this.query(c,a)}});}_initOpenRouter(e,r){let o=e[0]?.inline?.model??"google/gemma-2-2b-it",i=[];this._apiProviders.set("openrouter",{async query(n,d){let c=[];d?.systemPrompt&&c.push({role:"system",content:d.systemPrompt}),c.push(...i),c.push({role:"user",content:n});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:d?.model||o,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(),p=new TextDecoder,u="",y="";for(;;){let{done:v,value:T}=await g.read();if(v)break;y+=p.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 b=h.slice(6);if(b!=="[DONE]")try{let k=JSON.parse(b).choices?.[0]?.delta?.content??"";u+=k,k&&d?.onOutput&&d.onOutput(u,"stdout");}catch{}}}return i.push({role:"user",content:n}),i.push({role:"assistant",content:u}),u},async execute(n,d){return this.query(n,d)}});}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,o){let i=Date.now(),n;try{n=w(e,Array.from(this._agents.values()));}catch(p){if(p instanceof m)return {ok:false,data:"",error:{code:"AGENT_NOT_FOUND",message:p.message},meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:Date.now()-i}};throw p}let d=Array.isArray(n.provider)?n.provider[0]??"api/default":n.provider,c=o?.provider??d,a=o?.model??n.inline?.model,g;try{g=x(c);}catch(p){return {ok:false,data:"",error:{code:"PROVIDER_ERROR",message:p.message},meta:{agentId:n.id,provider:c,model:a,durationMs:Date.now()-i}}}try{return {ok:!0,data:await g.query(r,{model:a,context:o?.context,systemPrompt:n.inline?.system_prompt??n.inline?.prompt,onOutput:o?.onOutput?u=>o.onOutput(u):void 0}),meta:{agentId:n.id,provider:c,model:a,durationMs:Date.now()-i}}}catch(p){return {ok:false,data:"",error:{code:"QUERY_FAILED",message:p.message},meta:{agentId:n.id,provider:c,model:a,durationMs:Date.now()-i}}}}async execute(e,r,o){let i=Date.now(),n;try{n=w(e,Array.from(this._agents.values()));}catch(p){if(p instanceof m)return {ok:false,data:"",error:{code:"AGENT_NOT_FOUND",message:p.message},meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:Date.now()-i}};throw p}let d=Array.isArray(n.provider)?n.provider[0]??"api/default":n.provider,c=o?.provider??d,a=o?.model??n.inline?.model,g;try{g=x(c);}catch(p){return {ok:false,data:"",error:{code:"PROVIDER_ERROR",message:p.message},meta:{agentId:n.id,provider:c,model:a,durationMs:Date.now()-i}}}try{return {ok:!0,data:await g.execute(r,{model:a,context:o?.context,systemPrompt:n.inline?.system_prompt??n.inline?.prompt}),meta:{agentId:n.id,provider:c,model:a,durationMs:Date.now()-i}}}catch(p){return {ok:false,data:"",error:{code:"EXECUTE_FAILED",message:p.message},meta:{agentId:n.id,provider:c,model:a,durationMs:Date.now()-i}}}}};var F=z$1.object({model:z$1.string().optional(),system_prompt:z$1.string().optional(),prompt:z$1.string().optional(),layout:z$1.union([z$1.string(),z$1.object({id:z$1.string(),props:z$1.record(z$1.unknown()).optional()}),z$1.object({props:z$1.record(z$1.unknown())}),z$1.object({template:z$1.string()})]).optional()}).catchall(z$1.unknown()),U=z$1.object({include:z$1.array(z$1.string()).optional()}).optional(),N=z$1.object({id:z$1.string(),name:z$1.string().optional(),role:z$1.string().optional(),team:z$1.string().optional(),provider:z$1.union([z$1.string(),z$1.array(z$1.string())]),working_directory:z$1.string().optional(),description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),inline:F.optional(),skills:U}).catchall(z$1.unknown()),L=z$1.object({bin_resolution:z$1.enum(["global_first","local_first"]).optional()}).catchall(z$1.unknown()),_=z$1.object({agents:z$1.array(N).optional(),hooks:z$1.array(z$1.unknown()).optional(),settings:L.optional(),skills:z$1.unknown().optional(),layouts:z$1.record(z$1.unknown()).optional(),documents:z$1.record(z$1.unknown()).optional()}).catchall(z$1.unknown());var f=class extends Error{constructor(r,o){super(r);this.cause=o;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=$(e),o=_.safeParse(r);if(!o.success)throw new f(`Config validation error: ${o.error.message}`);return o.data}function $(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,o=Object.entries(r).map(([i,n])=>({id:i,...n&&typeof n=="object"?n:{}}));return {...e,agents:o}}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),o=this.store.get(r);if(o===void 0)throw new Error(`BrowserFsAdapter: file not found: ${e}`);return o}async exists(e){return this.store.has(this.toKey(e))}resolvePath(...e){let r=e.map(d=>d.replace(/\\/g,"/")).join("/").replace(/\/+/g,"/"),o=r.split("/"),i=[];for(let d of o)d==="."||d===""||(d===".."?i.pop():i.push(d));let n=i.join("/");return r.startsWith("/")?`/${n}`:n}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(/\/$/,""),o=this.toKey(r+"/"),i=[];for(let n of this.store.keys())if(n.startsWith(o)){let c=n.slice(o.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 B(s){let e=s.indexOf("/");return e===-1?s:s.slice(e+1)}function R(s){let e=B(s),r=C.indexOf(e);return r===-1?C.length:r}function W(s,e){return R(s)-R(e)}var z=new Set(["claude","copilot","codex","opencode"]);function q(s){if(!s)return "";if(s.startsWith("acp/")){let e=s.slice(4);if(z.has(e))return `cli/${e}`}return s}export{E as BrowserFsAdapter,f as ConfigLoadError,A as Crewx,C as PROVIDER_ORDER,l as ProviderError,W as compareProviders,x as createProvider,q as normalizeProviderId,Q as parseYamlContent,R as providerRank,P as registerProviderFactory};
|