@crewx/sdk 0.8.9-rc.30 → 0.8.9-rc.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js
CHANGED
|
@@ -20,7 +20,7 @@ import*as G from'path';import G__default,{join,resolve,dirname,isAbsolute,basena
|
|
|
20
20
|
|
|
21
21
|
`):s.length>0?s.join(`
|
|
22
22
|
|
|
23
|
-
`):i.length>0?i.join(""):a||n.trim()}function Is(n){let e=fe(n);return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0}:null}function Os(n,e,t=process.platform){return n==="copilot"&&t==="win32"&&e instanceof P&&e.message.includes('CLI command "copilot" not found')}function Sn(n,e,t,r,o,s,i){return new Promise((a,d)=>{let l=o?.timeoutMs??288e5,u=tt({command:n,allowShellFallback:true}),p=rt(u,e),h=spawn(p.command,p.argv,{env:{...process.env,...o?.env??{}},cwd:o?.cwd,stdio:["pipe","pipe","pipe"],shell:p.shell??false,windowsHide:p.windowsHide});s!==void 0&&h.stdin.write(s),h.stdin.end(),h.pid!==void 0&&o?.onPid?.(h.pid);let g=false,w=false,_=()=>{try{h.kill("SIGKILL");}catch{}},x=setTimeout(()=>{if(!g){w=true;try{h.kill("SIGTERM");}catch{}setTimeout(_,bn).unref();}},l);x.unref();let v=new StringDecoder("utf8"),k=new StringDecoder("utf8"),O="",b="",z="",q="";h.stdout.on("data",R=>{let H=v.write(R);O+=H,z+=H;let K=z.split(`
|
|
23
|
+
`):i.length>0?i.join(""):a||n.trim()}function Is(n){let e=fe(n);return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0}:null}function Os(n,e,t=process.platform){return n==="copilot"&&t==="win32"&&e instanceof P&&e.message.includes('CLI command "copilot" not found')}function Sn(n,e,t,r,o,s,i){return new Promise((a,d)=>{let l=o?.timeoutMs??288e5,u=tt({command:n,allowShellFallback:true}),p=rt(u,e),h=spawn(p.command,p.argv,{env:{...process.env,...o?.env??{}},cwd:o?.cwd,stdio:["pipe","pipe","pipe"],shell:p.shell??false,windowsHide:p.windowsHide,detached:process.platform!=="win32"});s!==void 0&&h.stdin.write(s),h.stdin.end(),h.pid!==void 0&&o?.onPid?.(h.pid);let g=false,w=false,_=()=>{try{h.kill("SIGKILL");}catch{}},x=setTimeout(()=>{if(!g){w=true;try{h.kill("SIGTERM");}catch{}setTimeout(_,bn).unref();}},l);x.unref();let v=new StringDecoder("utf8"),k=new StringDecoder("utf8"),O="",b="",z="",q="";h.stdout.on("data",R=>{let H=v.write(R);O+=H,z+=H;let K=z.split(`
|
|
24
24
|
`);z=K.pop()??"";for(let W of K)if(W.trim()&&(o?.onOutput?.(W,"stdout"),i?.extractFailure)){let V=i.extractFailure(W);if(V){g=true,clearTimeout(x);try{h.kill("SIGTERM");}catch{}setTimeout(_,bn).unref(),d(V);return}}}),h.stderr.on("data",R=>{let H=k.write(R);b+=H,q+=H;let K=q.split(`
|
|
25
25
|
`);q=K.pop()??"";for(let W of K)W.trim()&&o?.onOutput?.(W,"stderr");}),h.on("error",R=>{g=true,clearTimeout(x),R.code==="ENOENT"?d(new P(`CLI command "${n}" not found. Is ${t} installed?`,t)):d(new P(`Spawn error: ${R.message}`,t));}),h.on("close",R=>{if(g)return;g=true,clearTimeout(x);let H=v.end(),K=k.end();H&&(O+=H,z+=H),K&&(b+=K,q+=K),z.trim()&&o?.onOutput?.(z,"stdout"),q.trim()&&o?.onOutput?.(q,"stderr");let W=R??0;if(o?.onExitCode?.(W),w)return d(new be(`Total runtime exceeded ${l}ms; process killed.`,t));if(W!==0){if(i?.interpretExit){let B=i.interpretExit(W,b);if(B){d(B);return}}d(new P(`Process exited with code ${W}: ${b.slice(0,500)}`,t));return}let V;try{V=i?i.extractText(O):Ss(O);}catch(B){d(B instanceof Error?B:new P(String(B),t));return}a({stdout:O,parsed:V});});})}function ye(n,e){In.set(n,e);}function he(n){let e=n.split("/");if(e.length!==2)throw new P(`Invalid provider format: "${n}". Expected namespace/id (e.g., cli/claude)`,n);let[t,r]=e,o=In.get(t);if(o)return o(r,n);if(t==="cli"){let s=te[r];if(!s)throw new P(`Unknown CLI provider id: "${r}". Supported: ${Object.keys(te).join(", ")}`,n);return new fr(r,s,n)}throw new P(`Unsupported provider namespace: "${t}". Register a factory with registerProviderFactory('${t}', factory).`,n)}var bn,de,In,fr,ue=L(()=>{c();Mt();Ke();Ae();nt();nt();bn=2e3;de=class extends Error{constructor(t,r){super(`Client tool call required: ${t.toolName}`);this.toolCall=t;this.continuationState=r;}toolCall;continuationState;name="ClientToolCallRequiredError"},In=new Map;fr=class{constructor(e,t,r){this.providerId=e;this.adapter=t;this.providerStr=r;}providerId;adapter;providerStr;async execute(e,t){let r=this.composeMessage(e,t),{args:o,stdinMessage:s}=this.adapter.buildArgs(r,t??{},true);t?.onCommand?.(`${this.adapter.command} ${o.join(" ")}`);let{stdout:i,parsed:a}=await this.runProcess(o,t,s);return this.handleResultMeta(i,t),a}async query(e,t){let r=this.composeMessage(e,t),{args:o,stdinMessage:s}=this.adapter.buildArgs(r,t??{},false);t?.onCommand?.(`${this.adapter.command} ${o.join(" ")}`);let{stdout:i,parsed:a}=await this.runProcess(o,t,s);return this.handleResultMeta(i,t),a}composeMessage(e,t){return t?.systemPrompt?`${t.systemPrompt}
|
|
26
26
|
|
|
@@ -57,7 +57,7 @@ ${n??""}
|
|
|
57
57
|
${r.join(`
|
|
58
58
|
`)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ri(n,i),s?.cnt&&(Ci(n,o,t),Ti(n,o,t)),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let l=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${l} (${d} migration${d>1?"s":""} applied).`);}}function Ft(n,e){Vn.has(e)||(Pi(n),Vn.add(e));}c();var D=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};c();c();var Xn=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()});c();var m=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)},n=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));c();var Yn=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Xn.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id)}));c();var De=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>m.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>De.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));c();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>m.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()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));c();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>Yn.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()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));c();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")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));var Ue="2026-05-09",Vi="0.8.9-rc.13",je=10,He=parseInt(Vi.split("rc.")[1]),ft=class extends Xe{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new D("NOT_FOUND","Database not found");let r=xe(t);if(e)try{Ft(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(m).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoNothing().run();}catch(r){throw r instanceof D?r:new D("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
59
59
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
60
|
-
model=COALESCE(?, model) WHERE id
|
|
60
|
+
model=COALESCE(?, model) WHERE id=? AND status='running'`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id]);}catch(r){throw r instanceof D?r:new D("DB_ERROR","Failed to finish task",r)}finally{t.close();}}appendLog(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{let s=o.select({logs:m.logs}).from(m).where(eq(m.id,e)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(t),o.update(m).set({logs:JSON.stringify(i)}).where(eq(m.id,e)).run();},{behavior:"immediate"});}catch(o){throw o instanceof D?o:new D("DB_ERROR","Failed to append log",o)}finally{r.close();}}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(m).where(eq(m.status,"running")).orderBy(desc(m.started_at)).all()}catch(t){throw new D("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(m).orderBy(desc(m.started_at)).limit(100).all()}catch(t){throw new D("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(m).where(eq(m.id,e)).limit(1).get()??void 0}catch(r){throw new D("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:m.id,status:m.status,pid:m.pid}).from(m).where(eq(m.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(m).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(m.id,e),eq(m.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof D?r:new D("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:m.id,pid:m.pid}).from(m).where(eq(m.status,"running")).all(),r=0;for(let o of t){if(!o.pid)continue;let s=!1;try{process.kill(o.pid,0),s=!0;}catch{}s||(e.db.update(m).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(m.id,o.id),eq(m.status,"running"))).run(),r++);}return r}finally{e.close();}}findTaskStatus(e,t){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=xe(o);try{let i=t?eq(m.workspace_id,t):void 0,a=i?and(eq(m.id,e),i):eq(m.id,e),d=s.db.select().from(m).where(a).limit(1).get()??void 0;if(!d){let l=or$1(eq(m.thread_id,e),and(isNull(m.thread_id),like(m.command,`%--thread=${e}%`))),u=i?and(l,i):l;d=s.db.select().from(m).where(u).orderBy(desc(m.started_at)).limit(1).get()??void 0;}if(d)return d}catch(i){throw new D("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let a=xe(i);try{let d=t?and(eq(m.parent_task_id,e),eq(m.workspace_id,t)):eq(m.parent_task_id,e),l=a.db.select().from(m).where(d).orderBy(asc(m.started_at)).all();for(let u of l)o.has(u.id)||(o.add(u.id),s.push(u));}catch(d){throw new D("DB_ERROR","Failed to find child tasks",d)}finally{a.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?sql`
|
|
61
61
|
SELECT
|
|
62
62
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
63
63
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -12,7 +12,7 @@ Message: ${e.message}
|
|
|
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),zt(d,i),r?.cnt&&(jt(d,n,e),Wt(d,n,e)),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function Y(d,t){kt.has(t)||(Kt(d),kt.add(t));}var _=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 z=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)},d=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(d.agent_id),idx_tasks_status:index("idx_tasks_status").on(d.status),idx_tasks_started_at:index("idx_tasks_started_at").on(d.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(d.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(d.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(d.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(d.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(d.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(d.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(d.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(d.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(d.workspace_id,d.started_at)}));var u=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>z.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},d=>({idx_threads_updated_at:index("idx_threads_updated_at").on(d.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(d.workspace_id)}));var te=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(()=>te.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},d=>({idx_spans_task_id:index("idx_spans_task_id").on(d.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(d.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>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()},d=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(d.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(d.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(d.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>u.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},d=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(d.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(d.thread_id,d.seq),uniq_thread_boxes_thread_seq:unique().on(d.thread_id,d.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},d=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(d.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(d.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(d.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(d.partition_key)}));var U="2026-05-09",_e="0.8.9-rc.13",B=10,F=parseInt(_e.split("rc.")[1]),et=class extends H{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=dirname(e);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(e))throw new _("NOT_FOUND","Database not found");let s=T(e);if(t)try{Y(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 _?s:new _("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
|
|
15
|
+
model=COALESCE(?, model) WHERE id=? AND status='running'`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof _?s:new _("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(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(eq(o.id,t)).run();},{behavior:"immediate"});}catch(n){throw n instanceof _?n:new _("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(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(e){throw new _("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 _("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(s){throw new _("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(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(and(eq(o.id,t),eq(o.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof _?s:new _("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(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(and(eq(o.id,n.id),eq(o.status,"running"))).run(),s++);}return s}finally{t.close();}}findTaskStatus(t,e){let s=this.resolveDbPaths();for(let n of s){if(!existsSync(n))continue;let r=T(n);try{let i=e?eq(o.workspace_id,e):void 0,a=i?and(eq(o.id,t),i):eq(o.id,t),l=r.db.select().from(o).where(a).limit(1).get()??void 0;if(!l){let c=or(eq(o.thread_id,t),and(isNull(o.thread_id),like(o.command,`%--thread=${t}%`))),p=i?and(c,i):c;l=r.db.select().from(o).where(p).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(l)return l}catch(i){throw new _("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(!existsSync(i))continue;let a=T(i);try{let l=e?and(eq(o.parent_task_id,t),eq(o.workspace_id,e)):eq(o.parent_task_id,t),c=a.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let p of c)n.has(p.id)||(n.add(p.id),r.push(p));}catch(l){throw new _("DB_ERROR","Failed to find child tasks",l)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
16
16
|
SELECT
|
|
17
17
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
18
18
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -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(_).where(eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?and(eq(_.slug,t),ne(_.id,e)):eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(_).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(_).where(eq(_.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(and(eq(_.is_active,1),isNotNull(_.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(_.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Mt=[_,i,p,U,$,L,Q];function Ne(){return H__default.join(se.homedir(),".crewx","crewx.db")}function Ce(a){if(!zt.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return zt.copyFileSync(a,e),e}function qt(a){let t=a.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(t.map(e=>e.name))}function Le(a){return a==null||typeof a=="object"&&"queryChunks"in a?null:typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":typeof a=="string"?`'${a.replace(/'/g,"''")}'`:String(a)}function ve(a){let t=a.getSQLType(),e=`"${a.name}" ${t}`,n=Le(a.default);return n!==null&&(e+=` DEFAULT ${n}`),a.notNull&&(e+=" NOT NULL"),e}function Pe(a,t){let e=t?.dbPath??Ne(),n=t?.force??false,s=t?.dryRun??false,r=s?null:Ce(e);if(n&&!s)try{a.run("DELETE FROM __drizzle_migrations");}catch{}let o=qt(a);if(!s)try{J(a);}catch(m){let w=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!w.includes("duplicate column"))throw m}let l,u;s?(l=Mt.map(w=>getTableConfig(w).name).filter(w=>!o.has(w)),u=o):(u=qt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Mt){let w=getTableConfig(m),y=w.name;if(!u.has(y))continue;let q=a.all(`PRAGMA table_info("${y}")`),F=new Set(q.map(P=>P.name)),pt=new Set(w.columns.map(P=>P.name));for(let P of w.columns)if(!F.has(P.name)){if(!s){let _t=ve(P);a.run(`ALTER TABLE "${y}" ADD COLUMN ${_t}`);}c.push({table:y,column:P.name});}for(let P of q)pt.has(P.name)||h.push(`${y}.${P.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:r}}var G="2026-05-09",Ue="0.8.9-rc.13",Y=10,X=parseInt(Ue.split("rc.")[1]),yt=class extends T{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{O(n.db,e);}catch(s){throw n.close(),s}return n}startTask(t){let e=this.openHandle(true);try{e.db.insert(i).values({id:t.id,agent_id:t.agentId,prompt:t.prompt,mode:t.mode,status:t.status,started_at:t.startedAt,pid:t.pid??null,parent_task_id:t.parentTaskId??null,caller_agent_id:t.callerAgentId??null,trace_id:t.traceId??null,command:t.command??null,metadata:t.metadata??null,workspace_id:t.workspaceId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoNothing().run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{e.close();}}finishTask(t){let e=this.openHandle(true);try{e.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
9
9
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
10
|
-
model=COALESCE(?, model) WHERE id
|
|
10
|
+
model=COALESCE(?, model) WHERE id=? AND status='running'`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:i.logs}).from(i).where(eq(i.id,t)).limit(1).get(),o=r?.logs?JSON.parse(r.logs):[];o.push(e),s.update(i).set({logs:JSON.stringify(o)}).where(eq(i.id,t)).run();},{behavior:"immediate"});}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append log",s)}finally{n.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all()}catch(e){throw new d("DB_ERROR","Failed to get running tasks",e)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).orderBy(desc(i.started_at)).limit(100).all()}catch(e){throw new d("DB_ERROR","Failed to get all tasks",e)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let e=this.openHandle(false);try{return e.db.select().from(i).where(eq(i.id,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{e.close();}}killTask(t){if(!this.dbExists())return {killed:false};let e=this.openHandle(true);try{let n=e.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(eq(i.id,t)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return e.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(i.id,t),eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{e.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let e=t.db.select({id:i.id,pid:i.pid}).from(i).where(eq(i.status,"running")).all(),n=0;for(let s of e){if(!s.pid)continue;let r=!1;try{process.kill(s.pid,0),r=!0;}catch{}r||(t.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(i.id,s.id),eq(i.status,"running"))).run(),n++);}return n}finally{t.close();}}findTaskStatus(t,e){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let r=k(s);try{let o=e?eq(i.workspace_id,e):void 0,l=o?and(eq(i.id,t),o):eq(i.id,t),u=r.db.select().from(i).where(l).limit(1).get()??void 0;if(!u){let c=or(eq(i.thread_id,t),and(isNull(i.thread_id),like(i.command,`%--thread=${t}%`))),h=o?and(c,o):c;u=r.db.select().from(i).where(h).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(o){throw new d("DB_ERROR","Failed to find task status",o)}finally{r.close();}}}findChildTasks(t,e){let n=this.resolveDbPaths(),s=new Set,r=[];for(let o of n){if(!existsSync(o))continue;let l=k(o);try{let u=e?and(eq(i.parent_task_id,t),eq(i.workspace_id,e)):eq(i.parent_task_id,t),c=l.db.select().from(i).where(u).orderBy(asc(i.started_at)).all();for(let h of c)s.has(h.id)||(s.add(h.id),r.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?sql`
|
|
11
11
|
SELECT
|
|
12
12
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
13
13
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
package/dist/index.js
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
|
|
21
21
|
`):s.length>0?s.join(`
|
|
22
22
|
|
|
23
|
-
`):i.length>0?i.join(""):a||n.trim()}function Ts(n){let e=me(n);return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0}:null}function Cs(n,e,t=process.platform){return n==="copilot"&&t==="win32"&&e instanceof exports.ProviderError&&e.message.includes('CLI command "copilot" not found')}function Pn(n,e,t,r,o,s,i){return new Promise((a,d)=>{let l=o?.timeoutMs??288e5,u=et({command:n,allowShellFallback:true}),p=tt(u,e),y=child_process.spawn(p.command,p.argv,{env:{...process.env,...o?.env??{}},cwd:o?.cwd,stdio:["pipe","pipe","pipe"],shell:p.shell??false,windowsHide:p.windowsHide});s!==void 0&&y.stdin.write(s),y.stdin.end(),y.pid!==void 0&&o?.onPid?.(y.pid);let g=false,h=false,k=()=>{try{y.kill("SIGKILL");}catch{}},w=setTimeout(()=>{if(!g){h=true;try{y.kill("SIGTERM");}catch{}setTimeout(k,Cn).unref();}},l);w.unref();let _=new string_decoder.StringDecoder("utf8"),x=new string_decoder.StringDecoder("utf8"),I="",P="",W="",F="";y.stdout.on("data",A=>{let j=_.write(A);I+=j,W+=j;let z=W.split(`
|
|
23
|
+
`):i.length>0?i.join(""):a||n.trim()}function Ts(n){let e=me(n);return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0}:null}function Cs(n,e,t=process.platform){return n==="copilot"&&t==="win32"&&e instanceof exports.ProviderError&&e.message.includes('CLI command "copilot" not found')}function Pn(n,e,t,r,o,s,i){return new Promise((a,d)=>{let l=o?.timeoutMs??288e5,u=et({command:n,allowShellFallback:true}),p=tt(u,e),y=child_process.spawn(p.command,p.argv,{env:{...process.env,...o?.env??{}},cwd:o?.cwd,stdio:["pipe","pipe","pipe"],shell:p.shell??false,windowsHide:p.windowsHide,detached:process.platform!=="win32"});s!==void 0&&y.stdin.write(s),y.stdin.end(),y.pid!==void 0&&o?.onPid?.(y.pid);let g=false,h=false,k=()=>{try{y.kill("SIGKILL");}catch{}},w=setTimeout(()=>{if(!g){h=true;try{y.kill("SIGTERM");}catch{}setTimeout(k,Cn).unref();}},l);w.unref();let _=new string_decoder.StringDecoder("utf8"),x=new string_decoder.StringDecoder("utf8"),I="",P="",W="",F="";y.stdout.on("data",A=>{let j=_.write(A);I+=j,W+=j;let z=W.split(`
|
|
24
24
|
`);W=z.pop()??"";for(let B of z)if(B.trim()&&(o?.onOutput?.(B,"stdout"),i?.extractFailure)){let K=i.extractFailure(B);if(K){g=true,clearTimeout(w);try{y.kill("SIGTERM");}catch{}setTimeout(k,Cn).unref(),d(K);return}}}),y.stderr.on("data",A=>{let j=x.write(A);P+=j,F+=j;let z=F.split(`
|
|
25
25
|
`);F=z.pop()??"";for(let B of z)B.trim()&&o?.onOutput?.(B,"stderr");}),y.on("error",A=>{g=true,clearTimeout(w),A.code==="ENOENT"?d(new exports.ProviderError(`CLI command "${n}" not found. Is ${t} installed?`,t)):d(new exports.ProviderError(`Spawn error: ${A.message}`,t));}),y.on("close",A=>{if(g)return;g=true,clearTimeout(w);let j=_.end(),z=x.end();j&&(I+=j,W+=j),z&&(P+=z,F+=z),W.trim()&&o?.onOutput?.(W,"stdout"),F.trim()&&o?.onOutput?.(F,"stderr");let B=A??0;if(o?.onExitCode?.(B),h)return d(new Pe(`Total runtime exceeded ${l}ms; process killed.`,t));if(B!==0){if(i?.interpretExit){let q=i.interpretExit(B,P);if(q){d(q);return}}d(new exports.ProviderError(`Process exited with code ${B}: ${P.slice(0,500)}`,t));return}let K;try{K=i?i.extractText(I):Es(I);}catch(q){d(q instanceof Error?q:new exports.ProviderError(String(q),t));return}a({stdout:I,parsed:K});});})}function fe(n,e){bn.set(n,e);}function ye(n){let e=n.split("/");if(e.length!==2)throw new exports.ProviderError(`Invalid provider format: "${n}". Expected namespace/id (e.g., cli/claude)`,n);let[t,r]=e,o=bn.get(t);if(o)return o(r,n);if(t==="cli"){let s=exports.BUILTIN_ADAPTERS[r];if(!s)throw new exports.ProviderError(`Unknown CLI provider id: "${r}". Supported: ${Object.keys(exports.BUILTIN_ADAPTERS).join(", ")}`,n);return new mr(r,s,n)}throw new exports.ProviderError(`Unsupported provider namespace: "${t}". Register a factory with registerProviderFactory('${t}', factory).`,n)}var Cn;exports.ClientToolCallRequiredError=void 0;var bn,mr,ce=D(()=>{c();Ot();ze();ve();rt();rt();Cn=2e3;exports.ClientToolCallRequiredError=class extends Error{constructor(t,r){super(`Client tool call required: ${t.toolName}`);this.toolCall=t;this.continuationState=r;}toolCall;continuationState;name="ClientToolCallRequiredError"},bn=new Map;mr=class{constructor(e,t,r){this.providerId=e;this.adapter=t;this.providerStr=r;}providerId;adapter;providerStr;async execute(e,t){let r=this.composeMessage(e,t),{args:o,stdinMessage:s}=this.adapter.buildArgs(r,t??{},true);t?.onCommand?.(`${this.adapter.command} ${o.join(" ")}`);let{stdout:i,parsed:a}=await this.runProcess(o,t,s);return this.handleResultMeta(i,t),a}async query(e,t){let r=this.composeMessage(e,t),{args:o,stdinMessage:s}=this.adapter.buildArgs(r,t??{},false);t?.onCommand?.(`${this.adapter.command} ${o.join(" ")}`);let{stdout:i,parsed:a}=await this.runProcess(o,t,s);return this.handleResultMeta(i,t),a}composeMessage(e,t){return t?.systemPrompt?`${t.systemPrompt}
|
|
26
26
|
|
|
@@ -57,7 +57,7 @@ ${n??""}
|
|
|
57
57
|
${r.join(`
|
|
58
58
|
`)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),xi(n,i),s?.cnt&&(vi(n,o,t),_i(n,o,t)),e(n,{migrationsFolder:o});let d=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(d>0){let l=s?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${l} (${d} migration${d>1?"s":""} applied).`);}}function Ht(n,e){zn.has(e)||(Ai(n),zn.add(e));}c();var N=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};c();c();var Vn=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()});c();var m=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)},n=>({idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(n.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));c();var Xn=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Vn.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)},n=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(n.workspace_id)}));c();var Ne=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>m.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Ne.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")},n=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(n.parent_span_id)}));c();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>m.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()},n=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(n.timestamp)}));c();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>Xn.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()},n=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(n.thread_id,n.seq)}));c();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")},n=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(n.partition_key)}));var $e="2026-05-09",qi="0.8.9-rc.13",Ue=10,je=parseInt(qi.split("rc.")[1]),mt=class extends Ge{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=V.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=V.dirname(t);eo.existsSync(o)||eo.mkdirSync(o,{recursive:true});}else if(!eo.existsSync(t))throw new N("NOT_FOUND","Database not found");let r=we(t);if(e)try{Ht(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{t.db.insert(m).values({id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null}).onConflictDoNothing().run();}catch(r){throw r instanceof N?r:new N("DB_ERROR","Failed to start task",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
59
59
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
60
|
-
model=COALESCE(?, model) WHERE id
|
|
60
|
+
model=COALESCE(?, model) WHERE id=? AND status='running'`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id]);}catch(r){throw r instanceof N?r:new N("DB_ERROR","Failed to finish task",r)}finally{t.close();}}appendLog(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{let s=o.select({logs:m.logs}).from(m).where(drizzleOrm.eq(m.id,e)).limit(1).get(),i=s?.logs?JSON.parse(s.logs):[];i.push(t),o.update(m).set({logs:JSON.stringify(i)}).where(drizzleOrm.eq(m.id,e)).run();},{behavior:"immediate"});}catch(o){throw o instanceof N?o:new N("DB_ERROR","Failed to append log",o)}finally{r.close();}}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(m).where(drizzleOrm.eq(m.status,"running")).orderBy(drizzleOrm.desc(m.started_at)).all()}catch(t){throw new N("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(m).orderBy(drizzleOrm.desc(m.started_at)).limit(100).all()}catch(t){throw new N("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(m).where(drizzleOrm.eq(m.id,e)).limit(1).get()??void 0}catch(r){throw new N("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:m.id,status:m.status,pid:m.pid}).from(m).where(drizzleOrm.eq(m.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(m).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(m.id,e),drizzleOrm.eq(m.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof N?r:new N("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:m.id,pid:m.pid}).from(m).where(drizzleOrm.eq(m.status,"running")).all(),r=0;for(let o of t){if(!o.pid)continue;let s=!1;try{process.kill(o.pid,0),s=!0;}catch{}s||(e.db.update(m).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(m.id,o.id),drizzleOrm.eq(m.status,"running"))).run(),r++);}return r}finally{e.close();}}findTaskStatus(e,t){let r=this.resolveDbPaths();for(let o of r){if(!eo.existsSync(o))continue;let s=we(o);try{let i=t?drizzleOrm.eq(m.workspace_id,t):void 0,a=i?drizzleOrm.and(drizzleOrm.eq(m.id,e),i):drizzleOrm.eq(m.id,e),d=s.db.select().from(m).where(a).limit(1).get()??void 0;if(!d){let l=drizzleOrm.or(drizzleOrm.eq(m.thread_id,e),drizzleOrm.and(drizzleOrm.isNull(m.thread_id),drizzleOrm.like(m.command,`%--thread=${e}%`))),u=i?drizzleOrm.and(l,i):l;d=s.db.select().from(m).where(u).orderBy(drizzleOrm.desc(m.started_at)).limit(1).get()??void 0;}if(d)return d}catch(i){throw new N("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!eo.existsSync(i))continue;let a=we(i);try{let d=t?drizzleOrm.and(drizzleOrm.eq(m.parent_task_id,e),drizzleOrm.eq(m.workspace_id,t)):drizzleOrm.eq(m.parent_task_id,e),l=a.db.select().from(m).where(d).orderBy(drizzleOrm.asc(m.started_at)).all();for(let u of l)o.has(u.id)||(o.add(u.id),s.push(u));}catch(d){throw new N("DB_ERROR","Failed to find child tasks",d)}finally{a.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?drizzleOrm.sql`
|
|
61
61
|
SELECT
|
|
62
62
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
63
63
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
package/dist/plugins/index.js
CHANGED
|
@@ -12,7 +12,7 @@ Message: ${e.message}
|
|
|
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),Mt(d,i),r?.cnt&&(Ft(d,n,e),Bt(d,n,e)),t(d,{migrationsFolder:n});let l=(d.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=r?.cnt?"Database migrated":"Database initialized";console.log(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function X(d,t){gt.has(t)||(Ht(d),gt.add(t));}var _=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 H=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 u=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>H.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 Yt=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(()=>Yt.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(()=>u.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 M="2026-05-09",ae="0.8.9-rc.13",U=10,B=parseInt(ae.split("rc.")[1]),tt=class extends F{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=D.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let n=D.dirname(e);fs.existsSync(n)||fs.mkdirSync(n,{recursive:true});}else if(!fs.existsSync(e))throw new _("NOT_FOUND","Database not found");let s=S(e);if(t)try{X(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 _?s:new _("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
|
|
15
|
+
model=COALESCE(?, model) WHERE id=? AND status='running'`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(s){throw s instanceof _?s:new _("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 _?n:new _("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 _("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 _("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 _("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 _?s:new _("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=S(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),l=r.db.select().from(o).where(a).limit(1).get()??void 0;if(!l){let c=drizzleOrm.or(drizzleOrm.eq(o.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(o.thread_id),drizzleOrm.like(o.command,`%--thread=${t}%`))),p=i?drizzleOrm.and(c,i):c;l=r.db.select().from(o).where(p).orderBy(drizzleOrm.desc(o.started_at)).limit(1).get()??void 0;}if(l)return l}catch(i){throw new _("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=S(i);try{let l=e?drizzleOrm.and(drizzleOrm.eq(o.parent_task_id,t),drizzleOrm.eq(o.workspace_id,e)):drizzleOrm.eq(o.parent_task_id,t),c=a.db.select().from(o).where(l).orderBy(drizzleOrm.asc(o.started_at)).all();for(let p of c)n.has(p.id)||(n.add(p.id),r.push(p));}catch(l){throw new _("DB_ERROR","Failed to find child tasks",l)}finally{a.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
|
|
16
16
|
SELECT
|
|
17
17
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
18
18
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
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(_).where(drizzleOrm.eq(_.slug,t)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{e.close();}}slugExists(t,e){if(!this.dbExists())return false;let n=this.openHandle(false);try{let s=e?drizzleOrm.and(drizzleOrm.eq(_.slug,t),drizzleOrm.ne(_.id,e)):drizzleOrm.eq(_.slug,t);return !!n.db.select({id:_.id}).from(_).where(s).limit(1).get()}catch(s){throw new d("DB_ERROR","Failed to check slug",s)}finally{n.close();}}insert(t,e,n,s){let r=this.openHandle(true);try{let o=new Date().toISOString();r.db.insert(_).values({id:t,slug:e,name:n,workspace_path:s,is_active:1,created_at:o,updated_at:o}).run();let l=r.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(!l)throw new d("DB_ERROR","Insert did not return a row");return l}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to insert workspace",o)}finally{r.close();}}update(t,e,n){let s=this.openHandle(true);try{s.runRaw(`UPDATE workspaces SET ${e.join(", ")} WHERE id = ?`,n);let r=s.db.select().from(_).where(drizzleOrm.eq(_.id,t)).limit(1).get();if(!r)throw new d("NOT_FOUND",`Workspace ${t} not found`);return r}catch(r){throw r instanceof d?r:new d("DB_ERROR","Failed to update workspace",r)}finally{s.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let t=this.openHandle(true);try{let e=t.db.select({id:_.id,workspace_path:_.workspace_path}).from(_).where(drizzleOrm.and(drizzleOrm.eq(_.is_active,1),drizzleOrm.isNotNull(_.workspace_path))).all(),n=0;for(let s of e){let r=s.workspace_path;Ht.existsSync(I.join(r,"crewx.yaml"))||Ht.existsSync(I.join(r,"crewx.yml"))||(t.db.update(_).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(_.id,s.id)).run(),n+=1);}return {softDeleted:n,checked:e.length}}catch(e){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",e)}finally{t.close();}}delete(t){let e=this.openHandle(true);try{e.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${t}`),e.db.delete(_).where(drizzleOrm.eq(_.id,t)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{e.close();}}};var Ut=[_,i,p,z,P,C,V];function Te(){return I__namespace.default.join(Qt__default.default.homedir(),".crewx","crewx.db")}function De(a){if(!Ht__default.default.existsSync(a))return null;let t=Math.floor(Date.now()/1e3),e=`${a}.bak-${t}`;return Ht__default.default.copyFileSync(a,e),e}function Mt(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 Oe(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 Ae(a,t){let e=t?.dbPath??Te(),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 o=Mt(a);if(!s)try{X(a);}catch(m){let w=m instanceof Error?`${m.message} ${m.cause?.message??""}`:"";if(!n||!w.includes("duplicate column"))throw m}let l,u;s?(l=Ut.map(w=>sqliteCore.getTableConfig(w).name).filter(w=>!o.has(w)),u=o):(u=Mt(a),l=[...u].filter(m=>!o.has(m)));let c=[],h=[];for(let m of Ut){let w=sqliteCore.getTableConfig(m),R=w.name;if(!u.has(R))continue;let M=a.all(`PRAGMA table_info("${R}")`),q=new Set(M.map(v=>v.name)),ut=new Set(w.columns.map(v=>v.name));for(let v of w.columns)if(!q.has(v.name)){if(!s){let pt=Oe(v);a.run(`ALTER TABLE "${R}" ADD COLUMN ${pt}`);}c.push({table:R,column:v.name});}for(let v of M)ut.has(v.name)||h.push(`${R}.${v.name} exists in DB but not in schema (untouched)`);}return {created:l,altered:c,warnings:h,backupPath:r}}var K="2026-05-09",$e="0.8.9-rc.13",G=10,Y=parseInt($e.split("rc.")[1]),Rt=class extends S{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=I.join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=I.dirname(e);Ht.existsSync(s)||Ht.mkdirSync(s,{recursive:true});}else if(!Ht.existsSync(e))throw new d("NOT_FOUND","Database not found");let n=k(e);if(t)try{x(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
|
|
10
|
+
model=COALESCE(?, model) WHERE id=? AND status='running'`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{e.close();}}appendLog(t,e){let n=this.openHandle(true);try{n.db.transaction(s=>{let r=s.select({logs:i.logs}).from(i).where(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(!Ht.existsSync(s))continue;let r=k(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 c=drizzleOrm.or(drizzleOrm.eq(i.thread_id,t),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${t}%`))),h=o?drizzleOrm.and(c,o):c;u=r.db.select().from(i).where(h).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(!Ht.existsSync(o))continue;let l=k(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),c=l.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let h of c)s.has(h.id)||(s.add(h.id),r.push(h));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{l.close();}}return r}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.all(t?drizzleOrm.sql`
|
|
11
11
|
SELECT
|
|
12
12
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
13
13
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|