@crewx/sdk 0.8.8-rc.8 → 0.8.8
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/conversation/types.d.ts +1 -0
- package/dist/esm/index.js +127 -42
- package/dist/esm/plugins/index.js +4 -4
- package/dist/esm/repository/index.js +1 -1
- package/dist/events/types.d.ts +3 -0
- package/dist/facade/Crewx.d.ts +1 -0
- package/dist/facade/trace-context.d.ts +4 -0
- package/dist/index.browser.js +2 -2
- package/dist/index.d.ts +5 -1
- package/dist/index.js +127 -42
- package/dist/plugins/index.js +4 -4
- package/dist/provider/acp/adapter.d.ts +1 -0
- package/dist/provider/acp/adapters/claude.d.ts +4 -0
- package/dist/provider/acp/meta.d.ts +1 -0
- package/dist/repository/index.js +1 -1
- package/dist/template/helpers/format-conversation.d.ts +4 -1
- package/dist/template/helpers/time.d.ts +2 -0
- package/dist/types/index.d.ts +7 -0
- package/package.json +1 -1
- package/templates/agents/default.yaml +23 -8
package/dist/plugins/index.js
CHANGED
|
@@ -8,11 +8,11 @@ Message: ${e.message}
|
|
|
8
8
|
`;fs.writeFileSync(n,r,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toISOString();fs.appendFileSync(s,`[${n}] STDOUT: ${e.output}
|
|
9
9
|
`,"utf8");}catch{}}),t.on("task:end",e=>{try{let s=this.logFiles.get(e.traceId);if(!s)return;let n=new Date().toLocaleString(),r=e.error?`failed: ${e.error.message}`:"completed successfully",i=`[${n}] INFO: Task ${r} in ${e.durationMs}ms
|
|
10
10
|
[${n}] INFO: Process closed with exit code: ${e.error?1:0}
|
|
11
|
-
`;fs.appendFileSync(s,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Ot(d){let t=L__namespace.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function mt(d){let t=Ot(d);return crypto.createHash("sha256").update(t).digest("hex")}var F=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:L.join(Pt__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return fs.existsSync(t??this.resolveDbPath())}};function w(d){let t=H("better-sqlite3"),{drizzle:e}=H("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),{db:e(s),runRaw:(n,r=[])=>s.prepare(n).run(...r),close:()=>s.close()}}var ht=new Set,Lt={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 Mt(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function It(d,t){if(t>0||!Mt(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),s=new Set(e.map(n=>n.name));for(let[n,r]of Object.entries(Lt))s.has(n)||d.run(`ALTER TABLE tasks ADD COLUMN ${n} ${r}`);}function Ut(d,t,e){let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(i=>i.hash)),r=JSON.parse(fs.readFileSync(L__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let a=L__namespace.default.join(t,`${i.tag}.sql`);if(!fs.existsSync(a))continue;let c=fs.readFileSync(a,"utf-8"),p=crypto.createHash("sha256").update(c).digest("hex");if(n.has(p))continue;let m=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],E;for(;(E=m.exec(c))!==null;)f.push({table:E[1],column:E[2]});if(f.length===0||!c.split(/-->\s*statement-breakpoint/).map(N=>N.trim()).filter(Boolean).every(N=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(N)))continue;f.every(({table:N,column:tt})=>d.all(`PRAGMA table_info("${N}")`).some(
|
|
11
|
+
`;fs.appendFileSync(s,i,"utf8"),this.logFiles.delete(e.traceId);}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[],this.logFiles.clear();}};function Ot(d){let t=L__namespace.resolve(d);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(e,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function mt(d){let t=Ot(d);return crypto.createHash("sha256").update(t).digest("hex")}var F=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:L.join(Pt__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return fs.existsSync(t??this.resolveDbPath())}};function w(d){let t=H("better-sqlite3"),{drizzle:e}=H("drizzle-orm/better-sqlite3"),s=new t(d);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),{db:e(s),runRaw:(n,r=[])=>s.prepare(n).run(...r),close:()=>s.close()}}var ht=new Set,Lt={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 Mt(d,t){return (d.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function It(d,t){if(t>0||!Mt(d,"tasks"))return;let e=d.all("PRAGMA table_info(tasks)"),s=new Set(e.map(n=>n.name));for(let[n,r]of Object.entries(Lt))s.has(n)||d.run(`ALTER TABLE tasks ADD COLUMN ${n} ${r}`);}function Ut(d,t,e){let s=d.all(e`SELECT hash FROM __drizzle_migrations`),n=new Set(s.map(i=>i.hash)),r=JSON.parse(fs.readFileSync(L__namespace.default.join(t,"meta/_journal.json"),"utf-8"));for(let i of r.entries){let a=L__namespace.default.join(t,`${i.tag}.sql`);if(!fs.existsSync(a))continue;let c=fs.readFileSync(a,"utf-8"),p=crypto.createHash("sha256").update(c).digest("hex");if(n.has(p))continue;let m=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,f=[],E;for(;(E=m.exec(c))!==null;)f.push({table:E[1],column:E[2]});if(f.length===0||!c.split(/-->\s*statement-breakpoint/).map(N=>N.trim()).filter(Boolean).every(N=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(N)))continue;f.every(({table:N,column:tt})=>d.all(`PRAGMA table_info("${N}")`).some(St=>St.name===tt))&&d.run(e`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${p}, ${i.when})`);}}function $t(d){let{migrate:t}=H("drizzle-orm/better-sqlite3/migrator"),{sql:e}=H("drizzle-orm"),s=[L__namespace.default.join(__dirname,"../migrations"),L__namespace.default.join(__dirname,"migrations"),L__namespace.default.join(__dirname,"../../../../drizzle/migrations"),L__namespace.default.join(process.cwd(),"drizzle/migrations")],n=s.find(p=>fs.existsSync(L__namespace.default.join(p,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
|
|
12
12
|
${s.join(`
|
|
13
13
|
`)}`);let r=d.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;r?.cnt&&(i=d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),It(d,i),r?.cnt&&Ut(d,n,e),t(d,{migrationsFolder:n});let c=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(c>0){let p=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${p} (${c} migration${c>1?"s":""} applied).`);}}function j(d,t){ht.has(t)||($t(d),ht.add(t));}var u=class extends Error{code;cause;constructor(t,e,s){super(e),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var B=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var o=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0)},d=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(d.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var l=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>B.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(d.workspace_id)}));var Xt=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Xt.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},d=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},d=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>l.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(d.thread_id,d.seq)}));sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},d=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(d.partition_key)}));var K=class extends F{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=L.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=L.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new u("NOT_FOUND","Database not found");let s=w(e);if(t)try{j(s.db,e);}catch(n){throw s.close(),n}return s}startTask(t){let e=this.openHandle(true);try{e.db.insert(o).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to start task",s)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
14
14
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
15
|
-
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),n.update(o).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.started_at)).all()}catch(e){throw new u("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(drizzleOrm.desc(o.started_at)).limit(100).all()}catch(e){throw new u("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new u("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(drizzleOrm.eq(o.status,"running")).all(),s=0;for(let n of e){let r=!1;
|
|
15
|
+
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to finish task",s)}finally{e.close();}}appendLog(t,e){let s=this.openHandle(true);try{s.db.transaction(n=>{let r=n.select({logs:o.logs}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get(),i=r?.logs?JSON.parse(r.logs):[];i.push(e),n.update(o).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to append log",n)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(drizzleOrm.eq(o.status,"running")).orderBy(drizzleOrm.desc(o.started_at)).all()}catch(e){throw new u("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).orderBy(drizzleOrm.desc(o.started_at)).limit(100).all()}catch(e){throw new u("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get()??void 0}catch(s){throw new u("DB_ERROR","Failed to get task",s)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let s=e.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(drizzleOrm.eq(o.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return e.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to kill task",s)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:o.id,pid:o.pid}).from(o).where(drizzleOrm.eq(o.status,"running")).all(),s=0;for(let n of e){if(!n.pid)continue;let r=!1;try{process.kill(n.pid,0),r=!0;}catch{}r||(t.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(o.id,n.id),drizzleOrm.eq(o.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=w(n);try{let i=e?drizzleOrm.eq(o.workspace_id,e):void 0,a=i?drizzleOrm.and(drizzleOrm.eq(o.id,t),i):drizzleOrm.eq(o.id,t),c=r.db.select().from(o).where(a).limit(1).get()??void 0;if(!c){let p=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),m=i?drizzleOrm.and(p,i):p;c=r.db.select().from(o).where(m).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??void 0;}if(c)return c}catch(i){throw new u("DB_ERROR","Failed to find task status",i)}finally{r.close();}}}findChildTasks(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!fs.existsSync(i))continue;let a=w(i);try{let c=e?drizzleOrm.and(drizzleOrm.eq(o.parent_task_id,t),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.eq(o.parent_task_id,t),p=a.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let m of p)n.has(m.id)||(n.add(m.id),r.push(m));}catch(c){throw new u("DB_ERROR","Failed to find child tasks",c)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
|
|
16
16
|
SELECT
|
|
17
17
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
18
18
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -93,7 +93,7 @@ ${s.join(`
|
|
|
93
93
|
AND t.started_at < ${e}
|
|
94
94
|
GROUP BY date(t.started_at), t.agent_id
|
|
95
95
|
ORDER BY date(t.started_at) ASC
|
|
96
|
-
`).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 u("DB_ERROR","Failed to get agent usage trend",r)}finally{n.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new u("DB_ERROR","Failed to find task for stop",n)}finally{s.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString(),i=s?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,s)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));n.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!fs.existsSync(i))continue;let a=w(i);try{let c=e?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.like(o.prompt,`%${t}%`),p=a.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let m of p)n.has(m.id)||(n.add(m.id),r.push(m));}catch(c){throw new u("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{a.close();}}return r}};var it=class extends A{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=L.join(t?.dbRoot??Pt.homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new K({dbPath:this.dbPath}),s=process.cwd(),r=fs.existsSync(L.join(s,"crewx.yaml"))||fs.existsSync(L.join(s,"crewx.yml"))?mt(s):null,i=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let c=
|
|
96
|
+
`).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 u("DB_ERROR","Failed to get agent usage trend",r)}finally{n.close();}}findTaskForStop(t,e){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(o).where(drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.workspace_id,e))).limit(1).get()??void 0}catch(n){throw new u("DB_ERROR","Failed to find task for stop",n)}finally{s.close();}}markTaskFailed(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString(),i=s?drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"),drizzleOrm.eq(o.workspace_id,s)):drizzleOrm.and(drizzleOrm.eq(o.id,t),drizzleOrm.eq(o.status,"running"));n.db.update(o).set({status:"failed",error:e,completed_at:r}).where(i).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to mark task failed",r)}finally{n.close();}}findTasksByPromptHint(t,e){let s=this.resolveDbPaths(),n=new Set,r=[];for(let i of s){if(!fs.existsSync(i))continue;let a=w(i);try{let c=e?drizzleOrm.and(drizzleOrm.like(o.prompt,`%${t}%`),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.like(o.prompt,`%${t}%`),p=a.db.select().from(o).where(c).orderBy(drizzleOrm.asc(o.started_at)).all();for(let m of p)n.has(m.id)||(n.add(m.id),r.push(m));}catch(c){throw new u("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{a.close();}}return r}};var it=class extends A{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=L.join(t?.dbRoot??Pt.homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let e=new K({dbPath:this.dbPath}),s=process.cwd(),r=fs.existsSync(L.join(s,"crewx.yaml"))||fs.existsSync(L.join(s,"crewx.yml"))?mt(s):null,i=process.argv.join(" ");this.unsubs.push(t.on("task:start",a=>{try{let c=a.callerAgentId??null,p=a.parentTaskId??null,m=a.rootTraceId??a.traceId,f=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});e.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:i,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??r,callerAgentId:c,parentTaskId:p,traceId:m,metadata:f,threadId:a.threadId??null});}catch{}}),t.on("task:output",a=>{try{e.appendLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch{}}),t.on("task:end",a=>{try{e.finishTask({id:a.traceId,status:a.error?"failed":"success",result:a.result??null,error:a.error?JSON.stringify(a.error):null,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null});}catch{}}));}detach(t){this.unsubs.forEach(e=>e()),this.unsubs=[];}};var Q=class extends F{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=L.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=L.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new u("NOT_FOUND","Database not found");let s=w(e);if(t)try{j(s.db,e);}catch(n){throw s.close(),n}return s}validateWorkspaceId(t,e){return t.db.select({id:B.id}).from(B).where(drizzleOrm.eq(B.id,e)).limit(1).get()?e:null}findAllThreads(t){let e=this.resolveDbPaths(),s=new Set,n=[];for(let r of e){if(!fs.existsSync(r))continue;let i=w(r);try{let a=t?drizzleOrm.eq(l.workspace_id,t):void 0,c=i.db.select().from(l).where(a).orderBy(drizzleOrm.desc(l.updated_at)).all();for(let p of c)s.has(p.id)||(s.add(p.id),n.push(p));}catch(a){throw new u("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return n}findThreadById(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=w(n);try{let i=drizzleOrm.eq(l.id,t),a=e?drizzleOrm.and(i,drizzleOrm.eq(l.workspace_id,e)):i,c=r.db.select().from(l).where(a).limit(1).get()??void 0;if(c)return c}catch(i){throw new u("DB_ERROR","Failed to find thread by id",i)}finally{r.close();}}}threadExists(t,e){let s=this.resolveDbPaths();for(let n of s){if(!fs.existsSync(n))continue;let r=w(n);try{let i=drizzleOrm.eq(l.id,t),a=e?drizzleOrm.and(i,drizzleOrm.eq(l.workspace_id,e)):i;if(r.db.select({id:l.id}).from(l).where(a).limit(1).get())return !0}catch(i){throw new u("DB_ERROR","Failed to check thread existence",i)}finally{r.close();}}return false}aggregateTaskStats(t,e){let s=this.resolveDbPaths(),n=0,r=0,i=0,a=0,c=0,p=new Set;for(let m of s){if(!fs.existsSync(m))continue;let f=w(m);try{let E=drizzleOrm.and(drizzleOrm.eq(o.thread_id,t),drizzleOrm.or(drizzleOrm.isNull(o.parent_task_id),drizzleOrm.eq(o.parent_task_id,""))),O=e?drizzleOrm.and(E,drizzleOrm.eq(o.workspace_id,e)):E,P=f.db.select({cnt:drizzleOrm.sql`count(*)`,total_input:drizzleOrm.sql`COALESCE(SUM(input_tokens), 0)`,total_output:drizzleOrm.sql`COALESCE(SUM(output_tokens), 0)`,total_cached:drizzleOrm.sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:drizzleOrm.sql`COALESCE(SUM(cost_usd), 0)`}).from(o).where(O).get();P&&(n+=P.cnt,r+=P.total_input,i+=P.total_output,a+=P.total_cached,c+=P.total_cost);let N=f.db.all(drizzleOrm.sql`
|
|
97
97
|
SELECT DISTINCT agent_id FROM tasks
|
|
98
98
|
WHERE thread_id = ${t}
|
|
99
99
|
AND agent_id IS NOT NULL AND agent_id != ''
|
|
@@ -110,4 +110,4 @@ ${s.join(`
|
|
|
110
110
|
`),p},{behavior:"immediate"})}}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to save user message",r)}finally{n.close();}}saveAssistantMessage(t,e,s){if(!this.dbExists())return;let n=this.openHandle(true);try{let r=new Date().toISOString();n.db.update(l).set({last_message:e,updated_at:r}).where(drizzleOrm.eq(l.id,t)).run();}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to save assistant message",r)}finally{n.close();}}updateThread(t,e){if(!this.dbExists())return;let s=this.openHandle(true);try{let n={updated_at:new Date().toISOString()};e.title!==void 0&&(n.title=e.title,n.title_locked=1),e.titleLocked!==void 0&&(n.title_locked=e.titleLocked?1:0),s.db.update(l).set(n).where(drizzleOrm.eq(l.id,t)).run();}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to update thread",n)}finally{s.close();}}togglePin(t,e){let s=this.openHandle(true);try{let n=e?drizzleOrm.and(drizzleOrm.eq(l.id,t),drizzleOrm.eq(l.workspace_id,e)):drizzleOrm.eq(l.id,t),r=s.db.select({pinned:l.pinned,metadata:l.metadata}).from(l).where(n).get();if(!r)return null;let i=r.pinned?0:1,a=r.metadata?JSON.parse(r.metadata):{};if(i){let c=e?drizzleOrm.and(drizzleOrm.eq(l.pinned,1),drizzleOrm.eq(l.workspace_id,e)):drizzleOrm.eq(l.pinned,1),p=s.db.select({metadata:l.metadata}).from(l).where(c).all(),m=0;for(let f of p){let E=f.metadata?JSON.parse(f.metadata):{};typeof E.pinOrder=="number"&&E.pinOrder>m&&(m=E.pinOrder);}a.pinOrder=m+1;}else delete a.pinOrder;return s.db.update(l).set({pinned:i,metadata:Object.keys(a).length>0?JSON.stringify(a):null}).where(n).run(),{pinned:!!i}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to toggle pin",n)}finally{s.close();}}reorderPins(t,e){let s=this.openHandle(true);try{for(let n=0;n<t.length;n++){let r=e?drizzleOrm.and(drizzleOrm.eq(l.id,t[n]),drizzleOrm.eq(l.workspace_id,e)):drizzleOrm.eq(l.id,t[n]),i=s.db.select({metadata:l.metadata}).from(l).where(r).get();if(!i)continue;let a=i.metadata?JSON.parse(i.metadata):{};a.pinOrder=n+1,s.db.update(l).set({metadata:JSON.stringify(a)}).where(r).run();}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to reorder pins",n)}finally{s.close();}}toggleStar(t,e){let s=this.openHandle(true);try{let n=e?drizzleOrm.and(drizzleOrm.eq(l.id,t),drizzleOrm.eq(l.workspace_id,e)):drizzleOrm.eq(l.id,t),r=s.db.select({starred:l.starred}).from(l).where(n).get();if(!r)return null;let i=r.starred?0:1;return s.db.update(l).set({starred:i}).where(n).run(),{starred:!!i}}catch(n){throw n instanceof u?n:new u("DB_ERROR","Failed to toggle star",n)}finally{s.close();}}};function pe(d){return d.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
111
111
|
`).filter(n=>!(n.startsWith("Loaded ")&&n.includes("layouts from")||n.includes("[dotenv@")||n.includes("[Nest]")&&n.includes("DEBUG")||n.startsWith("Registered custom layout:")||n.startsWith("Updated custom layout:"))).join(`
|
|
112
112
|
`).trim()}function _e(d){if(!d)return "";let t=d;try{let e=JSON.parse(t);Array.isArray(e)?t=e.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
|
|
113
|
-
`):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=pe(t);}return t}var Z=class{dbPath;constructor(t){this.dbPath=t??L.join(Pt.homedir(),".crewx","crewx.db");}getThreadRepo(){return new Q({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let n=this.getThreadRepo(),r=n.findThreadById(t);if(r){if(r.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${r.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return n.ensureThread(t,e,s),{created:true}}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),i=n.findTopLevelTasks(t),a=new Set(["done","completed","success"]);i=i.filter(m=>(!m.status||a.has(m.status))&&(!e?.currentTraceId||m.trace_id!==e.currentTraceId)),i=i.slice(0,s);let c=r?.platform??"cli",p=this.rowsToMessages(i);return {threadId:t,platform:c,messages:p,metadata:{title:r?.title??void 0,firstMessage:r?.first_message??void 0,lastMessage:r?.last_message??void 0,messageCount:r?.message_count??0,updatedAt:r?.updated_at?new Date(r.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,n){let{firstMessage:r}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:r}}async saveAssistantMessage(t,e,s,n){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}close(){}rowsToMessages(t){let e=[];for(let s of t){s.prompt&&e.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime()});let n=_e(s.result);n&&e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime()});}return e}};var lt=class extends A{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new Z(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,s,n){}async afterAssistantMessage(t,e,s){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{let n=await this._provider.ensureThread(e.threadId,s,e.workspaceId),r=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,r.id,n.created||r.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let n=e.agentRef?.replace(/^@/,"")??"";try{let{id:r}=await this._provider.saveAssistantMessage(s,e.result,n);await this.afterAssistantMessage(s,r,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=lt;exports.FileLoggerPlugin=et;exports.SqliteTracingPlugin=it;
|
|
113
|
+
`):e&&typeof e=="object"&&e.result!==void 0&&(t=e.result||"");}catch{t=pe(t);}return t}var Z=class{dbPath;constructor(t){this.dbPath=t??L.join(Pt.homedir(),".crewx","crewx.db");}getThreadRepo(){return new Q({dbPath:this.dbPath})}updateThread(t,e){this.getThreadRepo().updateThread(t,{title:e.title});}async ensureThread(t,e,s){let n=this.getThreadRepo(),r=n.findThreadById(t);if(r){if(r.platform!==e)throw new Error(`Thread '${t}' already exists with platform '${r.platform}' \u2014 cannot change to '${e}' (platform is immutable)`);return {created:false}}return n.ensureThread(t,e,s),{created:true}}async fetchHistory(t,e){let s=e?.limit??100,n=this.getThreadRepo(),r=n.findThreadById(t),i=n.findTopLevelTasks(t),a=new Set(["done","completed","success"]);i=i.filter(m=>(!m.status||a.has(m.status))&&(!e?.currentTraceId||m.trace_id!==e.currentTraceId)),i=i.slice(0,s);let c=r?.platform??"cli",p=this.rowsToMessages(i);return {threadId:t,platform:c,messages:p,metadata:{title:r?.title??void 0,firstMessage:r?.first_message??void 0,lastMessage:r?.last_message??void 0,messageCount:r?.message_count??0,updatedAt:r?.updated_at?new Date(r.updated_at).getTime():void 0}}}async saveUserMessage(t,e,s,n){let{firstMessage:r}=this.getThreadRepo().saveUserMessage(t,e);return {id:t,firstMessage:r}}async saveAssistantMessage(t,e,s,n){return this.getThreadRepo().saveAssistantMessage(t,e),{id:t}}close(){}rowsToMessages(t){let e=[];for(let s of t){s.prompt&&e.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime()});let n=_e(s.result);n&&e.push({id:`${s.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:{agent_id:s.agent_id,task_id:s.id}});}return e}};var lt=class extends A{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new Z(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,e,s,n){}async afterAssistantMessage(t,e,s){}attach(t){this.unsubStart=t.on("task:start",async e=>{if(!e.threadId)return;let s=e.platform??"cli";try{let n=await this._provider.ensureThread(e.threadId,s,e.workspaceId),r=await this._provider.saveUserMessage(e.threadId,e.message??"");await this.afterUserMessage(e.threadId,r.id,n.created||r.firstMessage,e);}catch{}}),this.unsubEnd=t.on("task:end",async e=>{if(!e.result)return;let s=e.metadata?.threadId;if(!s)return;let n=e.agentRef?.replace(/^@/,"")??"";try{let{id:r}=await this._provider.saveAssistantMessage(s,e.result,n);await this.afterAssistantMessage(s,r,e);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=lt;exports.FileLoggerPlugin=et;exports.SqliteTracingPlugin=it;
|
|
@@ -39,6 +39,7 @@ export interface AcpProviderAdapter {
|
|
|
39
39
|
extractTextFromUpdate?(notification: SessionNotification): string | null;
|
|
40
40
|
extractUsage?(result: PromptResponse): ProviderUsage | null;
|
|
41
41
|
buildEffortAction?(effort: string, model?: string): AcpOptionAction | null;
|
|
42
|
+
buildSpawnEnv?(model: string): Record<string, string> | undefined;
|
|
42
43
|
resolveMode?(mode: string): string | null;
|
|
43
44
|
readonly yoloModeId?: string;
|
|
44
45
|
parseToolCall?(event: AcpToolCallEvent): AcpToolCallParsed | null;
|
package/dist/repository/index.js
CHANGED
|
@@ -7,7 +7,7 @@ ${n.join(`
|
|
|
7
7
|
ORDER BY t.updated_at DESC
|
|
8
8
|
LIMIT ${e.limit} OFFSET ${e.offset}`),total:s?.count??0}}catch(s){throw new d("DB_ERROR","Failed to find threads by project",s)}finally{n.close();}}findBySlug(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(h).where(drizzleOrm.eq(h.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?drizzleOrm.and(drizzleOrm.eq(h.slug,t),drizzleOrm.ne(h.id,e)):drizzleOrm.eq(h.slug,t);return !!n.db.select({id:h.id}).from(h).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(h).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.is_active,1),drizzleOrm.isNotNull(h.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;Lt.existsSync($.join(r,"crewx.yaml"))||Lt.existsSync($.join(r,"crewx.yml"))||(t.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(h).where(drizzleOrm.eq(h.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Ft=[h,i,c,F,v,P,G];function Re(){return $__namespace.default.join(Kt__default.default.homedir(),".crewx","crewx.db")}function Ee(a){if(!Lt__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Lt__default.default.copyFileSync(a,e),e}function Ht(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function xe(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function De(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=xe(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Se(a,t){let e=t?.dbPath??Re(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Ee(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=Ht(a);if(!s)try{X(a);}catch(m){let b=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!b.includes("duplicate column"))throw m}let l,u;s?(l=Ft.map(b=>sqliteCore.getTableConfig(b).name).filter(b=>!o.has(b)),u=o):(u=Ht(a),l=[...u].filter(m=>!o.has(m)));let p=[],f=[];for(let m of Ft){let b=sqliteCore.getTableConfig(m),D=b.name;if(!u.has(D))continue;let B=a.all(`PRAGMA table_info("${D}")`),L=new Set(B.map(N=>N.name)),J=new Set(b.columns.map(N=>N.name));for(let N of b.columns)if(!L.has(N.name)){if(!s){let lt=De(N);a.run(`ALTER TABLE "${D}" ADD COLUMN ${lt}`);}p.push({table:D,column:N.name});}for(let N of B)J.has(N.name)||f.push(`${D}.${N.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:p,warnings:f,backupPath:r}}var gt=class extends R{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=$.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=$.dirname(e);Lt.existsSync(s)||Lt.mkdirSync(s,{recursive:true});}else if(!Lt.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=w(e);if(t)try{T(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
9
9
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
10
|
-
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(drizzleOrm.desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=0;for(let s of e){let r=!1;
|
|
10
|
+
model=COALESCE(?, model) WHERE id=?`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(drizzleOrm.eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(drizzleOrm.desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,s.id),drizzleOrm.eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!Lt.existsSync(s))continue;let r=w(s);try{let o=e?drizzleOrm.eq(i.workspace_id,e):void 0,l=o?drizzleOrm.and(drizzleOrm.eq(i.id,t),o):drizzleOrm.eq(i.id,t),u=r.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let p=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),f=o?drizzleOrm.and(p,o):p;u=r.db.select().from(i).where(f).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!Lt.existsSync(o))continue;let l=w(o);try{let u=e?drizzleOrm.and(drizzleOrm.eq(i.parent_task_id,t),drizzleOrm.eq(i.workspace_id,e)):drizzleOrm.eq(i.parent_task_id,t),p=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let f of p)s.has(f.id)||(s.add(f.id),r.push(f));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
|
|
11
11
|
SELECT
|
|
12
12
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
13
13
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -4,5 +4,8 @@ export interface FormatConversationBlockContext {
|
|
|
4
4
|
messagesCount: number;
|
|
5
5
|
agentIds: string[];
|
|
6
6
|
primaryAgentId: string;
|
|
7
|
+
currentAgentId: string;
|
|
8
|
+
threadId: string;
|
|
9
|
+
now: string;
|
|
7
10
|
}
|
|
8
|
-
export declare function formatConversationHelper(this: any,
|
|
11
|
+
export declare function formatConversationHelper(this: any, ...args: any[]): string;
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1275,6 +1275,11 @@ export declare const CrewxProjectConfigSchema: z.ZodObject<{
|
|
|
1275
1275
|
documents: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
1276
1276
|
}, z.ZodUnknown, "strip">>;
|
|
1277
1277
|
export type CrewxProjectConfig = z.infer<typeof CrewxProjectConfigSchema>;
|
|
1278
|
+
export interface TraceContext {
|
|
1279
|
+
parentTaskId: string | null;
|
|
1280
|
+
rootTraceId: string;
|
|
1281
|
+
callerAgentId: string | null;
|
|
1282
|
+
}
|
|
1278
1283
|
export interface CrewxOptions {
|
|
1279
1284
|
workspaceRoot?: string;
|
|
1280
1285
|
platform?: Platform;
|
|
@@ -1301,6 +1306,7 @@ export interface QueryOptions {
|
|
|
1301
1306
|
messages?: import('../conversation/types').TemplateMessage[];
|
|
1302
1307
|
vars?: Record<string, unknown>;
|
|
1303
1308
|
cwd?: string;
|
|
1309
|
+
trace?: TraceContext;
|
|
1304
1310
|
}
|
|
1305
1311
|
export interface QueryResult {
|
|
1306
1312
|
ok: boolean;
|
|
@@ -1336,6 +1342,7 @@ export interface ExecuteOptions {
|
|
|
1336
1342
|
messages?: import('../conversation/types').TemplateMessage[];
|
|
1337
1343
|
vars?: Record<string, unknown>;
|
|
1338
1344
|
cwd?: string;
|
|
1345
|
+
trace?: TraceContext;
|
|
1339
1346
|
}
|
|
1340
1347
|
export interface ExecuteResult {
|
|
1341
1348
|
ok: boolean;
|
package/package.json
CHANGED
|
@@ -83,16 +83,22 @@ layouts:
|
|
|
83
83
|
|
|
84
84
|
{{#if agent.optionsByMode.query}}
|
|
85
85
|
<cli_options mode="query">
|
|
86
|
-
{{#each agent.optionsByMode.query}}
|
|
87
|
-
<item>
|
|
86
|
+
{{#each agent.optionsByMode.query.named}}
|
|
87
|
+
<item>provider="{{@key}}" {{{this}}}</item>
|
|
88
|
+
{{/each}}
|
|
89
|
+
{{#each agent.optionsByMode.query.rawArgs}}
|
|
90
|
+
<item>{{{this}}}</item>
|
|
88
91
|
{{/each}}
|
|
89
92
|
</cli_options>
|
|
90
93
|
{{/if}}
|
|
91
94
|
|
|
92
95
|
{{#if agent.optionsByMode.execute}}
|
|
93
96
|
<cli_options mode="execute">
|
|
94
|
-
{{#each agent.optionsByMode.execute}}
|
|
95
|
-
<item>
|
|
97
|
+
{{#each agent.optionsByMode.execute.named}}
|
|
98
|
+
<item>provider="{{@key}}" {{{this}}}</item>
|
|
99
|
+
{{/each}}
|
|
100
|
+
{{#each agent.optionsByMode.execute.rawArgs}}
|
|
101
|
+
<item>{{{this}}}</item>
|
|
96
102
|
{{/each}}
|
|
97
103
|
</cli_options>
|
|
98
104
|
{{/if}}
|
|
@@ -298,8 +304,15 @@ layouts:
|
|
|
298
304
|
|
|
299
305
|
{{#if props.showConversationHistory}}
|
|
300
306
|
{{#if messages.length}}
|
|
307
|
+
{{#if thread_id}}
|
|
308
|
+
<conversation_context thread_id="{{thread_id}}" agent_id="{{agent.id}}" now="{{now}}">
|
|
309
|
+
To review your previous work in this conversation:
|
|
310
|
+
crewx dreaming --thread={{thread_id}} --agent={{agent.id}} --continue
|
|
311
|
+
</conversation_context>
|
|
312
|
+
|
|
313
|
+
{{/if}}
|
|
301
314
|
<conversation_history platform="{{platform}}">
|
|
302
|
-
{{#formatConversation messages platform}}
|
|
315
|
+
{{#formatConversation messages platform agent.id thread_id}}
|
|
303
316
|
{{#if primaryAgentId}}
|
|
304
317
|
Primary agent: @{{primaryAgentId}}
|
|
305
318
|
{{/if}}
|
|
@@ -313,15 +326,17 @@ layouts:
|
|
|
313
326
|
{{/if}}
|
|
314
327
|
{{#each messages}}
|
|
315
328
|
{{#if isAssistant}}
|
|
316
|
-
|
|
329
|
+
<message role="assistant"{{#if metadata.agent_id}} agent="{{metadata.agent_id}}"{{/if}}{{#if ../currentAgentId}}{{#if (eq metadata.agent_id ../currentAgentId)}}{{#if metadata.task_id}} task_id="{{metadata.task_id}}"{{/if}}{{/if}}{{/if}}{{#if created_at}} created_at="{{created_at}}"{{/if}}{{#if relative_time}} relative_time="{{relative_time}}"{{/if}}{{#if metadata.slack}}{{#with metadata.slack}}{{#if bot_username}} name="{{bot_username}}"{{/if}}{{#if bot_user_id}} slack_user="{{bot_user_id}}"{{/if}}{{/with}}{{/if}}>
|
|
317
330
|
{{else}}
|
|
318
|
-
|
|
319
|
-
{{/if}}
|
|
331
|
+
<message role="user"{{#if created_at}} created_at="{{created_at}}"{{/if}}{{#if relative_time}} relative_time="{{relative_time}}"{{/if}}{{#if metadata.slack}}{{#with metadata.slack}}{{#if user_profile.display_name}} name="{{user_profile.display_name}}"{{else if username}} name="{{username}}"{{/if}}{{#if user_id}} slack_user="{{user_id}}"{{/if}}{{/with}}{{/if}}>
|
|
332
|
+
{{/if}}
|
|
333
|
+
{{{escapeHandlebars text}}}
|
|
320
334
|
{{#if files}}
|
|
321
335
|
{{#each files}}
|
|
322
336
|
📎 {{name}}{{#if size}} ({{formatFileSize size}}){{/if}}{{#if localPath}} - Local: {{localPath}}{{/if}}
|
|
323
337
|
{{/each}}
|
|
324
338
|
{{/if}}
|
|
339
|
+
</message>
|
|
325
340
|
{{/each}}
|
|
326
341
|
{{/formatConversation}}
|
|
327
342
|
|