@crewx/sdk 0.8.6-rc.8 → 0.8.6
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 +1 -1
- package/dist/esm/plugins/index.js +17 -21
- package/dist/esm/repository/index.js +15 -19
- package/dist/index.js +1 -1
- package/dist/migrations/0002_normalize_task_names.sql +13 -0
- package/dist/migrations/meta/0002_snapshot.json +1077 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.js +17 -21
- package/dist/repository/index.js +15 -19
- package/dist/repository/task.repository.d.ts +0 -3
- package/dist/schema/tasks.d.ts +0 -38
- package/package.json +1 -1
|
@@ -1,40 +1,37 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as V from'path';import V__default,{join,dirname,basename}from'path';import {fileURLToPath}from'url';import vt,{existsSync,mkdirSync}from'fs';import Jt from'os';import {sql,and,eq,ne as ne$1,isNull,desc,isNotNull,or,like,asc,inArray,gte,lt}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique,getTableConfig}from'drizzle-orm/sqlite-core';import {randomUUID,createHash}from'crypto';var tt=(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 Gt=()=>fileURLToPath(import.meta.url),Kt=()=>V__default.dirname(Gt()),b=Kt();var R=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Jt.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 m(a){let t=tt("better-sqlite3"),{drizzle:e}=tt("drizzle-orm/better-sqlite3"),n=new t(a);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:e(n),runRaw:(s,r=[])=>n.prepare(s).run(...r),close:()=>n.close()}}var xt=new Set,te={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 ee(a,t){return (a.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function ne(a,t){if(t>0||!ee(a,"tasks"))return;let e=a.all("PRAGMA table_info(tasks)"),n=new Set(e.map(s=>s.name));for(let[s,r]of Object.entries(te))n.has(s)||a.run(`ALTER TABLE tasks ADD COLUMN ${s} ${r}`);}function Y(a){let{migrate:t}=tt("drizzle-orm/better-sqlite3/migrator"),{sql:e}=tt("drizzle-orm"),n=[V__default.join(b,"../migrations"),V__default.join(b,"migrations"),V__default.join(b,"../../../../drizzle/migrations"),V__default.join(process.cwd(),"drizzle/migrations")],s=n.find(_=>existsSync(V__default.join(_,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${n.join(`
|
|
3
|
-
`)}`);let r=
|
|
3
|
+
`)}`);let r=a.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ne(a,i),t(a,{migrationsFolder:s});let c=(a.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let _=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${_} (${c} migration${c>1?"s":""} applied).`);}}function T(a,t){xt.has(t)||(Y(a),xt.add(t));}var u=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},a=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(a.agent_id),idx_tasks_status:index("idx_tasks_status").on(a.status),idx_tasks_started_at:index("idx_tasks_started_at").on(a.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(a.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(a.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(a.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(a.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(a.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(a.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(a.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(a.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(a.workspace_id,a.started_at)}));var p=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>u.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)},a=>({idx_threads_updated_at:index("idx_threads_updated_at").on(a.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(a.workspace_id)}));var F=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>F.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 v=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},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 A=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>p.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},a=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(a.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(a.thread_id,a.seq),uniq_thread_boxes_thread_seq:unique().on(a.thread_id,a.seq)}));var K=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},a=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(a.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(a.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(a.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(a.partition_key)}));function pt(a){let t=V.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 At(a){let t=pt(a);return createHash("sha256").update(t).digest("hex")}function st(a){return a.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var ft=class extends R{dbRoot;constructor(t={}){super(),this.dbRoot=t.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=m(e);if(t)try{Y(n.db);}catch(s){throw n.close(),s}return n}resolveSlug(t,e,n){let s=st(basename(n)),i=`${st(basename(dirname(n)))}-${s}`,l=[s,i];try{let c=_=>t.select({id:u.id}).from(u).where(and(eq(u.slug,_),ne$1(u.id,e))).limit(1).all().length>0;for(let _ of l)if(!c(_))return _;for(let _=2;_<1e3;_+=1){let h=`${i}-${_}`;if(!c(h))return h}}catch{}return s}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:u.id,slug:u.slug}).from(u).all(),n=0;for(let s of e)if(s.slug.includes("/")){let r=st(s.slug.replace(/\//g,"-"));t.db.update(u).set({slug:r,updated_at:new Date().toISOString()}).where(eq(u.id,s.id)).run(),n+=1;}return {updated:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to normalize legacy slugs",e)}finally{t.close();}}ensureRow(t,e){let{id:n,slug:s,name:r,workspacePath:i}=e,l=new Date().toISOString();t.insert(u).values({id:n,slug:s,name:r,workspace_path:i,is_active:1,created_at:l,updated_at:l}).onConflictDoNothing().run(),t.update(u).set({workspace_path:i,updated_at:l}).where(and(eq(u.id,n),isNull(u.workspace_path))).run();}registerWorkspace(t){let e=pt(t),n=this.openHandle(true);try{let s=At(e),r=basename(e),i=this.resolveSlug(n.db,s,e);return this.ensureRow(n.db,{id:s,slug:i,name:r,workspacePath:e}),{id:s,slug:i}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to register workspace",s)}finally{n.close();}}listProjects(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=t.isActive!==void 0?eq(u.is_active,t.isActive?1:0):void 0,s=e.db.select({count:sql`count(*)`}).from(u).where(n).get();return {rows:e.db.select().from(u).where(n).orderBy(desc(u.updated_at)).limit(t.limit).offset(t.offset).all(),total:s?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{e.close();}}findById(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(u).where(eq(u.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{e.close();}}findAgentsByProject(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${t} AND agent_id IS NOT NULL ORDER BY agent_id`).map(s=>s.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{e.close();}}findThreadsByProject(t,e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let s=n.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${t}`);return {rows:n.db.all(sql`SELECT t.*,
|
|
4
4
|
(SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
|
|
5
5
|
FROM threads t
|
|
6
6
|
WHERE t.workspace_id = ${t}
|
|
7
7
|
ORDER BY t.updated_at DESC
|
|
8
|
-
LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new
|
|
8
|
+
LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new d("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(u).where(eq(u.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?and(eq(u.slug,t),ne$1(u.id,e)):eq(u.slug,t);return !!n.db.select({id:u.id}).from(u).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let i=new Date().toISOString();r.db.insert(u).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:i,updated_at:i}).run();let l=r.db.select().from(u).where(eq(u.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{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(u).where(eq(u.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:u.id,workspace_path:u.workspace_path}).from(u).where(and(eq(u.is_active,1),isNotNull(u.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))||(t.db.update(u).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(u.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(u).where(eq(u.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Lt=[u,o,p,F,v,A,K];function xe(){return V__default.join(Jt.homedir(),".crewx","crewx.db")}function De(a){if(!vt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return vt.copyFileSync(a,e),e}function qt(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Se(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 Te(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Se(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Oe(a,t){let e=t?.dbPath??xe(),n=t?.force??false,s=t?.dryRun??false,r=s?null:De(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let i=qt(a);s||Y(a);let l,c;s?(l=Lt.map(E=>getTableConfig(E).name).filter(E=>!i.has(E)),c=i):(c=qt(a),l=[...c].filter(w=>!i.has(w)));let _=[],h=[];for(let w of Lt){let E=getTableConfig(w),S=E.name;if(!c.has(S))continue;let L=a.all(`PRAGMA table_info("${S}")`),lt=new Set(L.map(B=>B.name)),ct=new Set(E.columns.map(B=>B.name));for(let B of E.columns)if(!lt.has(B.name)){if(!s){let Wt=Te(B);a.run(`ALTER TABLE "${S}" ADD COLUMN ${Wt}`);}_.push({table:S,column:B.name});}for(let B of L)ct.has(B.name)||h.push(`${S}.${B.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:_,warnings:h,backupPath:r}}var wt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
9
9
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
10
|
-
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof
|
|
10
|
+
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),s.update(o).set({logs:JSON.stringify(i)}).where(eq(o.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.status,"running")).orderBy(desc(o.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(o).orderBy(desc(o.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(o).where(eq(o.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:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.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(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=m(s);try{let i=e?eq(o.workspace_id,e):void 0,l=i?and(eq(o.id,t),i):eq(o.id,t),c=r.db.select().from(o).where(l).limit(1).get()??void 0;if(!c){let _=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),h=i?and(_,i):_;c=r.db.select().from(o).where(h).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new d("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),_=l.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of _)s.has(h.id)||(s.add(h.id),r.push(h));}catch(c){throw new d("DB_ERROR","Failed to find child tasks",c)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
11
11
|
SELECT
|
|
12
12
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
13
|
-
COALESCE(workspace_name, 'Unknown Workspace') AS workspace_name,
|
|
14
13
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
15
14
|
COALESCE(SUM(output_tokens), 0) AS output_tokens,
|
|
16
15
|
COALESCE(SUM(cost_usd), 0) AS cost_usd,
|
|
17
16
|
COUNT(*) AS task_count
|
|
18
17
|
FROM tasks
|
|
19
18
|
WHERE workspace_id = ${t}
|
|
20
|
-
GROUP BY workspace_id
|
|
19
|
+
GROUP BY workspace_id
|
|
21
20
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
22
21
|
`:sql`
|
|
23
22
|
SELECT
|
|
24
23
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
25
|
-
COALESCE(workspace_name, 'Unknown Workspace') AS workspace_name,
|
|
26
24
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
27
25
|
COALESCE(SUM(output_tokens), 0) AS output_tokens,
|
|
28
26
|
COALESCE(SUM(cost_usd), 0) AS cost_usd,
|
|
29
27
|
COUNT(*) AS task_count
|
|
30
28
|
FROM tasks
|
|
31
|
-
GROUP BY workspace_id
|
|
29
|
+
GROUP BY workspace_id
|
|
32
30
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
33
|
-
`)}catch(n){throw new
|
|
31
|
+
`)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{e.close();}}getThreadTokenUsage(t,e){let n=this.resolveDbPaths(),s=new Set,r=0,i=0,l=0;for(let c of n){if(!existsSync(c))continue;let _=m(c);try{let h=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),w=e?and(h,eq(o.workspace_id,e)):h,E=_.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(w).all();for(let S of E)s.has(S.id)||(s.add(S.id),r+=S.input_tokens??0,i+=S.output_tokens??0,l+=S.cost_usd??0);}catch(h){throw new d("DB_ERROR","Failed to get thread token usage",h)}finally{_.close();}}return {inputTokens:r,outputTokens:i,costUsd:l}}findTasksByThread(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),_=e?and(c,eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(asc(o.started_at)).all();for(let w of h)s.has(w.id)||(s.add(w.id),r.push(w));}catch(c){throw new d("DB_ERROR","Failed to find tasks by thread",c)}finally{l.close();}}return r}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let e=this.openHandle(false);try{let n=[];t.workspaceId&&n.push(eq(o.workspace_id,t.workspaceId));let s=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;s&&n.push(inArray(o.agent_id,s));let r=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;r&&n.push(inArray(o.status,r));let i=t.q??t.search;i&&n.push(like(o.prompt,`%${i}%`)),t.from&&n.push(gte(o.started_at,t.from)),t.to&&n.push(lt(o.started_at,t.to));let l=n.length>0?and(...n):void 0,c=e.db.select({count:sql`count(*)`}).from(o).where(l).get(),_=(t.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:e.db.select().from(o).where(l).orderBy(_).limit(t.limit).offset(t.offset).all(),total:c?.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 s=this.openHandle(false);try{return s.db.all(n?sql`
|
|
34
32
|
SELECT
|
|
35
33
|
t.agent_id,
|
|
36
34
|
t.workspace_id,
|
|
37
|
-
t.workspace_name,
|
|
38
35
|
COUNT(*) AS total_tasks,
|
|
39
36
|
COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
|
|
40
37
|
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
@@ -44,14 +41,13 @@ ${n.join(`
|
|
|
44
41
|
WHERE t.status IN ('completed', 'success')
|
|
45
42
|
AND t.started_at >= ${t}
|
|
46
43
|
AND t.started_at < ${e}
|
|
47
|
-
AND t.
|
|
48
|
-
GROUP BY t.agent_id, t.workspace_id
|
|
44
|
+
AND t.workspace_id = ${n}
|
|
45
|
+
GROUP BY t.agent_id, t.workspace_id
|
|
49
46
|
ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
|
|
50
47
|
`:sql`
|
|
51
48
|
SELECT
|
|
52
49
|
t.agent_id,
|
|
53
50
|
t.workspace_id,
|
|
54
|
-
t.workspace_name,
|
|
55
51
|
COUNT(*) AS total_tasks,
|
|
56
52
|
COALESCE(SUM(t.input_tokens), 0) AS input_tokens,
|
|
57
53
|
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
@@ -61,9 +57,9 @@ ${n.join(`
|
|
|
61
57
|
WHERE t.status IN ('completed', 'success')
|
|
62
58
|
AND t.started_at >= ${t}
|
|
63
59
|
AND t.started_at < ${e}
|
|
64
|
-
GROUP BY t.agent_id, t.workspace_id
|
|
60
|
+
GROUP BY t.agent_id, t.workspace_id
|
|
65
61
|
ORDER BY (COALESCE(SUM(t.input_tokens), 0) + COALESCE(SUM(t.output_tokens), 0)) DESC
|
|
66
|
-
`).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,
|
|
62
|
+
`).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd}))}catch(r){throw new d("DB_ERROR","Failed to get agent usage",r)}finally{s.close();}}getAgentUsageTrendRaw(t,e,n){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(n?sql`
|
|
67
63
|
SELECT
|
|
68
64
|
date(t.started_at) AS date,
|
|
69
65
|
t.agent_id,
|
|
@@ -75,7 +71,7 @@ ${n.join(`
|
|
|
75
71
|
WHERE t.status IN ('completed', 'success')
|
|
76
72
|
AND t.started_at >= ${t}
|
|
77
73
|
AND t.started_at < ${e}
|
|
78
|
-
AND t.
|
|
74
|
+
AND t.workspace_id = ${n}
|
|
79
75
|
GROUP BY date(t.started_at), t.agent_id
|
|
80
76
|
ORDER BY date(t.started_at) ASC
|
|
81
77
|
`:sql`
|
|
@@ -92,13 +88,13 @@ ${n.join(`
|
|
|
92
88
|
AND t.started_at < ${e}
|
|
93
89
|
GROUP BY date(t.started_at), t.agent_id
|
|
94
90
|
ORDER BY date(t.started_at) ASC
|
|
95
|
-
`).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}))}catch(r){throw new
|
|
91
|
+
`).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}))}catch(r){throw new d("DB_ERROR","Failed to get agent usage trend",r)}finally{s.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(o).where(and(eq(o.id,t),eq(o.workspace_id,e))).limit(1).get()??void 0}catch(s){throw new d("DB_ERROR","Failed to find task for stop",s)}finally{n.close();}}markTaskFailed(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString(),i=n?and(eq(o.id,t),eq(o.status,"running"),eq(o.workspace_id,n)):and(eq(o.id,t),eq(o.status,"running"));s.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to mark task failed",r)}finally{s.close();}}findTasksByPromptHint(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=e?and(like(o.prompt,`%${t}%`),eq(o.workspace_id,e)):like(o.prompt,`%${t}%`),_=l.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of _)s.has(h.id)||(s.add(h.id),r.push(h));}catch(c){throw new d("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{l.close();}}return r}};var kt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}validateWorkspaceId(t,e){return t.db.select({id:u.id}).from(u).where(eq(u.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),n=new Set,s=[];for(let r of e){if(!existsSync(r))continue;let i=m(r);try{let l=t?or(eq(p.workspace_id,t),isNull(p.workspace_id)):void 0,c=i.db.select().from(p).where(l).orderBy(desc(p.updated_at)).all();for(let _ of c)n.has(_.id)||(n.add(_.id),s.push(_));}catch(l){throw new d("DB_ERROR","Failed to find all threads",l)}finally{i.close();}}return s}findThreadById(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=m(s);try{let i=eq(p.id,t),l=e?and(i,or(eq(p.workspace_id,e),isNull(p.workspace_id))):i,c=r.db.select().from(p).where(l).limit(1).get()??void 0;if(c)return c}catch(i){throw new d("DB_ERROR","Failed to find thread by id",i)}finally{r.close();}}}threadExists(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=m(s);try{let i=eq(p.id,t),l=e?and(i,or(eq(p.workspace_id,e),isNull(p.workspace_id))):i;if(r.db.select({id:p.id}).from(p).where(l).limit(1).get())return !0}catch(i){throw new d("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let n=this.resolveDbPaths(),s=0,r=0,i=0,l=0,c=0,_=new Set;for(let h of n){if(!existsSync(h))continue;let w=m(h);try{let E=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),S=e?and(E,eq(o.workspace_id,e)):E,L=w.db.select({cnt:sql`count(*)`,total_input:sql`COALESCE(SUM(input_tokens), 0)`,total_output:sql`COALESCE(SUM(output_tokens), 0)`,total_cached:sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:sql`COALESCE(SUM(cost_usd), 0)`}).from(o).where(S).get();L&&(s+=L.cnt,r+=L.total_input,i+=L.total_output,l+=L.total_cached,c+=L.total_cost);let lt=w.db.all(sql`
|
|
96
92
|
SELECT DISTINCT agent_id FROM tasks
|
|
97
93
|
WHERE thread_id = ${t}
|
|
98
94
|
AND agent_id IS NOT NULL AND agent_id != ''
|
|
99
95
|
AND (parent_task_id IS NULL OR parent_task_id = '')
|
|
100
96
|
${e?sql`AND workspace_id = ${e}`:sql``}
|
|
101
|
-
`);for(let ct of lt)_.add(ct.agent_id);}catch(E){throw new
|
|
97
|
+
`);for(let ct of lt)_.add(ct.agent_id);}catch(E){throw new d("DB_ERROR","Failed to aggregate task stats",E)}finally{w.close();}}return {taskCount:s,inputTokens:r,outputTokens:i,cachedInputTokens:l,costUsd:c,agentIds:Array.from(_)}}findTopLevelTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=and(eq(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),_=e?and(c,eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(asc(o.started_at)).all();for(let w of h)s.has(w.id)||(s.add(w.id),r.push(w));}catch(c){throw new d("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}return r}findAllTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let l=m(i);try{let c=eq(o.thread_id,t),_=e?and(c,eq(o.workspace_id,e)):c,h=l.db.select().from(o).where(_).orderBy(asc(o.started_at)).all();for(let w of h)s.has(w.id)||(s.add(w.id),r.push(w));}catch(c){throw new d("DB_ERROR","Failed to find all tasks for thread",c)}finally{l.close();}}return r}findTaskById(t,e,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=m(r);try{let l=and(eq(o.id,e),eq(o.thread_id,t)),c=n?and(l,eq(o.workspace_id,n)):l,_=i.db.select().from(o).where(c).limit(1).get();if(!_)continue;let h=i.db.select().from(o).where(eq(o.parent_task_id,_.id)).orderBy(asc(o.started_at)).all();return {task:_,children:h}}catch(l){throw new d("DB_ERROR","Failed to find task by id",l)}finally{i.close();}}}batchFetchTasks(t,e){let n=new Map;if(t.length===0)return n;let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=m(r);try{let l=and(inArray(o.thread_id,t),or(isNull(o.parent_task_id),eq(o.parent_task_id,""))),c=e?and(l,eq(o.workspace_id,e)):l,_=i.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of _){let w=h.thread_id;n.has(w)||n.set(w,[]),n.get(w).push(h);}}catch(l){throw new d("DB_ERROR","Failed to batch fetch tasks",l)}finally{i.close();}}return n}updateThreadTitle(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=eq(p.id,t),i=n?and(r,or(eq(p.workspace_id,n),isNull(p.workspace_id))):r;if(!s.db.select({id:p.id}).from(p).where(i).limit(1).get())return;s.db.update(p).set({title:e,title_locked:1,updated_at:new Date().toISOString()}).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update thread title",r)}finally{s.close();}}upsertThread(t,e){let n=this.openHandle(true);try{let s=e.workspaceId?this.validateWorkspaceId(n,e.workspaceId):null,r=new Date().toISOString();if(n.db.select({id:p.id,message_count:p.message_count}).from(p).where(eq(p.id,t)).limit(1).get()){let l={updated_at:r};e.title!==void 0&&(l.title=e.title),e.titleLocked!==void 0&&(l.title_locked=e.titleLocked?1:0),n.db.update(p).set(l).where(eq(p.id,t)).run();}else n.db.insert(p).values({id:t,platform:e.platform,workspace_id:s,title:e.title??null,title_locked:e.titleLocked?1:0,message_count:0,created_at:r,updated_at:r}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to upsert thread",s)}finally{n.close();}}ensureThread(t,e,n){let s=this.openHandle(true);try{let r=n?this.validateWorkspaceId(s,n):null,i=s.db.select({id:p.id,platform:p.platform,workspace_id:p.workspace_id}).from(p).where(eq(p.id,t)).limit(1).get();if(i){r&&!i.workspace_id&&s.db.update(p).set({workspace_id:r}).where(eq(p.id,t)).run();return}let l=new Date().toISOString();s.db.insert(p).values({id:t,platform:e,workspace_id:r,message_count:0,created_at:l,updated_at:l}).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to ensure thread",r)}finally{s.close();}}saveUserMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.run(sql`
|
|
102
98
|
UPDATE threads
|
|
103
99
|
SET first_message = COALESCE(first_message, ${e}),
|
|
104
100
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${e}, 1, 60) ELSE title END,
|
|
@@ -106,4 +102,4 @@ ${n.join(`
|
|
|
106
102
|
message_count = message_count + 1,
|
|
107
103
|
updated_at = ${r}
|
|
108
104
|
WHERE id = ${t}
|
|
109
|
-
`);}catch(r){throw r instanceof
|
|
105
|
+
`);}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save user message",r)}finally{s.close();}}saveAssistantMessage(t,e,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r=new Date().toISOString();s.db.update(p).set({last_message:e,updated_at:r}).where(eq(p.id,t)).run();}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to save assistant message",r)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let n=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),n.db.update(p).set(s).where(eq(p.id,t)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread",s)}finally{n.close();}}};var bt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}insertSpan(t){let e=this.openHandle(true);try{e.db.insert(F).values(t).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{e.close();}}findByTaskId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(F).where(eq(F.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(F).where(eq(F.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 yt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}insertToolCall(t){let e=this.openHandle(true);try{e.db.insert(v).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(v).where(eq(v.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:v.tool_name,count:sql`count(*)`}).from(v).where(eq(v.task_id,t)).groupBy(v.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 Rt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}ensureThreadExists(t,e){if(!t.db.select({id:p.id}).from(p).where(eq(p.id,e)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${e}`)}findByThreadId(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return this.ensureThreadExists(e,t),e.db.select().from(A).where(eq(A.thread_id,t)).orderBy(asc(A.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(A).where(and(eq(A.id,e),eq(A.thread_id,t))).limit(1).get()??void 0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to find box by id",s)}finally{n.close();}}insert(t){let e=this.openHandle(true);try{this.ensureThreadExists(e,t.threadId);try{e.db.insert(A).values({id:t.id,thread_id:t.threadId,seq:t.seq,first_task_id:t.first_task_id,mid_task_id:t.mid_task_id,last_task_id:t.last_task_id,task_count:t.task_count,summary:t.summary??null,source_tokens:t.source_tokens,summary_tokens:t.summary_tokens??null,created_at:t.created_at}).run();}catch(s){throw s instanceof Error&&/UNIQUE constraint failed/i.test(s.message)?new d("CONFLICT",`Duplicate seq ${String(t.seq)} for thread ${t.threadId}`,s):s}let n=e.db.select().from(A).where(eq(A.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 Et=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=m(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}bulkInsert(t){if(t.length===0)return;let e=this.openHandle(true);try{let n=new Date().toISOString();e.db.transaction(s=>{for(let r of t)s.insert(K).values({id:randomUUID(),path:r.path,method:r.method,status_code:r.statusCode,duration_ms:r.durationMs,ip:r.ip??null,request_headers:r.requestHeaders??null,response_headers:r.responseHeaders??null,request_body:r.requestBody??null,response_body:r.responseBody??null,query:r.query??null,user_id:r.userId??null,project_id:r.projectId??null,partition_key:r.partitionKey??"default",timestamp:n,metadata:r.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{e.close();}}findRecent(t=100){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(K).orderBy(desc(K.timestamp)).limit(t).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{e.close();}}};export{R as BaseSqliteRepository,d as RepositoryError,Et as RequestLogRepository,bt as SpanRepository,wt as TaskRepository,Rt as ThreadBoxRepository,kt as ThreadRepository,yt as ToolCallRepository,ft as WorkspaceRepository,m as openDrizzleDb,Oe as pushSchema,Y as runMigrations,T as runMigrationsOnce};
|
package/dist/index.js
CHANGED
|
@@ -29,7 +29,7 @@ ${e}`:e}async runProcess(e,t,r){try{return await gr(this.adapter.command,e,this.
|
|
|
29
29
|
`);this.stderrBuffer=w.pop()??"";for(let h of w)h.trim()&&this.options.onStderr?.(h);}),this.proc=n;let s=new WritableStream({write:g=>new Promise((f,w)=>{n.stdin.write(g,h=>{h?w(h):f();});}),close:()=>{n.stdin.end();}}),i=new ReadableStream({start:g=>{n.stdout.on("data",f=>{g.enqueue(new Uint8Array(f));}),n.stdout.on("end",()=>{g.close();}),n.stdout.on("error",f=>{g.error(f);});}}),a=sdk.ndJsonStream(s,i),d=this,u=new sdk.ClientSideConnection(g=>({requestPermission:async f=>{if(d.options.configOptions?.allow_all!==void 0){let w=f.options;if(Array.isArray(w)&&w.length>0)return {outcome:{outcome:"selected",optionId:(w.find(k=>k.kind==="allow_once")??w.find(k=>k.kind?.startsWith("allow_"))??w[0]).optionId}}}return {outcome:{outcome:"cancelled"}}},sessionUpdate:async f=>{d.pendingUpdateCallback?.(f);}}),a);this.sdkConnection=u;let c=new Promise((g,f)=>{n.on("error",w=>{if(w.code==="ENOENT"){let k=t.command==="npx"&&t.args.length>0?`@agentclientprotocol/${t.args[0]}`:t.command;f(new exports.ProviderError(`ACP command "${t.command}" not found. Is the ACP adapter installed? Try: npm install -g ${k}`,"acp"));}else f(new exports.ProviderError(`ACP spawn error: ${w.message}`,"acp"));});}),m=this.doInitialize(u,e),p=new Promise((g,f)=>{setTimeout(()=>{f(new exports.AcpProtocolError(`ACP connect timeout after ${jr}ms. The ACP adapter may not be installed or may require interactive setup.`));},jr).unref();});await Promise.race([m,p,c]);}async doInitialize(e,t){let r=await e.initialize({protocolVersion:1,clientCapabilities:{auth:{}},clientInfo:{name:t?.name??"crewx-sdk",version:t?.version??"0.8.4"}});this._initResponse=r,this.authMethods=r.authMethods??[];}async newSession(e){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");try{return await this.newSessionWithTimeout(e)}catch(t){if(!this.isAuthError(t))throw t;return await this.tryAuthenticate(),this.newSessionWithTimeout(e)}}async newSessionWithTimeout(e){return (await this.newSessionRawTimeout(e)).sessionId}async newSessionRaw(e){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");try{return await this.newSessionRawTimeout(e)}catch(t){if(!this.isAuthError(t))throw t;return await this.tryAuthenticate(),this.newSessionRawTimeout(e)}}async newSessionRawTimeout(e){let t=this.sdkConnection.newSession(e),r=new Promise((n,s)=>{setTimeout(()=>{s(new exports.AcpProtocolError(`ACP session/new timeout after ${Dr}ms`));},Dr).unref();});return Promise.race([t,r])}isAuthError(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code===Io}async tryAuthenticate(){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected.","acp");let e=this.authMethods.find(r=>r.type==="env_var"&&this.hasEnvVarsFor(r));if(e){await this.sdkConnection.authenticate({methodId:e.id});return}let t=this.authMethods.map(r=>`${r.id} (${r.type??"agent"})`).join(", ");if(this.authMethods.length>0){let r=this.authMethods.filter(n=>n.type==="env_var");if(r.length>0){let n=r.flatMap(s=>(s.vars??[]).filter(i=>!i.optional&&!process.env[i.name]).map(i=>i.name));throw new exports.AcpProtocolError(`ACP authentication required. Missing environment variables: ${n.join(", ")}. Set them in your shell or crewx.yaml env block.`)}throw new exports.AcpProtocolError(`ACP authentication required but no supported method found. Available methods: ${t}. CrewX currently supports env_var authentication only.`)}throw new exports.AcpProtocolError("ACP agent requires authentication but advertised no auth methods.")}hasEnvVarsFor(e){return !e.vars||e.vars.length===0?true:e.vars.filter(t=>!t.optional).every(t=>!!process.env[t.name])}async setModel(e,t){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.unstable_setSessionModel({sessionId:e,modelId:t});}async setMode(e,t){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.setSessionMode({sessionId:e,modeId:t});}async setConfigOption(e,t,r){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.setSessionConfigOption({sessionId:e,configId:t,value:r});}async prompt(e,t,r,n){if(!this.sdkConnection||!this.proc)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");this.pendingUpdateCallback=r??null;let s=this.sdkConnection,i=this.proc,a=n??36e5,d=s.prompt({sessionId:e,prompt:t}),u=new Promise((m,p)=>{setTimeout(()=>{s.cancel({sessionId:e}).catch(()=>{}),p(new Ce(`ACP prompt timeout after ${a}ms`,"acp"));},a).unref();}),c=new Promise((m,p)=>{let g=f=>{f!==0&&p(new exports.ProviderError(`ACP process exited unexpectedly (code=${String(f)}): ${this.collectedStderr.slice(0,500)}`,"acp"));};i.once("close",g),d.then(()=>i.off("close",g)).catch(()=>i.off("close",g));});try{return await Promise.race([d,u,c])}finally{this.pendingUpdateCallback=null;}}async dispose(){if(this.disposed)return;this.disposed=true,this.pendingUpdateCallback=null,this.sdkConnection=null;let e=this.proc;e&&(this.proc=null,this.stderrBuffer.trim()&&(this.options.onStderr?.(this.stderrBuffer),this.stderrBuffer=""),await new Promise(t=>{let r=()=>{clearTimeout(n),t();};e.once("close",r),e.once("error",r);try{e.kill("SIGTERM");}catch{r();return}let n=setTimeout(()=>{try{e.kill("SIGKILL");}catch{}},Oo);}));}get isConnected(){return !this.disposed&&this.sdkConnection!==null&&this.proc!==null}};});function Ur(o,e){if(o!=null&&typeof o=="object"){let t=o;if(typeof t.command=="string")return t.command;if(typeof t.file_path=="string")return t.file_path;if(typeof t.filePath=="string")return t.filePath;if(typeof t.path=="string")return t.path;if(typeof t.query=="string")return t.query;if(typeof t.pattern=="string")return t.pattern;if(typeof t.url=="string")return t.url;if(Object.keys(t).length>0)return JSON.stringify(t)}if(e&&e.length>0)return e.map(t=>t.path).join(", ")}var Mo;exports.AcpProviderRuntime=void 0;var Ht=O(()=>{l();se();rt();Mo={read:"Read",edit:"Edit",delete:"Delete",move:"Move",search:"Search",execute:"Bash",think:"Think",fetch:"WebFetch",switch_mode:"SwitchMode"};exports.AcpProviderRuntime=class{constructor(e,t,r){this.adapter=t;}adapter;async query(e,t){return this.runPrompt(e,t)}async execute(e,t){return this.runPrompt(e,t)}async dispose(){}async runPrompt(e,t){let{command:r,args:n}=this.adapter.spawn;t?.onCommand?.(`${r} ${n.join(" ")}`);let s=new exports.AcpConnection({spawn:this.adapter.spawn,env:t?.env,cwd:t?.cwd,timeoutMs:t?.timeoutMs,onPid:t?.onPid,onStderr:i=>t?.onOutput?.(i,"stderr"),configOptions:t?.configOptions});try{await s.connect(this.adapter.clientInfo);let i=this.adapter.buildSessionParams({cwd:t?.cwd,env:t?.env,model:t?.model,systemPrompt:t?.systemPrompt}),a=await s.newSession(i);await this.applySessionOptions(s,a,t);let d=this.composePrompt(e,t),u=[],c=await s.prompt(a,d,m=>this.handleUpdate(m,t,u),t?.timeoutMs);return this.handleUsage(c,t),u.join("")}finally{await s.dispose().catch(()=>{});}}async applySessionOptions(e,t,r){if(r?.model){let n=this.adapter.buildEffortAction?.(r.effort??"",r.model);n?.type==="set_model"?await e.setModel(t,n.modelId):await e.setModel(t,r.model);}if(r?.mode){let n=this.adapter.resolveMode?.(r.mode)??r.mode;if(n)try{await e.setMode(t,n);}catch(s){console.warn(`[acp] setMode(${n}) failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.effort){let n=this.adapter.buildEffortAction?.(r.effort,r.model);if(n&&n.type==="set_config_option")try{await e.setConfigOption(t,n.configId,n.value);}catch(s){console.warn(`[acp] setConfigOption(${n.configId}) effort failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.configOptions)for(let[n,s]of Object.entries(r.configOptions))try{await e.setConfigOption(t,n,s);}catch(i){console.warn(`[acp] setConfigOption(${n}) failed, retrying: ${i instanceof Error?i.message:String(i)}`);try{await new Promise(a=>setTimeout(a,500)),await e.setConfigOption(t,n,s);}catch(a){console.warn(`[acp] setConfigOption(${n}) retry failed: ${a instanceof Error?a.message:String(a)}`);}}}composePrompt(e,t){let r=[];return t?.systemPrompt?.trim()&&(r.push(t.systemPrompt),r.push("---")),t?.context&&(r.push(t.context),r.push("---")),r.push(e),[{type:"text",text:r.join(`
|
|
30
30
|
|
|
31
31
|
`)}]}handleUpdate(e,t,r){let n=e.update;if(n.sessionUpdate==="agent_message_chunk"){let s=null;this.adapter.extractTextFromUpdate?s=this.adapter.extractTextFromUpdate(e):s=Dt(e),s!==null&&(r.push(s),t?.onOutput?.(s,"stdout"));}else if(n.sessionUpdate==="tool_call"){let s=new Date().toISOString(),i=n,a={title:i.title??"",kind:i.kind,rawInput:i.rawInput,rawOutput:i.rawOutput,locations:i.locations,_meta:i._meta},d=this.resolveToolCall(a),u={timestamp:s,type:"tool_use",toolUseId:i.toolCallId,toolName:d.toolName,toolInput:d.toolInput};t?.onTaskLog?.([u]);}else if(n.sessionUpdate==="tool_call_update"){let s=new Date().toISOString(),i=n;if(i.status==="completed"||i.status==="failed"){let d=this.extractResultPreview(i.rawOutput),u={timestamp:s,type:"tool_result",toolUseId:i.toolCallId,resultPreview:d,isError:i.status==="failed"};t?.onTaskLog?.([u]);}else if(i.rawInput!=null&&typeof i.rawInput=="object"&&Object.keys(i.rawInput).length>0){let d={title:i.title??"",kind:i.kind,rawInput:i.rawInput,rawOutput:i.rawOutput,locations:i.locations,_meta:i._meta},u=this.resolveToolCall(d),c={timestamp:s,type:"tool_use",toolUseId:i.toolCallId,toolName:u.toolName,toolInput:u.toolInput};t?.onTaskLog?.([c]);}}else n.sessionUpdate;}resolveToolCall(e){let t=e._meta;if(t?.claudeCode?.toolName)return {toolName:t.claudeCode.toolName,toolInput:Ur(e.rawInput,e.locations)??(e.title||void 0)};if(this.adapter.parseToolCall){let s=this.adapter.parseToolCall(e);if(s)return {toolName:s.toolName??e.title??"unknown",toolInput:s.toolInput}}let r=Mo[e.kind??""]??e.title??"unknown",n=Ur(e.rawInput,e.locations)??(e.title||void 0);return {toolName:r,toolInput:n}}extractResultPreview(e){if(e!=null){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e.filter(r=>r!=null&&typeof r=="object"&&r.type==="text"&&typeof r.text=="string").map(r=>r.text);if(t.length>0)return t.join(`
|
|
32
|
-
`)}if(typeof e=="object"){let t=e;if(typeof t.formatted_output=="string")return t.formatted_output;if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)){let r=this.extractResultPreview(t.content);if(r)return r}if(typeof t.output=="string")return t.output;if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message;if(t.result!=null){let r=this.extractResultPreview(t.result);if(r)return r}if(t.error!=null){let r=this.extractResultPreview(t.error);if(r)return r}}return JSON.stringify(e)}}handleUsage(e,t){if(!t?.onUsage)return;if(this.adapter.extractUsage){let n=this.adapter.extractUsage(e);if(n){t.onUsage(n);return}}let r=e.usage;r&&t.onUsage({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,cachedInputTokens:r.cachedReadTokens??0,costUsd:0});}};});exports.claudeAcpAdapter=void 0;var Ft=O(()=>{l();se();exports.claudeAcpAdapter={spawn:{command:"npx",args:["claude-agent-acp"],shellOnWindows:true},npmPackage:"@agentclientprotocol/claude-agent-acp",clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"Claude",defaultMode:"default"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},extractUsage(o){let e=o.usage;return e?{inputTokens:e.inputTokens??0,outputTokens:e.outputTokens??0,cachedInputTokens:e.cachedReadTokens??0,costUsd:0}:null},yoloModeId:"bypassPermissions",buildEffortAction(o){return o?{type:"set_config_option",configId:"effort",value:o}:null},resolveMode(o){return {yolo:"bypassPermissions"}[o]??o},parseEvent:K};});exports.codexAcpAdapter=void 0;var qt=O(()=>{l();se();exports.codexAcpAdapter={spawn:{command:"npx",args:["codex-acp"],shellOnWindows:true},npmPackage:"@agentclientprotocol/codex-acp",clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"Codex",defaultMode:"agent"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},extractUsage(o){let e=o.usage;return e?{inputTokens:e.inputTokens??0,outputTokens:e.outputTokens??0,cachedInputTokens:e.cachedReadTokens??0,costUsd:0}:null},yoloModeId:"agent-full-access",buildEffortAction(o,e){return e&&o?{type:"set_model",modelId:`${e}[${o}]`}:e&&!o?{type:"set_model",modelId:`${e}[medium]`}:null},resolveMode(o){return {yolo:"agent-full-access",default:"agent",plan:"read-only"}[o]??o},parseEvent:K};});exports.geminiAcpAdapter=void 0;var Wt=O(()=>{l();se();exports.geminiAcpAdapter={spawn:{command:"gemini",args:["--acp"],shellOnWindows:false},clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"Gemini"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},yoloModeId:"yolo",buildEffortAction(o){return null},resolveMode(o){return {acceptEdits:"autoEdit"}[o]??o},parseEvent:K};});var ke;exports.copilotAcpAdapter=void 0;var Bt=O(()=>{l();se();ke="https://agentclientprotocol.com/protocol/session-modes",exports.copilotAcpAdapter={spawn:{command:"copilot",args:["--acp"],shellOnWindows:false},clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"GitHub Copilot"},buildSessionParams(o){return {cwd:o.cwd?D.resolve(o.cwd):process.cwd(),mcpServers:[]}},yoloModeId:`${ke}#autopilot`,buildEffortAction(o){return o?{type:"set_config_option",configId:"reasoning_effort",value:o}:null},resolveMode(o){return o.startsWith("https://")?o:{yolo:`${ke}#autopilot`,default:`${ke}#agent`,agent:`${ke}#agent`,plan:`${ke}#plan`,autopilot:`${ke}#autopilot`}[o]??null},parseEvent:K};});exports.opencodeAcpAdapter=void 0;var Vt=O(()=>{l();se();exports.opencodeAcpAdapter={spawn:{command:"opencode",args:["acp"],shellOnWindows:false},clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"OpenCode"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},yoloModeId:void 0,buildEffortAction(o){return o?{type:"set_config_option",configId:"effort",value:o}:null},resolveMode(o){let e={default:"build"};return o==="yolo"?null:e[o]??o},parseEvent:K};});exports.ACP_ADAPTERS=void 0;var dt=O(()=>{l();Ft();qt();Wt();Bt();Vt();Ft();qt();Wt();Bt();Vt();exports.ACP_ADAPTERS={claude:exports.claudeAcpAdapter,codex:exports.codexAcpAdapter,gemini:exports.geminiAcpAdapter,copilot:exports.copilotAcpAdapter,opencode:exports.opencodeAcpAdapter};});var Fr={};qe(Fr,{registerAcpProviders:()=>Hr});function Hr(o){if(o){Z("acp",o);return}Z("acp",(e,t)=>{let r=exports.ACP_ADAPTERS[e];if(!r)throw new exports.ProviderError(`Unknown ACP provider id: "${e}". Supported: ${Object.keys(exports.ACP_ADAPTERS).join(", ")}`,t);return new exports.AcpProviderRuntime(e,r,t)});}var zt=O(()=>{l();X();Ht();dt();X();});function $o(o){if(!o)return o;let e=o.trim().replace(/\/+$/,"");return e.toLowerCase().endsWith("/mcp")?e.slice(0,-4):e}exports.McpHttpTransport=void 0;var Kt=O(()=>{l();exports.McpHttpTransport=class{endpoint;headers;timeoutMs;constructor(e){let t=$o(e.url);this.endpoint=`${t}/mcp`,this.headers={"Content-Type":"application/json",...e.headers??{}},e.apiKey&&(this.headers.Authorization=`Bearer ${e.apiKey}`),this.timeoutMs=e.timeoutMs??3e4;}async send(e){let t=new AbortController,r=setTimeout(()=>t.abort(),this.timeoutMs);try{let n=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(e),signal:t.signal});if(clearTimeout(r),!n.ok){let a=await n.text();throw new Error(`HTTP ${n.status}: ${n.statusText}${a?` - ${a}`:""}`)}let s=n.headers.get("content-type");if(s?.includes("application/json"))return await n.json();let i=await n.text();return {jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Unexpected response content-type: ${s}`,data:i}}}catch(n){throw clearTimeout(r),n instanceof Error&&n.name==="AbortError"?new Error(`MCP-HTTP request timeout after ${this.timeoutMs}ms to ${this.endpoint}`):n}}async close(){}};});exports.RemoteAgentManager=void 0;var Jt=O(()=>{l();Kt();exports.RemoteAgentManager=class{logger;configs=new Map;transports=new Map;constructor(e={}){this.logger=e.logger??(()=>{});}loadConfig(e,t){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,new exports.McpHttpTransport({url:t.url,apiKey:t.apiKey,headers:t.headers,timeoutMs:t.timeoutMs})),this.logger(`Loaded remote agent config for: ${e}`,"debug");}loadConfigWithTransport(e,t,r){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,r),this.logger(`Loaded remote agent config for: ${e} (custom transport)`,"debug");}getConfig(e){return this.configs.get(e)}isRemoteAgent(e){return this.configs.has(e)}getRemoteAgentIds(){return Array.from(this.configs.keys())}async query(e,t){let r=this.requireConfig(e),n=r.tools?.query??"crewx_queryAgent",i={agentId:r.agentId??e,query:t.query};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,n,i);return this.normalizeResponse(a)}catch(a){let d=a instanceof Error?a.message:String(a);throw this.logger(`Remote query failed for agent ${e}: ${d}`,"error"),a}}async execute(e,t){let r=this.requireConfig(e),n=r.tools?.execute??"crewx_executeAgent",i={agentId:r.agentId??e,task:t.task};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,n,i);return this.normalizeResponse(a)}catch(a){let d=a instanceof Error?a.message:String(a);throw this.logger(`Remote execute failed for agent ${e}: ${d}`,"error"),a}}mapToolNames(e,t){let r=this.requireConfig(e);r.tools={query:t.query??r.tools?.query??"crewx_queryAgent",execute:t.execute??r.tools?.execute??"crewx_executeAgent"},this.logger(`Updated tool name mapping for agent ${e}`,"debug");}async clearConfigs(){for(let e of this.transports.values())await e.close();this.configs.clear(),this.transports.clear(),this.logger("Cleared all remote agent configurations","debug");}requireConfig(e){let t=this.configs.get(e);if(!t)throw new Error(`Agent ${e} is not configured as a remote agent`);return t}async callRemoteTool(e,t,r){let n=this.transports.get(e);if(!n)throw new Error(`No transport available for agent ${e}`);let s={jsonrpc:"2.0",id:`${t}-${Date.now()}`,method:"tools/call",params:{name:t,arguments:r}};this.logger(`Calling remote MCP tool ${t} for agent ${e}`,"debug");let i=await n.send(s);if(i.error)throw new Error(i.error.message||"MCP server returned an error");return i.result}normalizeResponse(e){if(!e)return {success:false,content:[{type:"text",text:"Remote agent returned no response."}]};let t=e;if(Array.isArray(t.content)&&t.content.length>0)return t;let r=t.response??t.implementation??t.message??t.output,n=typeof r=="string"?r:JSON.stringify(r??e,null,2);return {...t,content:[{type:"text",text:n}]}}validateConfig(e){if(!e.url)throw new Error("Remote agent configuration requires a URL");if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("Remote agent URL must start with http:// or https://");if(e.type!=="mcp-http")throw new Error(`Unsupported remote agent type: ${e.type}`)}};});var Wr={};qe(Wr,{RemoteProviderRuntime:()=>exports.RemoteProviderRuntime,createRemoteProviderFactory:()=>qr,resolveFileRemoteAgent:()=>Wo});function Fo(o){let e=fs$1.readFileSync(o,"utf-8"),t=jsYaml.load(e);return {agents:Array.isArray(t?.agents)?t.agents:void 0}}function qo(o){let e=Array.isArray(o.provider)?o.provider[0]:o.provider;return e||(Array.isArray(o.inline?.provider)?o.inline.provider[0]:o.inline?.provider)}function Wo(o,e=Fo,t=fs$1.existsSync){let r=o.location.replace("file://","");if(!t(r))throw new Error(`Remote config file not found: ${r}`);if(!o.external_agent_id)throw new Error(`external_agent_id is required for file:// remote provider "${o.id}"`);let s=e(r).agents?.find(d=>d.id===o.external_agent_id);if(!s)throw new Error(`Agent "${o.external_agent_id}" not found in ${r}`);let i=qo(s);if(!i)throw new Error(`Agent "${o.external_agent_id}" in ${r} has no provider configured`);if(i.startsWith("remote/"))throw new Error(`Chained remotes not allowed: ${o.id} \u2192 ${i}`);let a=D.resolve(D.dirname(r),s.working_directory??".");return {agent:{...s,working_directory:a},provider:i}}function qr(o,e=ee){return (t,r)=>{let n=o.get(t);if(!n)throw new Error(`Remote provider "${t}" not found. Available: ${Array.from(o.keys()).join(", ")||"(none)"}`);if(n.location.startsWith("file://"))throw new Error(`Remote provider "${t}" uses file:// location which is not supported at the SDK level. Use the CLI commands (crewx query / crewx execute) which handle file:// remotes automatically.`);return new exports.RemoteProviderRuntime(t,n,e)}}function Bo(o,e){let t=e.location;if(!t)throw new Error("Remote provider config requires a location");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Unsupported remote location protocol for MCP-HTTP: ${t}`);return {type:"mcp-http",url:t,apiKey:e.apiKey,headers:e.headers,timeoutMs:e.timeout?.query??3e4,agentId:e.external_agent_id??o}}exports.RemoteProviderRuntime=void 0;var Xt=O(()=>{l();X();Jt();exports.RemoteProviderRuntime=class{manager;agentId;constructor(e,t,r=ee){this.agentId=t.external_agent_id??e,this.manager=new exports.RemoteAgentManager;let n=Bo(e,t);this.manager.loadConfig(this.agentId,n);}async query(e,t){return (await this.manager.query(this.agentId,{agentId:this.agentId,query:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(n=>n.text).join(`
|
|
32
|
+
`)}if(typeof e=="object"){let t=e;if(typeof t.formatted_output=="string")return t.formatted_output;if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)){let r=this.extractResultPreview(t.content);if(r)return r}if(typeof t.output=="string")return t.output;if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message;if(t.result!=null){let r=this.extractResultPreview(t.result);if(r)return r}if(t.error!=null){let r=this.extractResultPreview(t.error);if(r)return r}}return JSON.stringify(e)}}handleUsage(e,t){if(!t?.onUsage)return;if(this.adapter.extractUsage){let n=this.adapter.extractUsage(e);if(n){t.onUsage(n);return}}let r=e.usage;r&&t.onUsage({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,cachedInputTokens:r.cachedReadTokens??0,costUsd:0});}};});exports.claudeAcpAdapter=void 0;var Ft=O(()=>{l();se();exports.claudeAcpAdapter={spawn:{command:"npx",args:["-y","@agentclientprotocol/claude-agent-acp"],shellOnWindows:true},npmPackage:"@agentclientprotocol/claude-agent-acp",clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"Claude",defaultMode:"default"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},extractUsage(o){let e=o.usage;return e?{inputTokens:e.inputTokens??0,outputTokens:e.outputTokens??0,cachedInputTokens:e.cachedReadTokens??0,costUsd:0}:null},yoloModeId:"bypassPermissions",buildEffortAction(o){return o?{type:"set_config_option",configId:"effort",value:o}:null},resolveMode(o){return {yolo:"bypassPermissions"}[o]??o},parseEvent:K};});exports.codexAcpAdapter=void 0;var qt=O(()=>{l();se();exports.codexAcpAdapter={spawn:{command:"npx",args:["-y","@agentclientprotocol/codex-acp"],shellOnWindows:true},npmPackage:"@agentclientprotocol/codex-acp",clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"Codex",defaultMode:"agent"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},extractUsage(o){let e=o.usage;return e?{inputTokens:e.inputTokens??0,outputTokens:e.outputTokens??0,cachedInputTokens:e.cachedReadTokens??0,costUsd:0}:null},yoloModeId:"agent-full-access",buildEffortAction(o,e){return e&&o?{type:"set_model",modelId:`${e}[${o}]`}:e&&!o?{type:"set_model",modelId:`${e}[medium]`}:null},resolveMode(o){return {yolo:"agent-full-access",default:"agent",plan:"read-only"}[o]??o},parseEvent:K};});exports.geminiAcpAdapter=void 0;var Wt=O(()=>{l();se();exports.geminiAcpAdapter={spawn:{command:"gemini",args:["--acp"],shellOnWindows:false},clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"Gemini"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},yoloModeId:"yolo",buildEffortAction(o){return null},resolveMode(o){return {acceptEdits:"autoEdit"}[o]??o},parseEvent:K};});var ke;exports.copilotAcpAdapter=void 0;var Bt=O(()=>{l();se();ke="https://agentclientprotocol.com/protocol/session-modes",exports.copilotAcpAdapter={spawn:{command:"copilot",args:["--acp"],shellOnWindows:false},clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"GitHub Copilot"},buildSessionParams(o){return {cwd:o.cwd?D.resolve(o.cwd):process.cwd(),mcpServers:[]}},yoloModeId:`${ke}#autopilot`,buildEffortAction(o){return o?{type:"set_config_option",configId:"reasoning_effort",value:o}:null},resolveMode(o){return o.startsWith("https://")?o:{yolo:`${ke}#autopilot`,default:`${ke}#agent`,agent:`${ke}#agent`,plan:`${ke}#plan`,autopilot:`${ke}#autopilot`}[o]??null},parseEvent:K};});exports.opencodeAcpAdapter=void 0;var Vt=O(()=>{l();se();exports.opencodeAcpAdapter={spawn:{command:"opencode",args:["acp"],shellOnWindows:false},clientInfo:{name:"crewx-sdk",version:"0.8.4"},meta:{displayName:"OpenCode"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},yoloModeId:void 0,buildEffortAction(o){return o?{type:"set_config_option",configId:"effort",value:o}:null},resolveMode(o){let e={default:"build"};return o==="yolo"?null:e[o]??o},parseEvent:K};});exports.ACP_ADAPTERS=void 0;var dt=O(()=>{l();Ft();qt();Wt();Bt();Vt();Ft();qt();Wt();Bt();Vt();exports.ACP_ADAPTERS={claude:exports.claudeAcpAdapter,codex:exports.codexAcpAdapter,gemini:exports.geminiAcpAdapter,copilot:exports.copilotAcpAdapter,opencode:exports.opencodeAcpAdapter};});var Fr={};qe(Fr,{registerAcpProviders:()=>Hr});function Hr(o){if(o){Z("acp",o);return}Z("acp",(e,t)=>{let r=exports.ACP_ADAPTERS[e];if(!r)throw new exports.ProviderError(`Unknown ACP provider id: "${e}". Supported: ${Object.keys(exports.ACP_ADAPTERS).join(", ")}`,t);return new exports.AcpProviderRuntime(e,r,t)});}var zt=O(()=>{l();X();Ht();dt();X();});function $o(o){if(!o)return o;let e=o.trim().replace(/\/+$/,"");return e.toLowerCase().endsWith("/mcp")?e.slice(0,-4):e}exports.McpHttpTransport=void 0;var Kt=O(()=>{l();exports.McpHttpTransport=class{endpoint;headers;timeoutMs;constructor(e){let t=$o(e.url);this.endpoint=`${t}/mcp`,this.headers={"Content-Type":"application/json",...e.headers??{}},e.apiKey&&(this.headers.Authorization=`Bearer ${e.apiKey}`),this.timeoutMs=e.timeoutMs??3e4;}async send(e){let t=new AbortController,r=setTimeout(()=>t.abort(),this.timeoutMs);try{let n=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(e),signal:t.signal});if(clearTimeout(r),!n.ok){let a=await n.text();throw new Error(`HTTP ${n.status}: ${n.statusText}${a?` - ${a}`:""}`)}let s=n.headers.get("content-type");if(s?.includes("application/json"))return await n.json();let i=await n.text();return {jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Unexpected response content-type: ${s}`,data:i}}}catch(n){throw clearTimeout(r),n instanceof Error&&n.name==="AbortError"?new Error(`MCP-HTTP request timeout after ${this.timeoutMs}ms to ${this.endpoint}`):n}}async close(){}};});exports.RemoteAgentManager=void 0;var Jt=O(()=>{l();Kt();exports.RemoteAgentManager=class{logger;configs=new Map;transports=new Map;constructor(e={}){this.logger=e.logger??(()=>{});}loadConfig(e,t){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,new exports.McpHttpTransport({url:t.url,apiKey:t.apiKey,headers:t.headers,timeoutMs:t.timeoutMs})),this.logger(`Loaded remote agent config for: ${e}`,"debug");}loadConfigWithTransport(e,t,r){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,r),this.logger(`Loaded remote agent config for: ${e} (custom transport)`,"debug");}getConfig(e){return this.configs.get(e)}isRemoteAgent(e){return this.configs.has(e)}getRemoteAgentIds(){return Array.from(this.configs.keys())}async query(e,t){let r=this.requireConfig(e),n=r.tools?.query??"crewx_queryAgent",i={agentId:r.agentId??e,query:t.query};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,n,i);return this.normalizeResponse(a)}catch(a){let d=a instanceof Error?a.message:String(a);throw this.logger(`Remote query failed for agent ${e}: ${d}`,"error"),a}}async execute(e,t){let r=this.requireConfig(e),n=r.tools?.execute??"crewx_executeAgent",i={agentId:r.agentId??e,task:t.task};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,n,i);return this.normalizeResponse(a)}catch(a){let d=a instanceof Error?a.message:String(a);throw this.logger(`Remote execute failed for agent ${e}: ${d}`,"error"),a}}mapToolNames(e,t){let r=this.requireConfig(e);r.tools={query:t.query??r.tools?.query??"crewx_queryAgent",execute:t.execute??r.tools?.execute??"crewx_executeAgent"},this.logger(`Updated tool name mapping for agent ${e}`,"debug");}async clearConfigs(){for(let e of this.transports.values())await e.close();this.configs.clear(),this.transports.clear(),this.logger("Cleared all remote agent configurations","debug");}requireConfig(e){let t=this.configs.get(e);if(!t)throw new Error(`Agent ${e} is not configured as a remote agent`);return t}async callRemoteTool(e,t,r){let n=this.transports.get(e);if(!n)throw new Error(`No transport available for agent ${e}`);let s={jsonrpc:"2.0",id:`${t}-${Date.now()}`,method:"tools/call",params:{name:t,arguments:r}};this.logger(`Calling remote MCP tool ${t} for agent ${e}`,"debug");let i=await n.send(s);if(i.error)throw new Error(i.error.message||"MCP server returned an error");return i.result}normalizeResponse(e){if(!e)return {success:false,content:[{type:"text",text:"Remote agent returned no response."}]};let t=e;if(Array.isArray(t.content)&&t.content.length>0)return t;let r=t.response??t.implementation??t.message??t.output,n=typeof r=="string"?r:JSON.stringify(r??e,null,2);return {...t,content:[{type:"text",text:n}]}}validateConfig(e){if(!e.url)throw new Error("Remote agent configuration requires a URL");if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("Remote agent URL must start with http:// or https://");if(e.type!=="mcp-http")throw new Error(`Unsupported remote agent type: ${e.type}`)}};});var Wr={};qe(Wr,{RemoteProviderRuntime:()=>exports.RemoteProviderRuntime,createRemoteProviderFactory:()=>qr,resolveFileRemoteAgent:()=>Wo});function Fo(o){let e=fs$1.readFileSync(o,"utf-8"),t=jsYaml.load(e);return {agents:Array.isArray(t?.agents)?t.agents:void 0}}function qo(o){let e=Array.isArray(o.provider)?o.provider[0]:o.provider;return e||(Array.isArray(o.inline?.provider)?o.inline.provider[0]:o.inline?.provider)}function Wo(o,e=Fo,t=fs$1.existsSync){let r=o.location.replace("file://","");if(!t(r))throw new Error(`Remote config file not found: ${r}`);if(!o.external_agent_id)throw new Error(`external_agent_id is required for file:// remote provider "${o.id}"`);let s=e(r).agents?.find(d=>d.id===o.external_agent_id);if(!s)throw new Error(`Agent "${o.external_agent_id}" not found in ${r}`);let i=qo(s);if(!i)throw new Error(`Agent "${o.external_agent_id}" in ${r} has no provider configured`);if(i.startsWith("remote/"))throw new Error(`Chained remotes not allowed: ${o.id} \u2192 ${i}`);let a=D.resolve(D.dirname(r),s.working_directory??".");return {agent:{...s,working_directory:a},provider:i}}function qr(o,e=ee){return (t,r)=>{let n=o.get(t);if(!n)throw new Error(`Remote provider "${t}" not found. Available: ${Array.from(o.keys()).join(", ")||"(none)"}`);if(n.location.startsWith("file://"))throw new Error(`Remote provider "${t}" uses file:// location which is not supported at the SDK level. Use the CLI commands (crewx query / crewx execute) which handle file:// remotes automatically.`);return new exports.RemoteProviderRuntime(t,n,e)}}function Bo(o,e){let t=e.location;if(!t)throw new Error("Remote provider config requires a location");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Unsupported remote location protocol for MCP-HTTP: ${t}`);return {type:"mcp-http",url:t,apiKey:e.apiKey,headers:e.headers,timeoutMs:e.timeout?.query??3e4,agentId:e.external_agent_id??o}}exports.RemoteProviderRuntime=void 0;var Xt=O(()=>{l();X();Jt();exports.RemoteProviderRuntime=class{manager;agentId;constructor(e,t,r=ee){this.agentId=t.external_agent_id??e,this.manager=new exports.RemoteAgentManager;let n=Bo(e,t);this.manager.loadConfig(this.agentId,n);}async query(e,t){return (await this.manager.query(this.agentId,{agentId:this.agentId,query:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(n=>n.text).join(`
|
|
33
33
|
`)}async execute(e,t){return (await this.manager.execute(this.agentId,{agentId:this.agentId,task:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(n=>n.text).join(`
|
|
34
34
|
`)}};});var Kr={};qe(Kr,{PluginProviderRuntime:()=>exports.PluginProviderRuntime,createPluginProviderFactory:()=>zr});function zr(o){return (e,t)=>{let r=o.get(e);if(!r)throw new exports.ProviderError(`Plugin provider "${e}" not found. Available: ${Array.from(o.keys()).join(", ")||"(none)"}`,`plugin/${e}`);return new exports.PluginProviderRuntime(e,r)}}function Br(o,e,t,r){let n=o.map(s=>s.replace(/\{model\}/g,e));return r&&n.push(t),n}function zo(o){if(!o||typeof o!="string")throw new Error("Plugin provider requires a cli_command")}function Vr(o){if(!Array.isArray(o))throw new Error("CLI arguments must be an array");for(let e of o)if(typeof e!="string")throw new Error("Each CLI argument must be a string")}function Ko(o){for(let{pattern:e}of o)if(typeof e!="string")throw new Error("Error pattern must be a string")}function Jo(o){for(let[e,t]of Object.entries(o))if(typeof e!="string"||typeof t!="string")throw new Error("env entries must be string key/value pairs")}exports.PluginProviderRuntime=void 0;var Qt=O(()=>{l();X();Xe();exports.PluginProviderRuntime=class{constructor(e,t){this.config=t;this.providerStr=`plugin/${e}`,zo(t.cli_command),Vr(t.query_args),Vr(t.execute_args),t.error_patterns&&Ko(t.error_patterns),t.env&&Jo(t.env);}config;providerStr;async query(e,t){let r=t?.model??this.config.default_model??"default",n=Br(this.config.query_args,r,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${n.join(" ")}`);let i=this.config.timeout?.query??6e5;return this.runProcess(n,t,s,i)}async execute(e,t){let r=t?.model??this.config.default_model??"default",n=Br(this.config.execute_args,r,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${n.join(" ")}`);let i=this.config.timeout?.execute??6e5;return this.runProcess(n,t,s,i)}runProcess(e,t,r,n){return new Promise((s,i)=>{let a={...process.env,...this.config.env??{}},d=Ae({command:this.config.cli_command,allowShellFallback:true}),u=Pe(d,e),c=child_process.spawn(u.command,u.argv,{env:a,shell:u.shell??false,stdio:["pipe","pipe","pipe"],windowsHide:u.windowsHide});r!==void 0&&c.stdin.write(r),c.stdin.end(),c.pid!==void 0&&t?.onPid?.(c.pid);let m="",p="",g="",f="";c.stdout.on("data",h=>{let k=h.toString();m+=k,g+=k;let v=g.split(`
|
|
35
35
|
`);g=v.pop()??"";for(let R of v)R.trim()&&t?.onOutput?.(R,"stdout");}),c.stderr.on("data",h=>{let k=h.toString();p+=k,f+=k;let v=f.split(`
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
-- Backfill: workspace_id가 NULL이고 workspace_name만 있는 행을 workspaces 테이블에서 매칭
|
|
2
|
+
UPDATE tasks
|
|
3
|
+
SET workspace_id = (
|
|
4
|
+
SELECT w.id FROM workspaces w
|
|
5
|
+
WHERE w.name = tasks.workspace_name
|
|
6
|
+
LIMIT 1
|
|
7
|
+
)
|
|
8
|
+
WHERE workspace_id IS NULL
|
|
9
|
+
AND workspace_name IS NOT NULL
|
|
10
|
+
AND EXISTS (SELECT 1 FROM workspaces w WHERE w.name = tasks.workspace_name);
|
|
11
|
+
--> statement-breakpoint
|
|
12
|
+
ALTER TABLE tasks DROP COLUMN workspace_name;--> statement-breakpoint
|
|
13
|
+
ALTER TABLE tasks DROP COLUMN project_name;
|