@crewx/sdk 0.9.0-rc.61 → 0.9.0-rc.63
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 +92 -92
- package/dist/esm/plugins/index.js +37 -37
- package/dist/esm/repository/index.js +85 -85
- package/dist/events/types.d.ts +1 -0
- package/dist/index.browser.js +2 -2
- package/dist/index.js +93 -93
- package/dist/migrations/0015_panoramic_gorilla_man.sql +71 -0
- package/dist/migrations/meta/0015_snapshot.json +2315 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.js +34 -34
- package/dist/repository/index.d.ts +2 -0
- package/dist/repository/index.js +85 -85
- package/dist/repository/project.repository.d.ts +88 -0
- package/dist/repository/task.repository.d.ts +2 -0
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/projects.d.ts +610 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/utils/id.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as V from'path';import V__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import Re,{homedir}from'os';import {createHash}from'crypto';import {sql,eq,desc,and,isNull,lt as lt$1,or,notLike,like,asc,inArray,gte,isNotNull,ne}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique,uniqueIndex,primaryKey,check}from'drizzle-orm/sqlite-core';var wt=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var fe=()=>fileURLToPath(import.meta.url),ge=()=>V__default.dirname(fe()),k=ge();var et=class{detach(t){}};function Ft(o){let t=n=>String(n).padStart(2,"0");return `${o.getFullYear()}${t(o.getMonth()+1)}${t(o.getDate())}T${t(o.getHours())}${t(o.getMinutes())}${t(o.getSeconds())}`}function $t(o){let t=o.toISOString();return `${t.slice(0,10)} ${t.slice(11,19)} UTC`}var Dt=class extends et{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(t){super(),this.logsDir=join(t?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=t?.version??"unknown";}attach(t){this.unsubs.push(t.on("task:start",n=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let s=Ft(n.timestamp),r=join(this.logsDir,`${s}_${n.traceId}.log`);this.logFiles.set(n.traceId,r);let i=`=== TASK LOG: ${n.traceId} ===
|
|
2
2
|
CrewX Version: ${this.version}
|
|
3
3
|
Mode: ${n.mode}
|
|
4
4
|
Agent: ${n.agentRef}
|
|
5
|
-
Started: ${
|
|
5
|
+
Started: ${$t(n.timestamp)}
|
|
6
6
|
Message: ${n.message}
|
|
7
7
|
|
|
8
8
|
`;writeFileSync(r,i,{encoding:"utf8",mode:384});}catch{}}),t.on("task:output",n=>{try{let s=this.logFiles.get(n.traceId);if(!s)return;let r=new Date().toISOString();appendFileSync(s,`[${r}] STDOUT: ${n.output}
|
|
9
|
-
`,"utf8");}catch{}}),t.on("task:end",n=>{try{let s=this.logFiles.get(n.traceId);if(!s)return;let r
|
|
9
|
+
`,"utf8");}catch{}}),t.on("task:end",n=>{try{let s=this.logFiles.get(n.traceId);if(!s)return;let r=$t(new Date),i=n.error?`failed: ${n.error.message}`:"completed successfully",a=`[${r}] INFO: Task ${i} in ${n.durationMs}ms
|
|
10
10
|
[${r}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
11
|
-
`;appendFileSync(s,a,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(t){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};function
|
|
11
|
+
`;appendFileSync(s,a,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(t){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};function ye(o){let t=V.resolve(o);return process.platform==="win32"&&(t=t.replace(/\\/g,"/"),t=t.replace(/^([A-Z]):/,(n,s)=>`${s.toLowerCase()}:`)),t.length>1&&!/^[a-zA-Z]:\/$/.test(t)&&(t=t.replace(/\/+$/,"")),t}function Gt(o){let t=ye(o);return createHash("sha256").update(t).digest("hex")}var lt=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Re.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(t){return t instanceof Error&&/no such table:/i.test(t.message)}dbExists(t){return existsSync(t??this.resolveDbPath())}};function x(o){let t=wt("better-sqlite3"),{drizzle:n}=wt("drizzle-orm/better-sqlite3"),s=new t(o);return s.exec("PRAGMA journal_mode = WAL"),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400"),s.exec("PRAGMA optimize"),{db:n(s),runRaw:(r,i=[])=>s.prepare(r).run(...i),close:()=>s.close()}}var Jt=new Set,xe={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 Ot(o,t){return (o.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${t}'`)?.cnt??0)>0}function Ne(o,t){if(t>0||!Ot(o,"tasks"))return;let n=o.all("PRAGMA table_info(tasks)"),s=new Set(n.map(r=>r.name));for(let[r,i]of Object.entries(xe))s.has(r)||o.run(`ALTER TABLE tasks ADD COLUMN ${r} ${i}`);}var Ae={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"}};function be(o,t,n){if(!Ot(o,"__drizzle_migrations")||!Ot(o,"tasks"))return;let s=o.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(s.map(a=>a.hash)),i=JSON.parse(readFileSync(V__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of i.entries){let d=Ae[a.tag];if(!d)continue;let u=V__default.join(t,`${a.tag}.sql`);if(!existsSync(u))continue;let c=readFileSync(u,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(r.has(l))continue;let h=o.all("PRAGMA table_info(tasks)"),m=new Set(h.map(w=>w.name));for(let[w,O]of Object.entries(d))m.has(w)||(o.run(`ALTER TABLE tasks ADD COLUMN ${w} ${O}`),m.add(w));}}function Ce(o,t,n){let s=o.all(n`SELECT hash FROM __drizzle_migrations`),r=new Set(s.map(a=>a.hash)),i=JSON.parse(readFileSync(V__default.join(t,"meta/_journal.json"),"utf-8"));for(let a of i.entries){let d=V__default.join(t,`${a.tag}.sql`);if(!existsSync(d))continue;let u=readFileSync(d,"utf-8"),c=createHash("sha256").update(u).digest("hex");if(r.has(c))continue;let l=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,h=[],m;for(;(m=l.exec(u))!==null;)h.push({table:m[1],column:m[2]});if(h.length===0||!u.split(/-->\s*statement-breakpoint/).map(I=>I.trim()).filter(Boolean).every(I=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(I)))continue;h.every(({table:I,column:B})=>o.all(`PRAGMA table_info("${I}")`).some(Y=>Y.name===B))&&o.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${a.when})`);}}function ve(o){let{migrate:t}=wt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=wt("drizzle-orm"),s=[V__default.join(k,"../migrations"),V__default.join(k,"migrations"),V__default.join(k,"../../../../drizzle/migrations"),V__default.join(process.cwd(),"drizzle/migrations")],r=s.find(c=>existsSync(V__default.join(c,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
|
|
12
12
|
${s.join(`
|
|
13
|
-
`)}`);let i=o.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;i?.cnt&&(a=o.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),we(o,a),i?.cnt&&(Te(o,r,n),Se(o,r,n)),t(o,{migrationsFolder:r});let u=(o.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(u>0){let c=i?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function kt(o,t){jt.has(t)||(Re(o),jt.add(t));}var p=class extends Error{code;cause;constructor(t,n,s){super(n),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var ct=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 e=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},o=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(o.agent_id),idx_tasks_status:index("idx_tasks_status").on(o.status),idx_tasks_started_at:index("idx_tasks_started_at").on(o.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(o.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(o.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(o.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(o.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(o.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(o.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(o.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(o.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(o.workspace_id,o.started_at)}));var _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>ct.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)},o=>({idx_threads_updated_at:index("idx_threads_updated_at").on(o.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(o.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(o.workspace_id,o.updated_at),idx_threads_title:index("idx_threads_title").on(o.title)}));var Oe=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Oe.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")},o=>({idx_spans_task_id:index("idx_spans_task_id").on(o.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(o.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.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()},o=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(o.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(o.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(o.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},o=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(o.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(o.thread_id,o.seq),uniq_thread_boxes_thread_seq:unique().on(o.thread_id,o.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")},o=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(o.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(o.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(o.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(o.partition_key)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},o=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(o.provider,o.account_ref,o.limit_window,o.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(o.limit_window,o.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(o.provider,o.limit_window,o.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},o=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(o.workspace_id,o.month)}));sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},o=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(o.workspace_id,sql`${o.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},o=>({pk:primaryKey({columns:[o.notification_id,o.user_id]})}));sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},o=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(o.workspace_id,o.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(o.workspace_id,o.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},o=>({idCheck:check("ui_instances_id_ck",sql`length(${o.id}) BETWEEN 5 AND 128 AND ${o.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${o.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${o.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${o.definition_hash}) = 64 AND ${o.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${o.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${o.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${o.domain_ref_json}) AND json_type(${o.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${o.state_json}) AND json_type(${o.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${o.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${o.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${o.granted_capabilities_json}) AND json_type(${o.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${o.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${o.updated_at} >= ${o.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(o.workspace_id,o.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},o=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${o.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${o.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${o.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${o.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${o.actor_json}) AND json_type(${o.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${o.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${o.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${o.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${o.after_revision} IS NULL OR ${o.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${o.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${o.outcome} IS NULL OR ${o.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${o.input_json}) AND json_type(${o.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${o.result_json} IS NULL OR (json_valid(${o.result_json}) AND json_type(${o.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${o.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${o.settled_at} IS NULL OR ${o.settled_at} >= ${o.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
13
|
+
`)}`);let i=o.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;i?.cnt&&(a=o.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ne(o,a),i?.cnt&&(Ce(o,r,n),be(o,r,n)),t(o,{migrationsFolder:r});let u=(o.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(u>0){let c=i?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function yt(o,t){Jt.has(t)||(ve(o),Jt.add(t));}var p=class extends Error{code;cause;constructor(t,n,s){super(n),this.name="RepositoryError",this.code=t,this.cause=s,Object.setPrototypeOf(this,new.target.prototype);}};var _t=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 e=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},o=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(o.agent_id),idx_tasks_status:index("idx_tasks_status").on(o.status),idx_tasks_started_at:index("idx_tasks_started_at").on(o.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(o.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(o.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(o.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(o.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(o.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(o.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(o.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(o.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(o.workspace_id,o.started_at)}));var _=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>_t.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)},o=>({idx_threads_updated_at:index("idx_threads_updated_at").on(o.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(o.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(o.workspace_id,o.updated_at),idx_threads_title:index("idx_threads_title").on(o.title)}));var je=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>je.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")},o=>({idx_spans_task_id:index("idx_spans_task_id").on(o.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(o.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>e.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()},o=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(o.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(o.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(o.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},o=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(o.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(o.thread_id,o.seq),uniq_thread_boxes_thread_seq:unique().on(o.thread_id,o.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")},o=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(o.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(o.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(o.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(o.partition_key)}));sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},o=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(o.provider,o.account_ref,o.limit_window,o.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(o.limit_window,o.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(o.provider,o.limit_window,o.bucket_start)}));sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},o=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(o.workspace_id,o.month)}));sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},o=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(o.workspace_id,sql`${o.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},o=>({pk:primaryKey({columns:[o.notification_id,o.user_id]})}));sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},o=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(o.workspace_id,o.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(o.workspace_id,o.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},o=>({idCheck:check("ui_instances_id_ck",sql`length(${o.id}) BETWEEN 5 AND 128 AND ${o.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${o.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${o.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${o.definition_hash}) = 64 AND ${o.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${o.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${o.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${o.domain_ref_json}) AND json_type(${o.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${o.state_json}) AND json_type(${o.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${o.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${o.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${o.granted_capabilities_json}) AND json_type(${o.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${o.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${o.updated_at} >= ${o.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(o.workspace_id,o.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},o=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${o.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${o.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${o.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${o.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${o.actor_json}) AND json_type(${o.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${o.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${o.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${o.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${o.after_revision} IS NULL OR ${o.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${o.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${o.outcome} IS NULL OR ${o.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${o.input_json}) AND json_type(${o.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${o.result_json} IS NULL OR (json_valid(${o.result_json}) AND json_type(${o.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${o.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${o.settled_at} IS NULL OR ${o.settled_at} >= ${o.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
14
14
|
(${o.status} = 'requested' AND ${o.after_revision} IS NULL AND ${o.outcome} IS NULL AND ${o.settled_at} IS NULL)
|
|
15
15
|
OR
|
|
16
16
|
(${o.status} = 'settled' AND ${o.after_revision} IS NOT NULL AND ${o.outcome} IS NOT NULL AND ${o.settled_at} IS NOT NULL)
|
|
17
|
-
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(o.instance_id,o.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(o.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(o.requested_at)}));function
|
|
17
|
+
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(o.instance_id,o.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(o.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(o.requested_at)}));var oe=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},o=>({idCheck:check("projects_id_ck",sql`${o.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${o.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${o.stages_json}) AND json_type(${o.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${o.stage_index} >= 1`)}));sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>oe.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},o=>({idCheck:check("project_criteria_id_ck",sql`${o.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${o.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${o.evidence_json}) AND json_type(${o.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(o.project_id,o.position)}));sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>oe.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},o=>({idCheck:check("project_events_id_ck",sql`${o.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${o.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${o.payload_json}) AND json_type(${o.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(o.project_id,o.seq)}));function ie(o){let t=o.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let n=t.lastIndexOf("/");return n>=0&&(t=t.slice(n+1)),t=t.replace(/-\d{8}$/,""),t}var rt="2026-05-09",pn="0.8.9-rc.13",ot=10,it=parseInt(pn.split("rc.")[1]);function ae(){let o=sql`
|
|
18
18
|
CASE
|
|
19
19
|
WHEN ${e.model} LIKE 'claude-%' OR ${e.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
20
20
|
WHEN ${e.model} LIKE 'gpt-%' OR ${e.model} LIKE 'codex-%' THEN 'codex'
|
|
@@ -43,10 +43,10 @@ ${s.join(`
|
|
|
43
43
|
WHEN trim(${r}) = '' THEN 'unknown'
|
|
44
44
|
ELSE ${r}
|
|
45
45
|
END
|
|
46
|
-
`}var
|
|
46
|
+
`}var hn=new Set(["workflow","mcp"]),de=600*1e3,bt=class extends lt{dbPath;pidNullObservedSince=new Map;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let s=x(n);if(t)try{yt(s.db,n);}catch(r){throw s.close(),r}return s}startTask(t){let n=this.openHandle(true);try{n.db.insert(e).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,project_id:t.projectId??null,platform:t.platform??"cli",crewx_version:t.crewxVersion??null,thread_id:t.threadId??null,model:t.model??null,rendered_prompt:t.renderedPrompt??null,coding_agent_command:t.codingAgentCommand??null}).onConflictDoUpdate({target:e.id,set:{pid:sql`COALESCE(excluded.pid, ${e.pid})`},setWhere:eq(e.status,"running")}).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to start task",s)}finally{n.close();}}listTasksByProjectId(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(e).where(eq(e.project_id,t)).orderBy(desc(e.started_at)).all()}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to list tasks by project",s)}finally{n.close();}}finishTask(t){let n=this.openHandle(true);try{let s=t.runEpoch??null;n.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
47
47
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
48
48
|
model=COALESCE(?, model)
|
|
49
|
-
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,s]);}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to finish task",s)}finally{n.close();}}appendLog(t,n){let s=this.openHandle(true);try{s.db.transaction(r=>{let i=r.select({logs:e.logs}).from(e).where(eq(e.id,t)).limit(1).get(),a=i?.logs?JSON.parse(i.logs):[];a.push(n),r.update(e).set({logs:JSON.stringify(a)}).where(eq(e.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to append log",r)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(e).where(eq(e.status,"running")).orderBy(desc(e.started_at)).all()}catch(n){throw new p("DB_ERROR","Failed to get running tasks",n)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(e).orderBy(desc(e.started_at)).limit(100).all()}catch(n){throw new p("DB_ERROR","Failed to get all tasks",n)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(e).where(eq(e.id,t)).limit(1).get()??void 0}catch(s){throw new p("DB_ERROR","Failed to get task",s)}finally{n.close();}}killTask(t){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let s=n.db.select({id:e.id,status:e.status,pid:e.pid}).from(e).where(eq(e.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return n.db.update(e).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(e.id,t),eq(e.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to kill task",s)}finally{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=t.db.select({id:e.id,pid:e.pid,platform:e.platform,run_epoch:e.run_epoch}).from(e).where(eq(e.status,"running")).all(),s=Date.now(),r=new Set,i=0;for(let a of n){if(a.pid){let c=!1;try{process.kill(a.pid,0),c=!0;}catch{}c||(t.db.update(e).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(e.id,a.id),eq(e.status,"running"))).run(),i++);continue}if(
|
|
49
|
+
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[t.status,t.result??null,t.error??null,t.completedAt,t.durationMs??null,t.exitCode??null,t.inputTokens??0,t.outputTokens??0,t.cachedInputTokens??0,t.costUsd??0,t.model??null,t.id,s]);}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to finish task",s)}finally{n.close();}}appendLog(t,n){let s=this.openHandle(true);try{s.db.transaction(r=>{let i=r.select({logs:e.logs}).from(e).where(eq(e.id,t)).limit(1).get(),a=i?.logs?JSON.parse(i.logs):[];a.push(n),r.update(e).set({logs:JSON.stringify(a)}).where(eq(e.id,t)).run();},{behavior:"immediate"});}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to append log",r)}finally{s.close();}}getRunningTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(e).where(eq(e.status,"running")).orderBy(desc(e.started_at)).all()}catch(n){throw new p("DB_ERROR","Failed to get running tasks",n)}finally{t.close();}}getAllTasks(){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(e).orderBy(desc(e.started_at)).limit(100).all()}catch(n){throw new p("DB_ERROR","Failed to get all tasks",n)}finally{t.close();}}getTask(t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(e).where(eq(e.id,t)).limit(1).get()??void 0}catch(s){throw new p("DB_ERROR","Failed to get task",s)}finally{n.close();}}killTask(t){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let s=n.db.select({id:e.id,status:e.status,pid:e.pid}).from(e).where(eq(e.id,t)).limit(1).get();if(!s||s.status!=="running")return {killed:!1};if(s.pid)try{process.kill(s.pid,"SIGTERM");}catch{}return n.db.update(e).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(e.id,t),eq(e.status,"running"))).run(),{killed:!0,pid:s.pid??void 0}}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to kill task",s)}finally{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=t.db.select({id:e.id,pid:e.pid,platform:e.platform,run_epoch:e.run_epoch}).from(e).where(eq(e.status,"running")).all(),s=Date.now(),r=new Set,i=0;for(let a of n){if(a.pid){let c=!1;try{process.kill(a.pid,0),c=!0;}catch{}c||(t.db.update(e).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(e.id,a.id),eq(e.status,"running"))).run(),i++);continue}if(hn.has(a.platform??"cli"))continue;let d=`${a.id}:${a.run_epoch??0}`;r.add(d);let u=this.pidNullObservedSince.get(d);if(u===void 0){this.pidNullObservedSince.set(d,s);continue}s-u>=de&&(t.db.update(e).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(e.id,a.id),eq(e.status,"running"))).run(),i++,this.pidNullObservedSince.delete(d));}for(let a of Array.from(this.pidNullObservedSince.keys()))r.has(a)||this.pidNullObservedSince.delete(a);return i}finally{t.close();}}reapRunningWorkflowTasks(t=de){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let s=new Date(Date.now()-t).toISOString();return n.db.update(e).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(e.status,"running"),eq(e.platform,"workflow"),isNull(e.pid),lt$1(e.started_at,s),or(isNull(e.metadata),and(notLike(e.metadata,'%"kind":"workflow_card"%'),notLike(e.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{n.close();}}findTaskStatus(t,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=x(r);try{let a=n?eq(e.workspace_id,n):void 0,d=a?and(eq(e.id,t),a):eq(e.id,t),u=i.db.select().from(e).where(d).limit(1).get()??void 0;if(!u){let c=or(eq(e.thread_id,t),and(isNull(e.thread_id),like(e.command,`%--thread=${t}%`))),l=a?and(c,a):c;u=i.db.select().from(e).where(l).orderBy(desc(e.started_at)).limit(1).get()??void 0;}if(u)return u}catch(a){throw new p("DB_ERROR","Failed to find task status",a)}finally{i.close();}}}findChildTasks(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=n?and(eq(e.parent_task_id,t),eq(e.workspace_id,n)):eq(e.parent_task_id,t),c=d.db.select().from(e).where(u).orderBy(asc(e.started_at)).all();for(let l of c)r.has(l.id)||(r.add(l.id),i.push(l));}catch(u){throw new p("DB_ERROR","Failed to find child tasks",u)}finally{d.close();}}return i}getWorkspaceUsageSummary(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(t?sql`
|
|
50
50
|
SELECT
|
|
51
51
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
52
52
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -67,7 +67,7 @@ ${s.join(`
|
|
|
67
67
|
FROM tasks
|
|
68
68
|
GROUP BY workspace_id
|
|
69
69
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
70
|
-
`)}catch(s){throw new p("DB_ERROR","Failed to get workspace usage summary",s)}finally{n.close();}}getThreadTokenUsage(t,n){let s=this.resolveDbPaths(),r=new Set,i=0,a=0,d=0;for(let u of s){if(!existsSync(u))continue;let c=
|
|
70
|
+
`)}catch(s){throw new p("DB_ERROR","Failed to get workspace usage summary",s)}finally{n.close();}}getThreadTokenUsage(t,n){let s=this.resolveDbPaths(),r=new Set,i=0,a=0,d=0;for(let u of s){if(!existsSync(u))continue;let c=x(u);try{let l=or(eq(e.thread_id,t),and(isNull(e.thread_id),like(e.command,`%--thread=${t}%`))),h=n?and(l,eq(e.workspace_id,n)):l,m=c.db.select({id:e.id,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cost_usd:e.cost_usd}).from(e).where(h).all();for(let w of m)r.has(w.id)||(r.add(w.id),i+=w.input_tokens??0,a+=w.output_tokens??0,d+=w.cost_usd??0);}catch(l){throw new p("DB_ERROR","Failed to get thread token usage",l)}finally{c.close();}}return {inputTokens:i,outputTokens:a,costUsd:d}}findTasksByThread(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=or(eq(e.thread_id,t),and(isNull(e.thread_id),like(e.command,`%--thread=${t}%`))),c=n?and(u,eq(e.workspace_id,n)):u,l=d.db.select().from(e).where(c).orderBy(asc(e.started_at)).all();for(let h of l)r.has(h.id)||(r.add(h.id),i.push(h));}catch(u){throw new p("DB_ERROR","Failed to find tasks by thread",u)}finally{d.close();}}return i}parseWorkflowCardMetadata(t){if(!t)return {};try{let n=JSON.parse(t);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(t){return t?/--thread=(\S+)/.exec(t)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let t=[];for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let s=x(n);try{t.push(...s.db.select({id:e.id,agent_id:e.agent_id,thread_id:e.thread_id,workspace_id:e.workspace_id,platform:e.platform,status:e.status,error:e.error,completed_at:e.completed_at,duration_ms:e.duration_ms,started_at:e.started_at,metadata:e.metadata}).from(e).where(and(eq(e.platform,"workflow"),or(like(e.metadata,'%"kind":"workflow_card"%'),like(e.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(e.started_at)).all());}catch(r){throw new p("DB_ERROR","Failed to find workflow parent tasks",r)}finally{s.close();}}return t}batchFetchWorkflowCards(t,n){let s=new Map;if(t.length===0)return s;let r=new Set(t),i=new Map,a=n?eq(e.workspace_id,n):void 0,d=(u,c)=>{if(!u)return;let l=i.get(u);if(l&&c.started_at<=l)return;let h=this.parseWorkflowCardMetadata(c.metadata);h.kind!=="workflow_card"&&h.kind!=="workflow_ui_instance"||(i.set(u,c.started_at),s.set(u,{taskId:c.id,workflowRunId:h.workflowRunId,raw:c.result??void 0}));};for(let u of this.resolveDbPaths()){if(!existsSync(u))continue;let c=x(u);try{let l=and(inArray(e.thread_id,t),or(like(e.metadata,'%"kind":"workflow_card"%'),like(e.metadata,'%"kind":"workflow_ui_instance"%'))),h=c.db.select({id:e.id,thread_id:e.thread_id,metadata:e.metadata,result:e.result,started_at:e.started_at}).from(e).where(a?and(l,a):l).all();for(let O of h)d(O.thread_id,O);let m=and(isNull(e.thread_id),or(like(e.metadata,'%"kind":"workflow_card"%'),like(e.metadata,'%"kind":"workflow_ui_instance"%'))),w=c.db.select({id:e.id,command:e.command,metadata:e.metadata,result:e.result,started_at:e.started_at}).from(e).where(a?and(m,a):m).all();for(let O of w){let I=this.extractThreadIdFromCommand(O.command);!I||!r.has(I)||d(I,O);}}catch(l){throw new p("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{c.close();}}return s}findAllTasks(t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(e.workspace_id,t.workspaceId));let r=t.agents&&t.agents.length>0?t.agents:t.agentId?[t.agentId]:null;r&&s.push(inArray(e.agent_id,r));let i=t.statuses&&t.statuses.length>0?t.statuses:t.status?[t.status]:null;i&&s.push(inArray(e.status,i));let a=t.q??t.search;a&&s.push(like(e.prompt,`%${a}%`)),t.from&&s.push(gte(e.started_at,t.from)),t.to&&s.push(lt$1(e.started_at,t.to));let d=s.length>0?and(...s):void 0,u=n.db.select({count:sql`count(*)`}).from(e).where(d).get(),c=(t.sortDir??"DESC")==="ASC"?asc(e.started_at):desc(e.started_at);return {rows:n.db.select().from(e).where(d).orderBy(c).limit(t.limit).offset(t.offset).all(),total:u?.count??0}}catch(s){throw new p("DB_ERROR","Failed to find all tasks",s)}finally{n.close();}}getAgentUsage(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.all(s?sql`
|
|
71
71
|
SELECT
|
|
72
72
|
t.agent_id,
|
|
73
73
|
t.workspace_id,
|
|
@@ -75,11 +75,11 @@ ${s.join(`
|
|
|
75
75
|
COALESCE(SUM(
|
|
76
76
|
COALESCE(t.input_tokens, 0)
|
|
77
77
|
+ CASE
|
|
78
|
-
WHEN t.started_at >= ${
|
|
78
|
+
WHEN t.started_at >= ${rt}
|
|
79
79
|
AND (
|
|
80
80
|
t.crewx_version IS NULL
|
|
81
81
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
82
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
82
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
|
|
83
83
|
)
|
|
84
84
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
85
85
|
ELSE 0
|
|
@@ -98,11 +98,11 @@ ${s.join(`
|
|
|
98
98
|
COALESCE(SUM(
|
|
99
99
|
COALESCE(t.input_tokens, 0)
|
|
100
100
|
+ CASE
|
|
101
|
-
WHEN t.started_at >= ${
|
|
101
|
+
WHEN t.started_at >= ${rt}
|
|
102
102
|
AND (
|
|
103
103
|
t.crewx_version IS NULL
|
|
104
104
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
105
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
105
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
|
|
106
106
|
)
|
|
107
107
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
108
108
|
ELSE 0
|
|
@@ -118,11 +118,11 @@ ${s.join(`
|
|
|
118
118
|
COALESCE(SUM(
|
|
119
119
|
COALESCE(t.input_tokens, 0)
|
|
120
120
|
+ CASE
|
|
121
|
-
WHEN t.started_at >= ${
|
|
121
|
+
WHEN t.started_at >= ${rt}
|
|
122
122
|
AND (
|
|
123
123
|
t.crewx_version IS NULL
|
|
124
124
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
125
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
125
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
|
|
126
126
|
)
|
|
127
127
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
128
128
|
ELSE 0
|
|
@@ -140,11 +140,11 @@ ${s.join(`
|
|
|
140
140
|
COALESCE(SUM(
|
|
141
141
|
COALESCE(t.input_tokens, 0)
|
|
142
142
|
+ CASE
|
|
143
|
-
WHEN t.started_at >= ${
|
|
143
|
+
WHEN t.started_at >= ${rt}
|
|
144
144
|
AND (
|
|
145
145
|
t.crewx_version IS NULL
|
|
146
146
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
147
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
147
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
|
|
148
148
|
)
|
|
149
149
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
150
150
|
ELSE 0
|
|
@@ -159,11 +159,11 @@ ${s.join(`
|
|
|
159
159
|
COALESCE(SUM(
|
|
160
160
|
COALESCE(t.input_tokens, 0)
|
|
161
161
|
+ CASE
|
|
162
|
-
WHEN t.started_at >= ${
|
|
162
|
+
WHEN t.started_at >= ${rt}
|
|
163
163
|
AND (
|
|
164
164
|
t.crewx_version IS NULL
|
|
165
165
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
166
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
166
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
|
|
167
167
|
)
|
|
168
168
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
169
169
|
ELSE 0
|
|
@@ -186,11 +186,11 @@ ${s.join(`
|
|
|
186
186
|
COALESCE(SUM(
|
|
187
187
|
COALESCE(t.input_tokens, 0)
|
|
188
188
|
+ CASE
|
|
189
|
-
WHEN t.started_at >= ${
|
|
189
|
+
WHEN t.started_at >= ${rt}
|
|
190
190
|
AND (
|
|
191
191
|
t.crewx_version IS NULL
|
|
192
192
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
193
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
193
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${ot}) AS INTEGER) < ${it})
|
|
194
194
|
)
|
|
195
195
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
196
196
|
ELSE 0
|
|
@@ -205,14 +205,14 @@ ${s.join(`
|
|
|
205
205
|
AND t.started_at < ${n}
|
|
206
206
|
GROUP BY date(t.started_at), t.agent_id
|
|
207
207
|
ORDER BY date(t.started_at) ASC
|
|
208
|
-
`).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(i){throw new p("DB_ERROR","Failed to get agent usage trend",i)}finally{r.close();}}findTaskForStop(t,n){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(e).where(and(eq(e.id,t),eq(e.workspace_id,n))).limit(1).get()??void 0}catch(r){throw new p("DB_ERROR","Failed to find task for stop",r)}finally{s.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:e.id,thread_id:e.thread_id,status:e.status,result:e.result,error:e.error,started_at:e.started_at,completed_at:e.completed_at,metadata:e.metadata}).from(e).where(and(eq(e.agent_id,t.agentId),eq(e.workspace_id,t.workspaceId),sql`${e.metadata} IS NOT NULL AND json_valid(${e.metadata}) AND json_extract(${e.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(e.started_at)).limit(1).get()??null}catch(s){throw new p("DB_ERROR","Failed to find latest task by metadata",s)}finally{n.close();}}markTaskFailed(t,n,s){if(!this.dbExists())return;let r=this.openHandle(true);try{let i=new Date().toISOString(),a=s?and(eq(e.id,t),eq(e.status,"running"),eq(e.workspace_id,s)):and(eq(e.id,t),eq(e.status,"running"));r.db.update(e).set({status:"failed",error:n,completed_at:i}).where(a).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to mark task failed",i)}finally{r.close();}}findTasksByPromptHint(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=
|
|
208
|
+
`).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(i){throw new p("DB_ERROR","Failed to get agent usage trend",i)}finally{r.close();}}findTaskForStop(t,n){if(!this.dbExists())return;let s=this.openHandle(false);try{return s.db.select().from(e).where(and(eq(e.id,t),eq(e.workspace_id,n))).limit(1).get()??void 0}catch(r){throw new p("DB_ERROR","Failed to find task for stop",r)}finally{s.close();}}findLatestTaskByMetadata(t){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:e.id,thread_id:e.thread_id,status:e.status,result:e.result,error:e.error,started_at:e.started_at,completed_at:e.completed_at,metadata:e.metadata}).from(e).where(and(eq(e.agent_id,t.agentId),eq(e.workspace_id,t.workspaceId),sql`${e.metadata} IS NOT NULL AND json_valid(${e.metadata}) AND json_extract(${e.metadata}, '$.' || ${t.metaKey}) = ${t.metaValue}`)).orderBy(desc(e.started_at)).limit(1).get()??null}catch(s){throw new p("DB_ERROR","Failed to find latest task by metadata",s)}finally{n.close();}}markTaskFailed(t,n,s){if(!this.dbExists())return;let r=this.openHandle(true);try{let i=new Date().toISOString(),a=s?and(eq(e.id,t),eq(e.status,"running"),eq(e.workspace_id,s)):and(eq(e.id,t),eq(e.status,"running"));r.db.update(e).set({status:"failed",error:n,completed_at:i}).where(a).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to mark task failed",i)}finally{r.close();}}findTasksByPromptHint(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=n?and(like(e.prompt,`%${t}%`),eq(e.workspace_id,n)):like(e.prompt,`%${t}%`),c=d.db.select().from(e).where(u).orderBy(asc(e.started_at)).all();for(let l of c)r.has(l.id)||(r.add(l.id),i.push(l));}catch(u){throw new p("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{d.close();}}return i}getProviderUsage(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{let i=ae(),a=sql`
|
|
209
209
|
COALESCE(${e.input_tokens}, 0)
|
|
210
210
|
+ CASE
|
|
211
|
-
WHEN ${e.started_at} >= ${
|
|
211
|
+
WHEN ${e.started_at} >= ${rt}
|
|
212
212
|
AND (
|
|
213
213
|
${e.crewx_version} IS NULL
|
|
214
214
|
OR (${e.crewx_version} LIKE '0.8.%' AND ${e.crewx_version} NOT LIKE '0.8.9%')
|
|
215
|
-
OR (${e.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${e.crewx_version}, ${
|
|
215
|
+
OR (${e.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${e.crewx_version}, ${ot}) AS INTEGER) < ${it})
|
|
216
216
|
)
|
|
217
217
|
THEN COALESCE(${e.cached_input_tokens}, 0)
|
|
218
218
|
ELSE 0
|
|
@@ -231,14 +231,14 @@ ${s.join(`
|
|
|
231
231
|
${d}
|
|
232
232
|
GROUP BY ${i}
|
|
233
233
|
ORDER BY (COALESCE(SUM(${a}), 0) + COALESCE(SUM(${e.output_tokens}), 0)) DESC
|
|
234
|
-
`).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(i){throw new p("DB_ERROR","Failed to get provider usage",i)}finally{r.close();}}getModelUsage(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{let i=
|
|
234
|
+
`).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(i){throw new p("DB_ERROR","Failed to get provider usage",i)}finally{r.close();}}getModelUsage(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{let i=ae(),a=sql`
|
|
235
235
|
COALESCE(${e.input_tokens}, 0)
|
|
236
236
|
+ CASE
|
|
237
|
-
WHEN ${e.started_at} >= ${
|
|
237
|
+
WHEN ${e.started_at} >= ${rt}
|
|
238
238
|
AND (
|
|
239
239
|
${e.crewx_version} IS NULL
|
|
240
240
|
OR (${e.crewx_version} LIKE '0.8.%' AND ${e.crewx_version} NOT LIKE '0.8.9%')
|
|
241
|
-
OR (${e.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${e.crewx_version}, ${
|
|
241
|
+
OR (${e.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${e.crewx_version}, ${ot}) AS INTEGER) < ${it})
|
|
242
242
|
)
|
|
243
243
|
THEN COALESCE(${e.cached_input_tokens}, 0)
|
|
244
244
|
ELSE 0
|
|
@@ -257,7 +257,7 @@ ${s.join(`
|
|
|
257
257
|
FROM ${e}
|
|
258
258
|
${d}
|
|
259
259
|
GROUP BY ${e.model}, ${i}
|
|
260
|
-
`),c=new Map;for(let l of u){let h=
|
|
260
|
+
`),c=new Map;for(let l of u){let h=ie(l.model??""),m=JSON.stringify([l.provider,h]),w=c.get(m);w?(w.totalTasks+=l.total_tasks,w.inputTokens+=l.input_tokens,w.outputTokens+=l.output_tokens,w.cachedInputTokens+=l.cached_input_tokens,w.costUsd+=l.cost_usd,w.totalTokens+=l.input_tokens+l.output_tokens,w.activeDurationMs+=l.active_duration_ms??0,l.last_active_at&&(!w.lastActiveAt||l.last_active_at>w.lastActiveAt)&&(w.lastActiveAt=l.last_active_at)):c.set(m,{model:h,provider:l.provider,totalTasks:l.total_tasks,inputTokens:l.input_tokens,outputTokens:l.output_tokens,cachedInputTokens:l.cached_input_tokens,costUsd:l.cost_usd,totalTokens:l.input_tokens+l.output_tokens,activeDurationMs:l.active_duration_ms??0,lastActiveAt:l.last_active_at??null});}return Array.from(c.values()).sort((l,h)=>h.costUsd-l.costUsd)}catch(i){throw new p("DB_ERROR","Failed to get model usage",i)}finally{r.close();}}getTasksForReport(t,n,s){if(!this.dbExists())return [];let r=this.openHandle(false);try{let i=s?sql`WHERE ${e.started_at} >= ${t} AND ${e.started_at} < ${n} AND ${e.workspace_id} = ${s}`:sql`WHERE ${e.started_at} >= ${t} AND ${e.started_at} < ${n}`;return r.db.all(sql`
|
|
261
261
|
SELECT
|
|
262
262
|
${e.thread_id} AS thread_id,
|
|
263
263
|
${e.agent_id} AS agent_id,
|
|
@@ -268,11 +268,11 @@ ${s.join(`
|
|
|
268
268
|
FROM ${e}
|
|
269
269
|
${i}
|
|
270
270
|
ORDER BY ${e.started_at} ASC
|
|
271
|
-
`).map(d=>({threadId:d.thread_id,agentId:d.agent_id,startedAt:d.started_at,status:d.status,error:d.error,exitCode:d.exit_code}))}catch(i){throw new p("DB_ERROR","Failed to get tasks for report",i)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(e.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&s.push(inArray(e.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&s.push(inArray(e.status,t.statuses)),t.from&&s.push(gte(e.started_at,t.from)),t.to&&s.push(lt(e.started_at,t.to));let r=s.length>0?and(...s):void 0,i=(t.order??"DESC")==="ASC"?asc(e.started_at):desc(e.started_at),a={id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id};return t.limit?n.db.select(a).from(e).where(r).orderBy(i).limit(t.limit).all():n.db.select(a).from(e).where(r).orderBy(i).all()}catch(s){throw new p("DB_ERROR","Failed to find task evidence",s)}finally{n.close();}}findThreadChains(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=t.maxThreads??8,r=t.maxTurnsPerThread??4,i=[isNotNull(e.thread_id),isNull(e.parent_task_id),isNull(e.caller_agent_id),or(isNull(e.platform),ne(e.platform,"workflow")),or(isNull(e.metadata),and(notLike(e.metadata,'%"kind":"workflow_card"%'),notLike(e.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(e.metadata),notLike(e.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&i.push(eq(e.workspace_id,t.workspaceId)),t.from&&i.push(gte(e.started_at,t.from)),t.to&&i.push(lt(e.started_at,t.to));let a=n.db.select({id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id}).from(e).where(and(...i)).orderBy(asc(e.started_at),asc(e.id)).all(),d=new Map;for(let c of a){if(!c.thread_id)continue;let l={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},h=d.get(c.thread_id);h?h.push(l):d.set(c.thread_id,[l]);}let u=[];for(let[c,l]of d){let h=l.filter(m=>m.agentId===t.targetAgentId).length;h<2||u.push({threadId:c,targetAgentTurnCount:h,turns:l});}return u.sort((c,l)=>{let h=c.turns[c.turns.length-1].startedAt,m=l.turns[l.turns.length-1].startedAt;return h<m?1:h>m?-1:0}),u.slice(0,s).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-r)}))}catch(s){throw new p("DB_ERROR","Failed to find thread chains",s)}finally{n.close();}}};var
|
|
271
|
+
`).map(d=>({threadId:d.thread_id,agentId:d.agent_id,startedAt:d.started_at,status:d.status,error:d.error,exitCode:d.exit_code}))}catch(i){throw new p("DB_ERROR","Failed to get tasks for report",i)}finally{r.close();}}findTaskEvidence(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=[];t.workspaceId&&s.push(eq(e.workspace_id,t.workspaceId)),t.agents&&t.agents.length>0&&s.push(inArray(e.agent_id,t.agents)),t.statuses&&t.statuses.length>0&&s.push(inArray(e.status,t.statuses)),t.from&&s.push(gte(e.started_at,t.from)),t.to&&s.push(lt$1(e.started_at,t.to));let r=s.length>0?and(...s):void 0,i=(t.order??"DESC")==="ASC"?asc(e.started_at):desc(e.started_at),a={id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id};return t.limit?n.db.select(a).from(e).where(r).orderBy(i).limit(t.limit).all():n.db.select(a).from(e).where(r).orderBy(i).all()}catch(s){throw new p("DB_ERROR","Failed to find task evidence",s)}finally{n.close();}}findThreadChains(t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let s=t.maxThreads??8,r=t.maxTurnsPerThread??4,i=[isNotNull(e.thread_id),isNull(e.parent_task_id),isNull(e.caller_agent_id),or(isNull(e.platform),ne(e.platform,"workflow")),or(isNull(e.metadata),and(notLike(e.metadata,'%"kind":"workflow_card"%'),notLike(e.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(e.metadata),notLike(e.metadata,'%"retriedFromTaskId"%'))];t.workspaceId&&i.push(eq(e.workspace_id,t.workspaceId)),t.from&&i.push(gte(e.started_at,t.from)),t.to&&i.push(lt$1(e.started_at,t.to));let a=n.db.select({id:e.id,agent_id:e.agent_id,status:e.status,prompt:e.prompt,started_at:e.started_at,completed_at:e.completed_at,thread_id:e.thread_id}).from(e).where(and(...i)).orderBy(asc(e.started_at),asc(e.id)).all(),d=new Map;for(let c of a){if(!c.thread_id)continue;let l={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},h=d.get(c.thread_id);h?h.push(l):d.set(c.thread_id,[l]);}let u=[];for(let[c,l]of d){let h=l.filter(m=>m.agentId===t.targetAgentId).length;h<2||u.push({threadId:c,targetAgentTurnCount:h,turns:l});}return u.sort((c,l)=>{let h=c.turns[c.turns.length-1].startedAt,m=l.turns[l.turns.length-1].startedAt;return h<m?1:h>m?-1:0}),u.slice(0,s).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-r)}))}catch(s){throw new p("DB_ERROR","Failed to find thread chains",s)}finally{n.close();}}};var Bt=class extends et{name="sqlite-tracing";unsubs=[];dbPath;version;constructor(t){super(),this.dbPath=join(t?.dbRoot??homedir(),".crewx","crewx.db"),this.version=t?.version??"unknown";}attach(t){let n=new bt({dbPath:this.dbPath}),s=process.cwd(),i=existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))?Gt(s):null,a=process.argv.join(" ");this.unsubs.push(t.on("task:start",d=>{try{let u=d.callerAgentId??null,c=d.parentTaskId??null,l=d.rootTraceId??d.traceId,h=d.metadata?JSON.stringify(d.metadata):JSON.stringify({provider:d.provider??"cli/claude"});n.startTask({id:d.traceId,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:d.pid??null,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:a,codingAgentCommand:d.codingAgentCommand??null,workspaceId:d.workspaceId??i,projectId:d.projectId??null,callerAgentId:u,parentTaskId:c,traceId:l,metadata:h,threadId:d.threadId??null});}catch{}}),t.on("task:output",d=>{try{n.appendLog(d.traceId,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch{}}),t.on("task:end",d=>{try{let u=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null,c=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{}}):null;n.finishTask({id:d.traceId,status:d.error?"failed":"success",result:d.result??null,error:c,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch:u});}catch{}}));}detach(t){this.unsubs.forEach(n=>n()),this.unsubs=[];}};var Ct=class extends lt{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 n=this.resolveDbPath();if(t){let r=dirname(n);existsSync(r)||mkdirSync(r,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let s=x(n);if(t)try{yt(s.db,n);}catch(r){throw s.close(),r}return s}validateWorkspaceId(t,n){return t.db.select({id:_t.id}).from(_t).where(eq(_t.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(t="child"){return sql.raw(`NOT EXISTS (
|
|
272
272
|
SELECT 1 FROM tasks parent
|
|
273
273
|
WHERE parent.id = ${t}.parent_task_id
|
|
274
274
|
AND parent.thread_id = ${t}.thread_id
|
|
275
|
-
)`)}findAllThreads(t){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let a=
|
|
275
|
+
)`)}findAllThreads(t){let n=this.resolveDbPaths(),s=new Set,r=[];for(let i of n){if(!existsSync(i))continue;let a=x(i);try{let d=t?eq(_.workspace_id,t):void 0,u=a.db.select().from(_).where(d).orderBy(desc(_.updated_at)).all();for(let c of u)s.has(c.id)||(s.add(c.id),r.push(c));}catch(d){throw new p("DB_ERROR","Failed to find all threads",d)}finally{a.close();}}return r}findThreadsByIdsOrTitles(t,n){if(t.length===0)return [];let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=or(inArray(_.id,t),inArray(_.title,t)),c=n?and(u,eq(_.workspace_id,n)):u,l=d.db.select().from(_).where(c).orderBy(desc(_.updated_at)).all();for(let h of l)r.has(h.id)||(r.add(h.id),i.push(h));}catch(u){throw new p("DB_ERROR","Failed to find threads by ids or titles",u)}finally{d.close();}}return i}findThreadById(t,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=x(r);try{let a=eq(_.id,t),d=n?and(a,eq(_.workspace_id,n)):a,u=i.db.select().from(_).where(d).limit(1).get()??void 0;if(u)return u}catch(a){throw new p("DB_ERROR","Failed to find thread by id",a)}finally{i.close();}}}threadExists(t,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=x(r);try{let a=eq(_.id,t),d=n?and(a,eq(_.workspace_id,n)):a;if(i.db.select({id:_.id}).from(_).where(d).limit(1).get())return !0}catch(a){throw new p("DB_ERROR","Failed to check thread existence",a)}finally{i.close();}}return false}aggregateTaskStats(t,n){let s=this.resolveDbPaths(),r=0,i=0,a=0,d=0,u=0,c=new Set;for(let l of s){if(!existsSync(l))continue;let h=x(l);try{let m=h.db.get(sql`
|
|
276
276
|
SELECT
|
|
277
277
|
count(*) AS cnt,
|
|
278
278
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -289,7 +289,7 @@ ${s.join(`
|
|
|
289
289
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
290
290
|
AND ${this.topLevelTaskPredicateSql()}
|
|
291
291
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
292
|
-
`);for(let
|
|
292
|
+
`);for(let O of w)c.add(O.agent_id);}catch(m){throw new p("DB_ERROR","Failed to aggregate task stats",m)}finally{h.close();}}return {taskCount:r,inputTokens:i,outputTokens:a,cachedInputTokens:d,costUsd:u,agentIds:Array.from(c)}}findTopLevelTasks(t,n,s){let r=this.resolveDbPaths(),i=new Set,a=[];for(let d of r){if(!existsSync(d))continue;let u=x(d);try{let c;s!==void 0?c=u.db.all(sql`
|
|
293
293
|
SELECT * FROM (
|
|
294
294
|
SELECT child.*,
|
|
295
295
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -306,7 +306,7 @@ ${s.join(`
|
|
|
306
306
|
AND ${this.topLevelTaskPredicateSql()}
|
|
307
307
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
308
308
|
ORDER BY child.started_at ASC
|
|
309
|
-
`);for(let l of c)i.has(l.id)||(i.add(l.id),a.push(l));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(s!==void 0&&r.length>1){let d=new Map;for(let u of a){let c=u.agent_id??"";d.has(c)||d.set(c,[]),d.get(c).push(u);}a=[];for(let u of d.values())u.sort((c,l)=>(l.started_at??"").localeCompare(c.started_at??"")),a.push(...u.slice(0,s));a.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return a}findAllTasks(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=
|
|
309
|
+
`);for(let l of c)i.has(l.id)||(i.add(l.id),a.push(l));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{u.close();}}if(s!==void 0&&r.length>1){let d=new Map;for(let u of a){let c=u.agent_id??"";d.has(c)||d.set(c,[]),d.get(c).push(u);}a=[];for(let u of d.values())u.sort((c,l)=>(l.started_at??"").localeCompare(c.started_at??"")),a.push(...u.slice(0,s));a.sort((u,c)=>(u.started_at??"").localeCompare(c.started_at??""));}return a}findAllTasks(t,n){let s=this.resolveDbPaths(),r=new Set,i=[];for(let a of s){if(!existsSync(a))continue;let d=x(a);try{let u=eq(e.thread_id,t),c=n?and(u,eq(e.workspace_id,n)):u,l=d.db.select().from(e).where(c).orderBy(asc(e.started_at)).all();for(let h of l)r.has(h.id)||(r.add(h.id),i.push(h));}catch(u){throw new p("DB_ERROR","Failed to find all tasks for thread",u)}finally{d.close();}}return i}findTaskById(t,n,s){let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let a=x(i);try{let d=and(eq(e.id,n),eq(e.thread_id,t)),u=s?and(d,eq(e.workspace_id,s)):d,c=a.db.select().from(e).where(u).limit(1).get();if(!c)continue;let l=a.db.select().from(e).where(eq(e.parent_task_id,c.id)).orderBy(asc(e.started_at)).all();return {task:c,children:l}}catch(d){throw new p("DB_ERROR","Failed to find task by id",d)}finally{a.close();}}}batchFetchTasksQuery(t,n){return sql`
|
|
310
310
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
311
311
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
312
312
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -316,7 +316,7 @@ ${s.join(`
|
|
|
316
316
|
AND ${this.topLevelTaskPredicateSql()}
|
|
317
317
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
318
318
|
ORDER BY child.started_at ASC
|
|
319
|
-
`}batchFetchTasks(t,n){let s=new Map;if(t.length===0)return s;let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let a=
|
|
319
|
+
`}batchFetchTasks(t,n){let s=new Map;if(t.length===0)return s;let r=this.resolveDbPaths();for(let i of r){if(!existsSync(i))continue;let a=x(i);try{let d=a.db.all(this.batchFetchTasksQuery(t,n));for(let u of d){let c=u.thread_id;s.has(c)||s.set(c,[]),s.get(c).push(u);}}catch(d){throw new p("DB_ERROR","Failed to batch fetch tasks",d)}finally{a.close();}}return s}explainBatchFetchTasksPlan(t,n){let s=this.resolveDbPaths();for(let r of s){if(!existsSync(r))continue;let i=x(r);try{return i.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(t,n)}`).map(d=>d.detail)}finally{i.close();}}return []}updateThreadTitle(t,n,s){if(!this.dbExists())return;let r=this.openHandle(true);try{let i=eq(_.id,t),a=s?and(i,eq(_.workspace_id,s)):i;if(!r.db.select({id:_.id}).from(_).where(a).limit(1).get())return;r.db.update(_).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(_.id,t)).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to update thread title",i)}finally{r.close();}}upsertThread(t,n){let s=this.openHandle(true);try{let r=n.workspaceId?this.validateWorkspaceId(s,n.workspaceId):null,i=new Date().toISOString();if(s.db.select({id:_.id,message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()){let d={updated_at:i};n.title!==void 0&&(d.title=n.title),n.titleLocked!==void 0&&(d.title_locked=n.titleLocked?1:0),s.db.update(_).set(d).where(eq(_.id,t)).run();}else s.db.insert(_).values({id:t,platform:n.platform,workspace_id:r,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:i,updated_at:i}).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to upsert thread",r)}finally{s.close();}}ensureThread(t,n,s){let r=this.openHandle(true);try{let i=s?this.validateWorkspaceId(r,s):null,a=r.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(eq(_.id,t)).limit(1).get();if(a){i&&!a.workspace_id&&r.db.update(_).set({workspace_id:i}).where(eq(_.id,t)).run();return}let d=new Date().toISOString();r.db.insert(_).values({id:t,platform:n,workspace_id:i,message_count:0,created_at:d,updated_at:d}).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to ensure thread",i)}finally{r.close();}}saveUserMessage(t,n,s){if(!this.dbExists())return {firstMessage:false};let r=this.openHandle(true);try{let i=new Date().toISOString();return {firstMessage:r.db.transaction(d=>{let c=d.select({message_count:_.message_count}).from(_).where(eq(_.id,t)).limit(1).get()?.message_count===0;return d.run(sql`
|
|
320
320
|
UPDATE threads
|
|
321
321
|
SET first_message = COALESCE(first_message, ${n}),
|
|
322
322
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
@@ -324,8 +324,8 @@ ${s.join(`
|
|
|
324
324
|
message_count = message_count + 1,
|
|
325
325
|
updated_at = ${i}
|
|
326
326
|
WHERE id = ${t}
|
|
327
|
-
`),c},{behavior:"immediate"})}}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to save user message",i)}finally{r.close();}}saveAssistantMessage(t,n,s){if(!this.dbExists())return;let r=this.openHandle(true);try{let i=new Date().toISOString();r.db.update(_).set({last_message:n,updated_at:i}).where(eq(_.id,t)).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to save assistant message",i)}finally{r.close();}}updateThread(t,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),s.db.update(_).set(r).where(eq(_.id,t)).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to update thread",r)}finally{s.close();}}togglePin(t,n){let s=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),i=s.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!i)return null;let a=i.pinned?0:1,d=i.metadata?JSON.parse(i.metadata):{};if(a){let u=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),c=s.db.select({metadata:_.metadata}).from(_).where(u).all(),l=null;for(let h of c){let m=h.metadata?JSON.parse(h.metadata):{};typeof m.pinOrder=="number"&&(l===null||m.pinOrder<l)&&(l=m.pinOrder);}d.pinOrder=l===null?0:l-1;}else delete d.pinOrder;return s.db.update(_).set({pinned:a,metadata:Object.keys(d).length>0?JSON.stringify(d):null}).where(r).run(),{pinned:!!a}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to toggle pin",r)}finally{s.close();}}reorderPins(t,n){let s=this.openHandle(true);try{for(let r=0;r<t.length;r++){let i=n?and(eq(_.id,t[r]),eq(_.workspace_id,n)):eq(_.id,t[r]),a=s.db.select({metadata:_.metadata}).from(_).where(i).get();if(!a)continue;let d=a.metadata?JSON.parse(a.metadata):{};d.pinOrder=r+1,s.db.update(_).set({metadata:JSON.stringify(d)}).where(i).run();}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to reorder pins",r)}finally{s.close();}}toggleStar(t,n){let s=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),i=s.db.select({starred:_.starred}).from(_).where(r).get();if(!i)return null;let a=i.starred?0:1;return s.db.update(_).set({starred:a}).where(r).run(),{starred:!!a}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to toggle star",r)}finally{s.close();}}resolveOverdriveForRequest(t,n,s,r){let a=this.openHandle(true);try{let d=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t);return a.db.transaction(c=>{let l=c.select({metadata:_.metadata}).from(_).where(d).get();if(!l)return null;let h=l.metadata?JSON.parse(l.metadata):{},m=h.overdrive??{},w=r?.defaultTurns??m.defaultTurns??3
|
|
327
|
+
`),c},{behavior:"immediate"})}}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to save user message",i)}finally{r.close();}}saveAssistantMessage(t,n,s){if(!this.dbExists())return;let r=this.openHandle(true);try{let i=new Date().toISOString();r.db.update(_).set({last_message:n,updated_at:i}).where(eq(_.id,t)).run();}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to save assistant message",i)}finally{r.close();}}updateThread(t,n){if(!this.dbExists())return;let s=this.openHandle(true);try{let r={updated_at:new Date().toISOString()};n.title!==void 0&&(r.title=n.title,r.title_locked=1),n.titleLocked!==void 0&&(r.title_locked=n.titleLocked?1:0),s.db.update(_).set(r).where(eq(_.id,t)).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to update thread",r)}finally{s.close();}}togglePin(t,n){let s=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),i=s.db.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(r).get();if(!i)return null;let a=i.pinned?0:1,d=i.metadata?JSON.parse(i.metadata):{};if(a){let u=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),c=s.db.select({metadata:_.metadata}).from(_).where(u).all(),l=null;for(let h of c){let m=h.metadata?JSON.parse(h.metadata):{};typeof m.pinOrder=="number"&&(l===null||m.pinOrder<l)&&(l=m.pinOrder);}d.pinOrder=l===null?0:l-1;}else delete d.pinOrder;return s.db.update(_).set({pinned:a,metadata:Object.keys(d).length>0?JSON.stringify(d):null}).where(r).run(),{pinned:!!a}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to toggle pin",r)}finally{s.close();}}reorderPins(t,n){let s=this.openHandle(true);try{for(let r=0;r<t.length;r++){let i=n?and(eq(_.id,t[r]),eq(_.workspace_id,n)):eq(_.id,t[r]),a=s.db.select({metadata:_.metadata}).from(_).where(i).get();if(!a)continue;let d=a.metadata?JSON.parse(a.metadata):{};d.pinOrder=r+1,s.db.update(_).set({metadata:JSON.stringify(d)}).where(i).run();}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to reorder pins",r)}finally{s.close();}}toggleStar(t,n){let s=this.openHandle(true);try{let r=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t),i=s.db.select({starred:_.starred}).from(_).where(r).get();if(!i)return null;let a=i.starred?0:1;return s.db.update(_).set({starred:a}).where(r).run(),{starred:!!a}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to toggle star",r)}finally{s.close();}}resolveOverdriveForRequest(t,n,s,r){let a=this.openHandle(true);try{let d=n?and(eq(_.id,t),eq(_.workspace_id,n)):eq(_.id,t);return a.db.transaction(c=>{let l=c.select({metadata:_.metadata}).from(_).where(d).get();if(!l)return null;let h=l.metadata?JSON.parse(l.metadata):{},m=h.overdrive??{},w=r?.defaultTurns??m.defaultTurns??3,O=r?.updatedBy??"ui",I=new Date().toISOString(),B,z,Y,pt;switch(s){case "enable-count":{let ht=r?.turns??w,ft=r?.consumeCurrent?Math.max(ht-1,0):ht;B=ft>0?"count":"off",z=ft,Y=!0,pt="count";break}case "enable-latch":{B="latch",z=0,Y=!0,pt="latch";break}case "disable":{B="off",z=0,Y=!1;break}default:{let ht=m.state??"off",ft=typeof m.remaining=="number"?m.remaining:0;if(ht==="count"&&ft>0){let qt=ft-1;qt<=0?(B="off",z=0):(B="count",z=qt),Y=!0,pt="count";}else ht==="latch"?(B="latch",z=0,Y=!0,pt="latch"):(B="off",z=0,Y=!1);break}}return h.overdrive={state:B,remaining:z,defaultTurns:w,updatedAt:I,updatedBy:O},c.update(_).set({metadata:JSON.stringify(h),updated_at:I}).where(d).run(),{applied:Y,appliedMode:pt,state:B,remaining:z}},{behavior:"immediate"})}catch(d){throw d instanceof p?d:new p("DB_ERROR","Failed to resolve overdrive",d)}finally{a.close();}}};function Sn(o){return o.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
328
328
|
`).filter(r=>!(r.startsWith("Loaded ")&&r.includes("layouts from")||r.includes("[dotenv@")||r.includes("[Nest]")&&r.includes("DEBUG")||r.startsWith("Registered custom layout:")||r.startsWith("Updated custom layout:"))).join(`
|
|
329
|
-
`).trim()}function
|
|
330
|
-
`):n&&typeof n=="object"&&n.result!==void 0&&(t=n.result||"");}catch{t=
|
|
331
|
-
`)[0].slice(0,200)),n.push({id:`${s.id}-assistant`,text:r,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:a});}}return n}};var
|
|
329
|
+
`).trim()}function Tn(o){if(!o)return "";let t=o;try{let n=JSON.parse(t);Array.isArray(n)?t=n.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
|
|
330
|
+
`):n&&typeof n=="object"&&n.result!==void 0&&(t=n.result||"");}catch{t=Sn(t);}return t}var vt=class{dbPath;constructor(t){this.dbPath=t??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Ct({dbPath:this.dbPath})}updateThread(t,n){this.getThreadRepo().updateThread(t,{title:n.title});}async ensureThread(t,n,s){let r=this.getThreadRepo(),i=r.findThreadById(t);if(i){if(i.platform!==n)throw new Error(`Thread '${t}' already exists with platform '${i.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return {created:false}}return r.ensureThread(t,n,s),{created:true}}async fetchHistory(t,n){let s=n?.limit??100,r=this.getThreadRepo(),i=r.findThreadById(t),a=r.findTopLevelTasks(t,void 0,s),d=new Set(["queued","cancelled"]);a=a.filter(l=>(!l.status||!d.has(l.status))&&(!n?.currentTraceId||l.trace_id!==n.currentTraceId));let u=i?.platform??"cli",c=this.rowsToMessages(a);return {threadId:t,platform:u,messages:c,metadata:{title:i?.title??void 0,firstMessage:i?.first_message??void 0,lastMessage:i?.last_message??void 0,messageCount:i?.message_count??0,updatedAt:i?.updated_at?new Date(i.updated_at).getTime():void 0}}}async saveUserMessage(t,n,s,r){let{firstMessage:i}=this.getThreadRepo().saveUserMessage(t,n);return {id:t,firstMessage:i}}async saveAssistantMessage(t,n,s,r){return this.getThreadRepo().saveAssistantMessage(t,n),{id:t}}close(){}normalizeStatus(t){if(t&&!["success","completed","done"].includes(t)){if(["failed","error"].includes(t))return "failed";if(t==="running")return "running"}}rowsToMessages(t){let n=[];for(let s of t){s.prompt&&n.push({id:`${s.id}-user`,text:s.prompt,isAssistant:false,timestamp:new Date(s.started_at).getTime(),metadata:{caller_agent_id:s.caller_agent_id}});let r=Tn(s.result),i=this.normalizeStatus(s.status);if(r||i==="running"||i==="failed"){let a={agent_id:s.agent_id,task_id:s.id};i&&(a.status=i),i==="failed"&&s.error&&(a.reason=s.error.split(`
|
|
331
|
+
`)[0].slice(0,200)),n.push({id:`${s.id}-assistant`,text:r,isAssistant:true,timestamp:new Date(s.started_at).getTime(),metadata:a});}}return n}};var Ht=class extends et{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(t){super(),this._provider=new vt(t?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(t,n,s,r){}async afterAssistantMessage(t,n,s){}attach(t){this.unsubStart=t.on("task:start",async n=>{if(!n.threadId)return;let s=n.platform??"cli";try{let r=await this._provider.ensureThread(n.threadId,s,n.workspaceId),i=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,i.id,r.created||i.firstMessage,n);}catch{}}),this.unsubEnd=t.on("task:end",async n=>{if(!n.result)return;let s=n.metadata?.threadId;if(!s)return;let r=n.agentRef?.replace(/^@/,"")??"";try{let{id:i}=await this._provider.saveAssistantMessage(s,n.result,r);await this.afterAssistantMessage(s,i,n);}catch{}});}detach(t){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{Ht as ConversationPlugin,Dt as FileLoggerPlugin,Bt as SqliteTracingPlugin};
|