@crewx/sdk 0.9.0-rc.79 → 0.9.0-rc.80
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 +115 -112
- package/dist/esm/plugins/index.js +83 -83
- package/dist/esm/repository/index.js +61 -61
- package/dist/facade/Crewx.d.ts +1 -0
- package/dist/highlight/thread-highlight-prompt.d.ts +1 -0
- package/dist/highlight/thread-highlighter.d.ts +164 -4
- package/dist/index.d.ts +10 -7
- package/dist/index.js +113 -110
- package/dist/migrations/0021_dashing_peter_quill.sql +51 -0
- package/dist/migrations/meta/0021_snapshot.json +3031 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.js +92 -92
- package/dist/repository/index.d.ts +3 -2
- package/dist/repository/index.js +61 -61
- package/dist/repository/thread-history.repository.d.ts +76 -1
- package/dist/schema/thread-history.d.ts +217 -1
- package/dist/ui-plugin/index.d.ts +3 -0
- package/dist/ui-plugin/manifest.d.ts +3 -0
- package/dist/ui-plugin/types.d.ts +76 -0
- package/dist/ui-plugin/validator.d.ts +9 -0
- package/dist/utils/id.d.ts +1 -1
- package/package.json +1 -1
- package/templates/agents/default.yaml +27 -1
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as fe from'path';import fe__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import _n,{homedir}from'os';import {createHash,randomBytes}from'crypto';import {sql,eq,desc,and,isNull,lt,or,notLike,asc,like,inArray,gte,isNotNull,ne}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey}from'drizzle-orm/sqlite-core';var Ge=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var nn=()=>fileURLToPath(import.meta.url),sn=()=>fe__default.dirname(nn()),y=sn();var Ne=class{detach(e){}};function nr(n){let e=t=>String(t).padStart(2,"0");return `${n.getFullYear()}${e(n.getMonth()+1)}${e(n.getDate())}T${e(n.getHours())}${e(n.getMinutes())}${e(n.getSeconds())}`}function vt(n){let e=n.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var Nt=class extends Ne{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(e){super(),this.logsDir=join(e?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=e?.version??"unknown";}attach(e){this.unsubs.push(e.on("task:start",t=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let r=nr(t.timestamp),s=join(this.logsDir,`${r}_${t.traceId}.log`);this.logFiles.set(t.traceId,s);let i=`=== TASK LOG: ${t.traceId} ===
|
|
2
2
|
CrewX Version: ${this.version}
|
|
3
|
-
Mode: ${
|
|
4
|
-
Agent: ${
|
|
5
|
-
Started: ${
|
|
6
|
-
Message: ${
|
|
3
|
+
Mode: ${t.mode}
|
|
4
|
+
Agent: ${t.agentRef}
|
|
5
|
+
Started: ${vt(t.timestamp)}
|
|
6
|
+
Message: ${t.message}
|
|
7
7
|
|
|
8
|
-
`;writeFileSync(s,i,{encoding:"utf8",mode:384});}catch{}}),
|
|
9
|
-
`,"utf8");}catch{}}),
|
|
10
|
-
[${s}] INFO: Process closed with exit code: ${
|
|
11
|
-
`;appendFileSync(r,a,"utf8"),this.logFiles.delete(
|
|
8
|
+
`;writeFileSync(s,i,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",t=>{try{let r=this.logFiles.get(t.traceId);if(!r)return;let s=new Date().toISOString();appendFileSync(r,`[${s}] STDOUT: ${t.output}
|
|
9
|
+
`,"utf8");}catch{}}),e.on("task:end",t=>{try{let r=this.logFiles.get(t.traceId);if(!r)return;let s=vt(new Date),i=t.error?`failed: ${t.error.message}`:"completed successfully",a=`[${s}] INFO: Task ${i} in ${t.durationMs}ms
|
|
10
|
+
[${s}] INFO: Process closed with exit code: ${t.error?1:0}
|
|
11
|
+
`;appendFileSync(r,a,"utf8"),this.logFiles.delete(t.traceId);}catch{}}));}detach(e){this.unsubs.forEach(t=>t()),this.unsubs=[],this.logFiles.clear();}};function ln(n){let e=fe.resolve(n);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,r)=>`${r.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function ar(n){let e=ln(n);return createHash("sha256").update(e).digest("hex")}var u=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};var Z=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(_n.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};var gn=32*1024*1024;function $(n){let e=Ge("better-sqlite3"),{drizzle:t}=Ge("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${gn}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),{db:t(r),runRaw:(s,i=[])=>r.prepare(s).run(...i),close:()=>r.close()}}var dr=new Set,fn={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",command:"TEXT"};function At(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function mn(n,e){if(e>0||!At(n,"tasks"))return;let t=n.all("PRAGMA table_info(tasks)"),r=new Set(t.map(s=>s.name));for(let[s,i]of Object.entries(fn))r.has(s)||n.run(`ALTER TABLE tasks ADD COLUMN ${s} ${i}`);}var Tn={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"}};function kn(n,e,t){if(!At(n,"__drizzle_migrations")||!At(n,"tasks"))return;let r=n.all(t`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(a=>a.hash)),i=JSON.parse(readFileSync(fe__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of i.entries){let d=Tn[a.tag];if(!d)continue;let c=fe__default.join(e,`${a.tag}.sql`);if(!existsSync(c))continue;let l=readFileSync(c,"utf-8"),h=createHash("sha256").update(l).digest("hex");if(s.has(h))continue;let p=n.all("PRAGMA table_info(tasks)"),g=new Set(p.map(f=>f.name));for(let[f,L]of Object.entries(d))g.has(f)||(n.run(`ALTER TABLE tasks ADD COLUMN ${f} ${L}`),g.add(f));}}function wn(n,e,t){let r=n.all(t`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(a=>a.hash)),i=JSON.parse(readFileSync(fe__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of i.entries){let d=fe__default.join(e,`${a.tag}.sql`);if(!existsSync(d))continue;let c=readFileSync(d,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(s.has(l))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,p=[],g;for(;(g=h.exec(c))!==null;)p.push({table:g[1],column:g[2]});if(p.length===0||!c.split(/-->\s*statement-breakpoint/).map(N=>N.trim()).filter(Boolean).every(N=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(N)))continue;p.every(({table:N,column:v})=>n.all(`PRAGMA table_info("${N}")`).some(U=>U.name===v))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${a.when})`);}}function yn(n){let{migrate:e}=Ge("drizzle-orm/better-sqlite3/migrator"),{sql:t}=Ge("drizzle-orm"),r=[fe__default.join(y,"../migrations"),fe__default.join(y,"migrations"),fe__default.join(y,"../../../../drizzle/migrations"),fe__default.join(process.cwd(),"drizzle/migrations")],s=r.find(l=>existsSync(fe__default.join(l,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
|
|
12
12
|
${r.join(`
|
|
13
|
-
`)}`);let i=n.get(e`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;i?.cnt&&(a=n.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),ar(n,a),i?.cnt&&(lr(n,s,e),cr(n,s,e)),t(n,{migrationsFolder:s});let c=(n.get(e`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(c>0){let l=i?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function nt(n,t){Ke.has(t)||(ur(n),Ke.add(t));}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 o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),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)},n=>({log_storage_check:check("tasks_log_storage_ck",sql`${n.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));var rt=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>o.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},n=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(n.task_id,n.seq)}));var yr="json_extract(metadata, '$.threadTitle.state')",Er="json_extract(metadata, '$.threadTitle.priority')",h=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)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(n.workspace_id,n.updated_at),idx_threads_title:index("idx_threads_title").on(n.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(n.workspace_id,sql.raw(yr)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(n.workspace_id,sql.raw(Er))}));var Ir=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Ir.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>h.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));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")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.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")},n=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(n.workspace_id,n.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")},n=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(n.workspace_id,sql`${n.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},n=>({pk:primaryKey({columns:[n.notification_id,n.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()},n=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(n.workspace_id,n.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(n.workspace_id,n.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()},n=>({idCheck:check("ui_instances_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128 AND ${n.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${n.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${n.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${n.definition_hash}) = 64 AND ${n.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${n.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${n.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${n.domain_ref_json}) AND json_type(${n.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${n.state_json}) AND json_type(${n.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${n.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${n.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${n.granted_capabilities_json}) AND json_type(${n.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${n.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${n.updated_at} >= ${n.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(n.workspace_id,n.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")},n=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${n.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${n.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${n.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${n.actor_json}) AND json_type(${n.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${n.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${n.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${n.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${n.after_revision} IS NULL OR ${n.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${n.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${n.outcome} IS NULL OR ${n.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${n.input_json}) AND json_type(${n.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${n.result_json} IS NULL OR (json_valid(${n.result_json}) AND json_type(${n.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${n.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${n.settled_at} IS NULL OR ${n.settled_at} >= ${n.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
13
|
+
`)}`);let i=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;i?.cnt&&(a=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),mn(n,a),i?.cnt&&(wn(n,s,t),kn(n,s,t)),e(n,{migrationsFolder:s});let c=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(c>0){let l=i?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}}function de(n,e){dr.has(e)||(yn(n),dr.add(e));}var Me=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var o=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),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)},n=>({log_storage_check:check("tasks_log_storage_ck",sql`${n.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));var ce=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>o.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},n=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(n.task_id,n.seq)}));var bn="json_extract(metadata, '$.threadTitle.state')",xn="json_extract(metadata, '$.threadTitle.priority')",_=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Me.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(n.workspace_id,n.updated_at),idx_threads_title:index("idx_threads_title").on(n.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(n.workspace_id,sql.raw(bn)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(n.workspace_id,sql.raw(xn))}));var $n=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>$n.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>o.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));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()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));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")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.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")},n=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(n.workspace_id,n.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")},n=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(n.workspace_id,sql`${n.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},n=>({pk:primaryKey({columns:[n.notification_id,n.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()},n=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(n.workspace_id,n.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(n.workspace_id,n.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()},n=>({idCheck:check("ui_instances_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128 AND ${n.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${n.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${n.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${n.definition_hash}) = 64 AND ${n.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${n.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${n.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${n.domain_ref_json}) AND json_type(${n.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${n.state_json}) AND json_type(${n.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${n.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${n.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${n.granted_capabilities_json}) AND json_type(${n.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${n.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${n.updated_at} >= ${n.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(n.workspace_id,n.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")},n=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${n.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${n.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${n.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${n.actor_json}) AND json_type(${n.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${n.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${n.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${n.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${n.after_revision} IS NULL OR ${n.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${n.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${n.outcome} IS NULL OR ${n.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${n.input_json}) AND json_type(${n.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${n.result_json} IS NULL OR (json_valid(${n.result_json}) AND json_type(${n.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${n.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${n.settled_at} IS NULL OR ${n.settled_at} >= ${n.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
14
14
|
(${n.status} = 'requested' AND ${n.after_revision} IS NULL AND ${n.outcome} IS NULL AND ${n.settled_at} IS NULL)
|
|
15
15
|
OR
|
|
16
16
|
(${n.status} = 'settled' AND ${n.after_revision} IS NOT NULL AND ${n.outcome} IS NOT NULL AND ${n.settled_at} IS NOT NULL)
|
|
17
|
-
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(n.instance_id,n.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(n.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(n.requested_at)}));var an=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")},n=>({idCheck:check("projects_id_ck",sql`${n.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${n.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(${n.stages_json}) AND json_type(${n.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${n.stage_index} >= 1`)}));sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>an.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()},n=>({idCheck:check("project_criteria_id_ck",sql`${n.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${n.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${n.evidence_json}) AND json_type(${n.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(n.project_id,n.position)}));sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>an.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()},n=>({idCheck:check("project_events_id_ck",sql`${n.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(n.project_id,n.seq)}));var ve=["THREAD_STATE","THREAD_PRIORITY"],Ne=["gray","blue","violet","green","amber","orange","red","pink"],m=sqliteTable("common_codes",{code_group:text("code_group").notNull(),code:text("code").notNull(),code_name:text("code_name"),color:text("color").notNull().default("gray"),sort_order:integer("sort_order").notNull(),workspace_id:text("workspace_id"),is_builtin:integer("is_builtin").notNull().default(0),is_archived:integer("is_archived").notNull().default(0),metadata:text("metadata"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},n=>({pk:primaryKey({columns:[n.code_group,n.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${n.metadata} IS NULL OR (json_valid(${n.metadata}) AND json_type(${n.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${n.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${n.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(n.code_group,n.is_archived,n.sort_order)}));var un=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted"],_n=["user","agent","system"],hn=["auto","manual"],pn=["decision","judgment","issue","result","pivot"];var S=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>h.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},n=>({typeCheck:check("thread_events_type_ck",sql`${n.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted')`),actorTypeCheck:check("thread_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(n.thread_id,n.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(n.thread_id,n.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(n.thread_id,n.seq)})),R=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>h.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},n=>({sourceCheck:check("thread_highlights_source_ck",sql`${n.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${n.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${n.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${n.status} = 'dismissed' OR (${n.text} IS NOT NULL AND length(${n.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${n.covers_from_task_id}) > 0 AND length(${n.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${n.source} = 'manual' OR (${n.source} = 'auto' AND ${n.source_task_id} IS NOT NULL AND ${n.detector_version} IS NOT NULL AND ${n.content_fingerprint} IS NOT NULL AND length(${n.source_task_id}) > 0 AND length(${n.detector_version}) > 0 AND length(${n.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(n.thread_id,n.status,n.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(n.thread_id,n.covers_from_task_id,n.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(n.thread_id,n.source_task_id,n.detector_version,n.content_fingerprint).where(sql`${n.source} = 'auto'`)}));function gn(n){let t=n.toLowerCase().trim();t=t.replace(/\[[^\]]*\]$/g,"");let e=t.lastIndexOf("/");return e>=0&&(t=t.slice(e+1)),t=t.replace(/-\d{8}$/,""),t}function wn(n,t){let e=t===void 0?"":` at index ${t}`;if(!n||typeof n!="object")throw new u("VALIDATION",`Task log entry${e} must be an object`);if(typeof n.timestamp!="string"||typeof n.level!="string"||typeof n.message!="string")throw new u("VALIDATION",`Task log entry${e} must contain string timestamp, level, and message fields`);return {timestamp:n.timestamp,level:n.level,message:n.message}}function kn(n,t){if(t===null||t.trim()==="")return [];let e;try{e=JSON.parse(t);}catch(r){throw new u("DB_ERROR",`Malformed legacy task logs: ${n}`,r)}if(!Array.isArray(e))throw new u("DB_ERROR",`Malformed legacy task logs: ${n} (expected an array)`);try{return e.map((r,s)=>wn(r,s))}catch(r){throw r instanceof u?new u("DB_ERROR",`Malformed legacy task logs: ${n}`,r):r}}function yn(n){if(n.log_storage!=="blob"&&n.log_storage!=="events")throw new u("DB_ERROR",`Invalid task log storage for task: ${n.id}`);if(!Number.isInteger(n.last_log_seq)||n.last_log_seq<0)throw new u("DB_ERROR",`Invalid task log sequence for task: ${n.id}`);if(!Number.isInteger(n.log_revision)||n.log_revision<0)throw new u("DB_ERROR",`Invalid task log revision for task: ${n.id}`);return n.log_storage}function Tn(n){return {taskId:n.id,source:yn(n),revision:n.log_revision,lastSeq:n.last_log_seq}}function ns(n){if(!Number.isInteger(n)||n<0)throw new u("VALIDATION","Task log tail limit must be a non-negative integer")}var se=class extends Y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(e))throw new u("NOT_FOUND","Database not found");let r=A(e);if(t)try{nt(r.db,e);}catch(s){throw r.close(),s}return r}findStateRow(t,e){return t.db.select({id:o.id,log_storage:o.log_storage,last_log_seq:o.last_log_seq,log_revision:o.log_revision,logs:o.logs}).from(o).where(eq(o.id,e)).limit(1).get()}findStateRowInTransaction(t,e){return t.select({id:o.id,log_storage:o.log_storage,last_log_seq:o.last_log_seq,log_revision:o.log_revision,logs:o.logs}).from(o).where(eq(o.id,e)).limit(1).get()}requireStateRowInTransaction(t,e){let r=this.findStateRowInTransaction(t,e);if(!r)throw new u("NOT_FOUND",`Task not found: ${e}`);return r}appendLog(t,e){return this.appendLogs(t,[e])}appendLogs(t,e){let r=e.map((i,a)=>wn(i,a));if(r.length===0){let i=this.getLogState(t);if(!i)throw new u("NOT_FOUND",`Task not found: ${t}`);return i}let s=this.openHandle(true);try{return s.db.transaction(a=>{let d=this.requireStateRowInTransaction(a,t),c=yn(d);if(c==="blob"){let g=kn(t,d.logs);if(a.update(o).set({logs:JSON.stringify([...g,...r]),log_revision:sql`${o.log_revision} + 1`}).where(eq(o.id,t)).run().changes!==1)throw new u("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:c,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let l=d.last_log_seq+1,_=d.last_log_seq+r.length;if(a.insert(rt).values(r.map((g,f)=>({task_id:t,seq:l+f,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(o).set({last_log_seq:_,log_revision:sql`${o.log_revision} + 1`}).where(eq(o.id,t)).run().changes!==1)throw new u("NOT_FOUND",`Task not found: ${t}`);return {taskId:t,source:c,revision:d.log_revision+1,lastSeq:_}},{behavior:"immediate"})}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to append task log",i)}finally{s.close();}}getLogState(t){if(!this.dbExists())return;let e=this.openHandle(false);try{let r=this.findStateRow(e,t);return r?Tn(r):void 0}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to read task log state",r)}finally{e.close();}}readLogs(t){return this.readLogsInternal(t)}readLogsTail(t,e){return ns(e),this.readLogsInternal(t,e)}readTail(t,e){return this.readLogsTail(t,e)}readLogsInternal(t,e){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(s=>{let i=this.findStateRowInTransaction(s,t);if(!i)return;let a=Tn(i);if(a.source==="blob"){let _=kn(t,i.logs);return {...a,entries:e===void 0?_:_.slice(Math.max(0,_.length-e))}}let d=s.select({seq:rt.seq,timestamp:rt.timestamp,level:rt.level,message:rt.message}).from(rt).where(eq(rt.task_id,t)).orderBy(e===void 0?asc(rt.seq):desc(rt.seq)),l=(e===void 0?d.all():d.limit(e).all()).map(({timestamp:_,level:p,message:g})=>({timestamp:_,level:p,message:g}));return e!==void 0&&l.reverse(),{...a,entries:l}},{behavior:"deferred"})}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to read task logs",s)}finally{r.close();}}};var Ce=40,ft="2026-05-09",ds="0.8.9-rc.13",mt=10,kt=parseInt(ds.split("rc.")[1]);function En(){let n=sql`
|
|
17
|
+
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(n.instance_id,n.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(n.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(n.requested_at)}));var yr=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")},n=>({idCheck:check("projects_id_ck",sql`${n.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${n.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(${n.stages_json}) AND json_type(${n.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${n.stage_index} >= 1`)}));sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>yr.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()},n=>({idCheck:check("project_criteria_id_ck",sql`${n.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${n.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${n.evidence_json}) AND json_type(${n.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(n.project_id,n.position)}));sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>yr.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()},n=>({idCheck:check("project_events_id_ck",sql`${n.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(n.project_id,n.seq)}));var Ht=["THREAD_STATE","THREAD_PRIORITY"],Pt=["gray","blue","violet","green","amber","orange","red","pink"],m=sqliteTable("common_codes",{code_group:text("code_group").notNull(),code:text("code").notNull(),code_name:text("code_name"),color:text("color").notNull().default("gray"),sort_order:integer("sort_order").notNull(),workspace_id:text("workspace_id"),is_builtin:integer("is_builtin").notNull().default(0),is_archived:integer("is_archived").notNull().default(0),metadata:text("metadata"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},n=>({pk:primaryKey({columns:[n.code_group,n.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${n.metadata} IS NULL OR (json_valid(${n.metadata}) AND json_type(${n.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${n.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${n.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(n.code_group,n.is_archived,n.sort_order)}));var Er=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Rr=["user","agent","system"],Ir=["auto","manual"],Sr=["decision","judgment","issue","result","pivot"];var vr=["queued","running","completed","failed"],O=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},n=>({typeCheck:check("thread_events_type_ck",sql`${n.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:check("thread_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(n.thread_id,n.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(n.thread_id,n.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(n.thread_id,n.seq)})),S=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),request_id:text("request_id").notNull(),status:text("status").notNull(),detector_version:text("detector_version").notNull(),requested_at:text("requested_at").notNull(),started_at:text("started_at"),completed_at:text("completed_at"),error_code:text("error_code"),previous_auto_count:integer("previous_auto_count"),new_auto_count:integer("new_auto_count")},n=>({statusCheck:check("thread_highlight_runs_status_ck",sql`${n.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:check("thread_highlight_runs_counts_ck",sql`(${n.previous_auto_count} IS NULL OR ${n.previous_auto_count} >= 0) AND (${n.new_auto_count} IS NULL OR ${n.new_auto_count} >= 0)`),threadRequestUnique:uniqueIndex("thread_highlight_runs_thread_request_uq").on(n.thread_id,n.request_id),inProgressThreadUnique:uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(n.thread_id).where(sql`${n.status} IN ('queued', 'running')`),threadStatusRequestedIndex:index("idx_thread_highlight_runs_thread_status_requested").on(n.thread_id,n.status,n.requested_at)})),w=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},n=>({sourceCheck:check("thread_highlights_source_ck",sql`${n.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${n.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${n.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${n.status} = 'dismissed' OR (${n.text} IS NOT NULL AND length(${n.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${n.covers_from_task_id}) > 0 AND length(${n.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${n.source} = 'manual' OR (${n.source} = 'auto' AND ${n.source_task_id} IS NOT NULL AND ${n.detector_version} IS NOT NULL AND ${n.content_fingerprint} IS NOT NULL AND length(${n.source_task_id}) > 0 AND length(${n.detector_version}) > 0 AND length(${n.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(n.thread_id,n.status,n.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(n.thread_id,n.covers_from_task_id,n.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(n.thread_id,n.source_task_id,n.detector_version,n.content_fingerprint).where(sql`${n.source} = 'auto'`)}));function Nr(n){let e=n.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let t=e.lastIndexOf("/");return t>=0&&(e=e.slice(t+1)),e=e.replace(/-\d{8}$/,""),e}function xr(n,e){let t=e===void 0?"":` at index ${e}`;if(!n||typeof n!="object")throw new u("VALIDATION",`Task log entry${t} must be an object`);if(typeof n.timestamp!="string"||typeof n.level!="string"||typeof n.message!="string")throw new u("VALIDATION",`Task log entry${t} must contain string timestamp, level, and message fields`);return {timestamp:n.timestamp,level:n.level,message:n.message}}function Or(n,e){if(e===null||e.trim()==="")return [];let t;try{t=JSON.parse(e);}catch(r){throw new u("DB_ERROR",`Malformed legacy task logs: ${n}`,r)}if(!Array.isArray(t))throw new u("DB_ERROR",`Malformed legacy task logs: ${n} (expected an array)`);try{return t.map((r,s)=>xr(r,s))}catch(r){throw r instanceof u?new u("DB_ERROR",`Malformed legacy task logs: ${n}`,r):r}}function Dr(n){if(n.log_storage!=="blob"&&n.log_storage!=="events")throw new u("DB_ERROR",`Invalid task log storage for task: ${n.id}`);if(!Number.isInteger(n.last_log_seq)||n.last_log_seq<0)throw new u("DB_ERROR",`Invalid task log sequence for task: ${n.id}`);if(!Number.isInteger(n.log_revision)||n.log_revision<0)throw new u("DB_ERROR",`Invalid task log revision for task: ${n.id}`);return n.log_storage}function br(n){return {taskId:n.id,source:Dr(n),revision:n.log_revision,lastSeq:n.last_log_seq}}function hs(n){if(!Number.isInteger(n)||n<0)throw new u("VALIDATION","Task log tail limit must be a non-negative integer")}var gt=class extends Z{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let s=dirname(t);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(t))throw new u("NOT_FOUND","Database not found");let r=$(t);if(e)try{de(r.db,t);}catch(s){throw r.close(),s}return r}findStateRow(e,t){return e.db.select({id:o.id,log_storage:o.log_storage,last_log_seq:o.last_log_seq,log_revision:o.log_revision,logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get()}findStateRowInTransaction(e,t){return e.select({id:o.id,log_storage:o.log_storage,last_log_seq:o.last_log_seq,log_revision:o.log_revision,logs:o.logs}).from(o).where(eq(o.id,t)).limit(1).get()}requireStateRowInTransaction(e,t){let r=this.findStateRowInTransaction(e,t);if(!r)throw new u("NOT_FOUND",`Task not found: ${t}`);return r}appendLog(e,t){return this.appendLogs(e,[t])}appendLogs(e,t){let r=t.map((i,a)=>xr(i,a));if(r.length===0){let i=this.getLogState(e);if(!i)throw new u("NOT_FOUND",`Task not found: ${e}`);return i}let s=this.openHandle(true);try{return s.db.transaction(a=>{let d=this.requireStateRowInTransaction(a,e),c=Dr(d);if(c==="blob"){let g=Or(e,d.logs);if(a.update(o).set({logs:JSON.stringify([...g,...r]),log_revision:sql`${o.log_revision} + 1`}).where(eq(o.id,e)).run().changes!==1)throw new u("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let l=d.last_log_seq+1,h=d.last_log_seq+r.length;if(a.insert(ce).values(r.map((g,f)=>({task_id:e,seq:l+f,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(o).set({last_log_seq:h,log_revision:sql`${o.log_revision} + 1`}).where(eq(o.id,e)).run().changes!==1)throw new u("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:d.log_revision+1,lastSeq:h}},{behavior:"immediate"})}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to append task log",i)}finally{s.close();}}getLogState(e){if(!this.dbExists())return;let t=this.openHandle(false);try{let r=this.findStateRow(t,e);return r?br(r):void 0}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to read task log state",r)}finally{t.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,t){return hs(t),this.readLogsInternal(e,t)}readTail(e,t){return this.readLogsTail(e,t)}readLogsInternal(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(s=>{let i=this.findStateRowInTransaction(s,e);if(!i)return;let a=br(i);if(a.source==="blob"){let h=Or(e,i.logs);return {...a,entries:t===void 0?h:h.slice(Math.max(0,h.length-t))}}let d=s.select({seq:ce.seq,timestamp:ce.timestamp,level:ce.level,message:ce.message}).from(ce).where(eq(ce.task_id,e)).orderBy(t===void 0?asc(ce.seq):desc(ce.seq)),l=(t===void 0?d.all():d.limit(t).all()).map(({timestamp:h,level:p,message:g})=>({timestamp:h,level:p,message:g}));return t!==void 0&&l.reverse(),{...a,entries:l}},{behavior:"deferred"})}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to read task logs",s)}finally{r.close();}}};var Bt=40,Ee="2026-05-09",Ts="0.8.9-rc.13",Re=10,Ie=parseInt(Ts.split("rc.")[1]);function Lr(){let n=sql`
|
|
18
18
|
CASE
|
|
19
19
|
WHEN ${o.model} LIKE 'claude-%' OR ${o.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
20
20
|
WHEN ${o.model} LIKE 'gpt-%' OR ${o.model} LIKE 'codex-%' THEN 'codex'
|
|
@@ -25,12 +25,12 @@ ${r.join(`
|
|
|
25
25
|
WHEN ${o.model} LIKE 'qwen%' THEN 'qwen'
|
|
26
26
|
ELSE 'unknown'
|
|
27
27
|
END
|
|
28
|
-
`,
|
|
28
|
+
`,e=sql`json_extract(${o.metadata}, '$.provider')`,t=sql`trim(${e})`,r=sql`substr(${t}, 1, instr(${t}, '/') - 1)`,s=sql`
|
|
29
29
|
CASE
|
|
30
|
-
WHEN instr(${
|
|
30
|
+
WHEN instr(${t}, '/') > 0
|
|
31
31
|
AND ${r} IN ('cli', 'acp', 'api', 'plugin', 'remote')
|
|
32
|
-
THEN substr(${
|
|
33
|
-
ELSE ${
|
|
32
|
+
THEN substr(${t}, instr(${t}, '/') + 1)
|
|
33
|
+
ELSE ${t}
|
|
34
34
|
END
|
|
35
35
|
`;return sql`
|
|
36
36
|
CASE
|
|
@@ -39,21 +39,21 @@ ${r.join(`
|
|
|
39
39
|
WHEN json_type(${o.metadata}, '$') IS NOT 'object' THEN 'unknown'
|
|
40
40
|
WHEN json_type(${o.metadata}, '$.provider') IS NULL THEN ${n}
|
|
41
41
|
WHEN json_type(${o.metadata}, '$.provider') IS NOT 'text' THEN 'unknown'
|
|
42
|
-
WHEN ${
|
|
42
|
+
WHEN ${t} = '' THEN 'unknown'
|
|
43
43
|
WHEN trim(${s}) = '' THEN 'unknown'
|
|
44
44
|
ELSE ${s}
|
|
45
45
|
END
|
|
46
|
-
`}var
|
|
46
|
+
`}var ks=new Set(["workflow","mcp"]),$r=600*1e3,mt=class extends Z{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new gt({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let s=dirname(t);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(t))throw new u("NOT_FOUND","Database not found");let r=$(t);if(e)try{de(r.db,t);}catch(s){throw r.close(),s}return r}startTask(e){let t=this.openHandle(true);try{let r={id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},s=i=>{t.db.insert(o).values(i).onConflictDoUpdate({target:o.id,set:{pid:sql`COALESCE(excluded.pid, ${o.pid})`},setWhere:eq(o.status,"running")}).run();};try{s(r);}catch(i){let a=i instanceof Error?i.message:typeof i=="object"&&i!==null&&"message"in i?String(i.message):String(i);if(!/log_storage/i.test(a)||!/no such column|no column named/i.test(a))throw i;t.runRaw(`INSERT INTO tasks (
|
|
47
47
|
id, agent_id, prompt, mode, status, started_at, pid,
|
|
48
48
|
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
49
49
|
workspace_id, project_id, platform, crewx_version, thread_id,
|
|
50
50
|
model, rendered_prompt, coding_agent_command
|
|
51
51
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
52
52
|
ON CONFLICT(id) DO UPDATE SET pid = COALESCE(excluded.pid, tasks.pid)
|
|
53
|
-
WHERE tasks.status = 'running'`,[r.id,r.agent_id,r.prompt,r.mode,r.status,r.started_at,r.pid,r.parent_task_id,r.caller_agent_id,r.trace_id,r.command,r.metadata,r.workspace_id,r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command]);}}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to start task",r)}finally{
|
|
53
|
+
WHERE tasks.status = 'running'`,[r.id,r.agent_id,r.prompt,r.mode,r.status,r.started_at,r.pid,r.parent_task_id,r.caller_agent_id,r.trace_id,r.command,r.metadata,r.workspace_id,r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command]);}}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to start task",r)}finally{t.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.project_id,e)).orderBy(desc(o.started_at)).all()}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to list tasks by project",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{let r=e.runEpoch??null;t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
|
|
54
54
|
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
55
55
|
model=COALESCE(?, model)
|
|
56
|
-
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[
|
|
56
|
+
WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id,r]);}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to finish task",r)}finally{t.close();}}appendLog(e,t){this.taskLogRepository.appendLog(e,t);}appendLogs(e,t){this.taskLogRepository.appendLogs(e,t);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,t){return this.taskLogRepository.readLogsTail(e,t)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(o).where(eq(o.status,"running")).orderBy(desc(o.started_at)).all()}catch(t){throw new u("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(o).orderBy(desc(o.started_at)).limit(100).all()}catch(t){throw new u("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(o).where(eq(o.id,e)).limit(1).get()??void 0}catch(r){throw new u("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:o.id,status:o.status,pid:o.pid}).from(o).where(eq(o.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(o).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(o.id,e),eq(o.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:o.id,pid:o.pid,platform:o.platform,run_epoch:o.run_epoch}).from(o).where(eq(o.status,"running")).all(),r=Date.now(),s=new Set,i=0;for(let a of t){if(a.pid){let l=!1;try{process.kill(a.pid,0),l=!0;}catch{}l||(e.db.update(o).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(o.id,a.id),eq(o.status,"running"))).run(),i++);continue}if(ks.has(a.platform??"cli"))continue;let d=`${a.id}:${a.run_epoch??0}`;s.add(d);let c=this.pidNullObservedSince.get(d);if(c===void 0){this.pidNullObservedSince.set(d,r);continue}r-c>=$r&&(e.db.update(o).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(o.id,a.id),eq(o.status,"running"))).run(),i++,this.pidNullObservedSince.delete(d));}for(let a of Array.from(this.pidNullObservedSince.keys()))s.has(a)||this.pidNullObservedSince.delete(a);return i}finally{e.close();}}reapRunningWorkflowTasks(e=$r){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString();return t.db.update(o).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(o.status,"running"),eq(o.platform,"workflow"),isNull(o.pid),lt(o.started_at,r),or(isNull(o.metadata),and(notLike(o.metadata,'%"kind":"workflow_card"%'),notLike(o.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{t.close();}}findTaskStatus(e,t){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=$(s);try{let a=t?eq(o.workspace_id,t):void 0,d=a?and(eq(o.id,e),a):eq(o.id,e),c=i.db.select().from(o).where(d).limit(1).get()??void 0;if(!c){let l=a?and(eq(o.thread_id,e),a):eq(o.thread_id,e);c=i.db.select().from(o).where(l).orderBy(desc(o.started_at)).limit(1).get()??void 0;}if(c)return c}catch(a){throw new u("DB_ERROR","Failed to find task status",a)}finally{i.close();}}}findChildTasks(e,t){let r=this.resolveDbPaths(),s=new Set,i=[];for(let a of r){if(!existsSync(a))continue;let d=$(a);try{let c=t?and(eq(o.parent_task_id,e),eq(o.workspace_id,t)):eq(o.parent_task_id,e),l=d.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of l)s.has(h.id)||(s.add(h.id),i.push(h));}catch(c){throw new u("DB_ERROR","Failed to find child tasks",c)}finally{d.close();}}return i}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?sql`
|
|
57
57
|
SELECT
|
|
58
58
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
59
59
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -61,7 +61,7 @@ ${r.join(`
|
|
|
61
61
|
COALESCE(SUM(cost_usd), 0) AS cost_usd,
|
|
62
62
|
COUNT(*) AS task_count
|
|
63
63
|
FROM tasks
|
|
64
|
-
WHERE workspace_id = ${
|
|
64
|
+
WHERE workspace_id = ${e}
|
|
65
65
|
GROUP BY workspace_id
|
|
66
66
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
67
67
|
`:sql`
|
|
@@ -74,7 +74,7 @@ ${r.join(`
|
|
|
74
74
|
FROM tasks
|
|
75
75
|
GROUP BY workspace_id
|
|
76
76
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
77
|
-
`)}catch(r){throw new u("DB_ERROR","Failed to get workspace usage summary",r)}finally{
|
|
77
|
+
`)}catch(r){throw new u("DB_ERROR","Failed to get workspace usage summary",r)}finally{t.close();}}getThreadTokenUsage(e,t){let r=this.resolveDbPaths(),s=new Set,i=0,a=0,d=0;for(let c of r){if(!existsSync(c))continue;let l=$(c);try{let h=eq(o.thread_id,e),p=t?and(h,eq(o.workspace_id,t)):h,g=l.db.select({id:o.id,input_tokens:o.input_tokens,output_tokens:o.output_tokens,cost_usd:o.cost_usd}).from(o).where(p).all();for(let f of g)s.has(f.id)||(s.add(f.id),i+=f.input_tokens??0,a+=f.output_tokens??0,d+=f.cost_usd??0);}catch(h){throw new u("DB_ERROR","Failed to get thread token usage",h)}finally{l.close();}}return {inputTokens:i,outputTokens:a,costUsd:d}}findTasksByThread(e,t,r){let s=this.resolveDbPaths(),i=new Set,a=[],d=r?.projection==="activity-log";for(let c of s){if(!existsSync(c))continue;let l=$(c);try{let h=eq(o.thread_id,e),p=t?and(h,eq(o.workspace_id,t)):h,g=d?l.db.select({id:o.id,thread_id:o.thread_id,agent_id:o.agent_id,parent_task_id:o.parent_task_id,started_at:o.started_at,completed_at:o.completed_at}).from(o).where(p).orderBy(asc(o.started_at)).all():l.db.select().from(o).where(p).orderBy(asc(o.started_at)).all();for(let f of g)i.has(f.id)||(i.add(f.id),a.push(f));}catch(h){throw new u("DB_ERROR","Failed to find tasks by thread",h)}finally{l.close();}}return a}parseWorkflowCardMetadata(e){if(!e)return {};try{let t=JSON.parse(e);return {kind:typeof t.kind=="string"?t.kind:void 0,workflowRunId:typeof t.workflowRunId=="string"?t.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let t of this.resolveDbPaths()){if(!existsSync(t))continue;let r=$(t);try{e.push(...r.db.select({id:o.id,agent_id:o.agent_id,thread_id:o.thread_id,workspace_id:o.workspace_id,platform:o.platform,status:o.status,error:o.error,completed_at:o.completed_at,duration_ms:o.duration_ms,started_at:o.started_at,metadata:o.metadata}).from(o).where(and(eq(o.platform,"workflow"),or(like(o.metadata,'%"kind":"workflow_card"%'),like(o.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(o.started_at)).all());}catch(s){throw new u("DB_ERROR","Failed to find workflow parent tasks",s)}finally{r.close();}}return e}batchFetchWorkflowCards(e,t){let r=new Map;if(e.length===0)return r;let s=new Set(e),i=new Map,a=t?eq(o.workspace_id,t):void 0,d=(c,l)=>{if(!c)return;let h=i.get(c);if(h&&l.started_at<=h)return;let p=this.parseWorkflowCardMetadata(l.metadata);p.kind!=="workflow_card"&&p.kind!=="workflow_ui_instance"||(i.set(c,l.started_at),r.set(c,{taskId:l.id,workflowRunId:p.workflowRunId,raw:l.result??void 0}));};for(let c of this.resolveDbPaths()){if(!existsSync(c))continue;let l=$(c);try{let h=and(inArray(o.thread_id,e),or(like(o.metadata,'%"kind":"workflow_card"%'),like(o.metadata,'%"kind":"workflow_ui_instance"%'))),p=l.db.select({id:o.id,thread_id:o.thread_id,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(a?and(h,a):h).all();for(let L of p)d(L.thread_id,L);let g=and(isNull(o.thread_id),or(like(o.metadata,'%"kind":"workflow_card"%'),like(o.metadata,'%"kind":"workflow_ui_instance"%'))),f=l.db.select({id:o.id,command:o.command,metadata:o.metadata,result:o.result,started_at:o.started_at}).from(o).where(a?and(g,a):g).all();for(let L of f){let N=this.extractThreadIdFromCommand(L.command);!N||!s.has(N)||d(N,L);}}catch(h){throw new u("DB_ERROR","Failed to batch fetch workflow cards",h)}finally{l.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(o.workspace_id,e.workspaceId));let s=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;s&&r.push(inArray(o.agent_id,s));let i=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;i&&r.push(inArray(o.status,i));let a=e.q??e.search;a&&r.push(like(o.prompt,`%${a}%`)),e.from&&r.push(gte(o.started_at,e.from)),e.to&&r.push(lt(o.started_at,e.to));let d=r.length>0?and(...r):void 0,c=t.db.select({count:sql`count(*)`}).from(o).where(d).get(),l=(e.sortDir??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at);return {rows:t.db.select().from(o).where(d).orderBy(l).limit(e.limit).offset(e.offset).all(),total:c?.count??0}}catch(r){throw new u("DB_ERROR","Failed to find all tasks",r)}finally{t.close();}}getAgentUsage(e,t,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(r?sql`
|
|
78
78
|
SELECT
|
|
79
79
|
t.agent_id,
|
|
80
80
|
t.workspace_id,
|
|
@@ -82,11 +82,11 @@ ${r.join(`
|
|
|
82
82
|
COALESCE(SUM(
|
|
83
83
|
COALESCE(t.input_tokens, 0)
|
|
84
84
|
+ CASE
|
|
85
|
-
WHEN t.started_at >= ${
|
|
85
|
+
WHEN t.started_at >= ${Ee}
|
|
86
86
|
AND (
|
|
87
87
|
t.crewx_version IS NULL
|
|
88
88
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
89
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
89
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Re}) AS INTEGER) < ${Ie})
|
|
90
90
|
)
|
|
91
91
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
92
92
|
ELSE 0
|
|
@@ -97,19 +97,19 @@ ${r.join(`
|
|
|
97
97
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
98
98
|
FROM tasks t
|
|
99
99
|
WHERE t.status IN ('completed', 'success')
|
|
100
|
-
AND t.started_at >= ${
|
|
101
|
-
AND t.started_at < ${
|
|
100
|
+
AND t.started_at >= ${e}
|
|
101
|
+
AND t.started_at < ${t}
|
|
102
102
|
AND t.workspace_id = ${r}
|
|
103
103
|
GROUP BY t.agent_id, t.workspace_id
|
|
104
104
|
ORDER BY (
|
|
105
105
|
COALESCE(SUM(
|
|
106
106
|
COALESCE(t.input_tokens, 0)
|
|
107
107
|
+ CASE
|
|
108
|
-
WHEN t.started_at >= ${
|
|
108
|
+
WHEN t.started_at >= ${Ee}
|
|
109
109
|
AND (
|
|
110
110
|
t.crewx_version IS NULL
|
|
111
111
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
112
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
112
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Re}) AS INTEGER) < ${Ie})
|
|
113
113
|
)
|
|
114
114
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
115
115
|
ELSE 0
|
|
@@ -125,11 +125,11 @@ ${r.join(`
|
|
|
125
125
|
COALESCE(SUM(
|
|
126
126
|
COALESCE(t.input_tokens, 0)
|
|
127
127
|
+ CASE
|
|
128
|
-
WHEN t.started_at >= ${
|
|
128
|
+
WHEN t.started_at >= ${Ee}
|
|
129
129
|
AND (
|
|
130
130
|
t.crewx_version IS NULL
|
|
131
131
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
132
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
132
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Re}) AS INTEGER) < ${Ie})
|
|
133
133
|
)
|
|
134
134
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
135
135
|
ELSE 0
|
|
@@ -140,18 +140,18 @@ ${r.join(`
|
|
|
140
140
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
141
141
|
FROM tasks t
|
|
142
142
|
WHERE t.status IN ('completed', 'success')
|
|
143
|
-
AND t.started_at >= ${
|
|
144
|
-
AND t.started_at < ${
|
|
143
|
+
AND t.started_at >= ${e}
|
|
144
|
+
AND t.started_at < ${t}
|
|
145
145
|
GROUP BY t.agent_id, t.workspace_id
|
|
146
146
|
ORDER BY (
|
|
147
147
|
COALESCE(SUM(
|
|
148
148
|
COALESCE(t.input_tokens, 0)
|
|
149
149
|
+ CASE
|
|
150
|
-
WHEN t.started_at >= ${
|
|
150
|
+
WHEN t.started_at >= ${Ee}
|
|
151
151
|
AND (
|
|
152
152
|
t.crewx_version IS NULL
|
|
153
153
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
154
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
154
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Re}) AS INTEGER) < ${Ie})
|
|
155
155
|
)
|
|
156
156
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
157
157
|
ELSE 0
|
|
@@ -159,18 +159,18 @@ ${r.join(`
|
|
|
159
159
|
), 0)
|
|
160
160
|
+ COALESCE(SUM(t.output_tokens), 0)
|
|
161
161
|
) DESC
|
|
162
|
-
`).map(a=>({agentId:a.agent_id,workspaceId:a.workspace_id??null,totalTasks:a.total_tasks,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 u("DB_ERROR","Failed to get agent usage",i)}finally{s.close();}}getAgentUsageTrendRaw(t,
|
|
162
|
+
`).map(a=>({agentId:a.agent_id,workspaceId:a.workspace_id??null,totalTasks:a.total_tasks,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 u("DB_ERROR","Failed to get agent usage",i)}finally{s.close();}}getAgentUsageTrendRaw(e,t,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{return s.db.all(r?sql`
|
|
163
163
|
SELECT
|
|
164
164
|
date(t.started_at) AS date,
|
|
165
165
|
t.agent_id,
|
|
166
166
|
COALESCE(SUM(
|
|
167
167
|
COALESCE(t.input_tokens, 0)
|
|
168
168
|
+ CASE
|
|
169
|
-
WHEN t.started_at >= ${
|
|
169
|
+
WHEN t.started_at >= ${Ee}
|
|
170
170
|
AND (
|
|
171
171
|
t.crewx_version IS NULL
|
|
172
172
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
173
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
173
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Re}) AS INTEGER) < ${Ie})
|
|
174
174
|
)
|
|
175
175
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
176
176
|
ELSE 0
|
|
@@ -181,8 +181,8 @@ ${r.join(`
|
|
|
181
181
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
182
182
|
FROM tasks t
|
|
183
183
|
WHERE t.status IN ('completed', 'success')
|
|
184
|
-
AND t.started_at >= ${
|
|
185
|
-
AND t.started_at < ${
|
|
184
|
+
AND t.started_at >= ${e}
|
|
185
|
+
AND t.started_at < ${t}
|
|
186
186
|
AND t.workspace_id = ${r}
|
|
187
187
|
GROUP BY date(t.started_at), t.agent_id
|
|
188
188
|
ORDER BY date(t.started_at) ASC
|
|
@@ -193,11 +193,11 @@ ${r.join(`
|
|
|
193
193
|
COALESCE(SUM(
|
|
194
194
|
COALESCE(t.input_tokens, 0)
|
|
195
195
|
+ CASE
|
|
196
|
-
WHEN t.started_at >= ${
|
|
196
|
+
WHEN t.started_at >= ${Ee}
|
|
197
197
|
AND (
|
|
198
198
|
t.crewx_version IS NULL
|
|
199
199
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
200
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
200
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Re}) AS INTEGER) < ${Ie})
|
|
201
201
|
)
|
|
202
202
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
203
203
|
ELSE 0
|
|
@@ -208,23 +208,23 @@ ${r.join(`
|
|
|
208
208
|
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
209
209
|
FROM tasks t
|
|
210
210
|
WHERE t.status IN ('completed', 'success')
|
|
211
|
-
AND t.started_at >= ${
|
|
212
|
-
AND t.started_at < ${
|
|
211
|
+
AND t.started_at >= ${e}
|
|
212
|
+
AND t.started_at < ${t}
|
|
213
213
|
GROUP BY date(t.started_at), t.agent_id
|
|
214
214
|
ORDER BY date(t.started_at) ASC
|
|
215
|
-
`).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 u("DB_ERROR","Failed to get agent usage trend",i)}finally{s.close();}}findTaskForStop(t
|
|
215
|
+
`).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 u("DB_ERROR","Failed to get agent usage trend",i)}finally{s.close();}}findTaskForStop(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(o).where(and(eq(o.id,e),eq(o.workspace_id,t))).limit(1).get()??void 0}catch(s){throw new u("DB_ERROR","Failed to find task for stop",s)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let t=this.openHandle(false);try{return t.db.select({id:o.id,thread_id:o.thread_id,status:o.status,result:o.result,error:o.error,started_at:o.started_at,completed_at:o.completed_at,metadata:o.metadata}).from(o).where(and(eq(o.agent_id,e.agentId),eq(o.workspace_id,e.workspaceId),sql`${o.metadata} IS NOT NULL AND json_valid(${o.metadata}) AND json_extract(${o.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(o.started_at)).limit(1).get()??null}catch(r){throw new u("DB_ERROR","Failed to find latest task by metadata",r)}finally{t.close();}}markTaskFailed(e,t,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let i=new Date().toISOString(),a=r?and(eq(o.id,e),eq(o.status,"running"),eq(o.workspace_id,r)):and(eq(o.id,e),eq(o.status,"running"));s.db.update(o).set({status:"failed",error:t,completed_at:i}).where(a).run();}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to mark task failed",i)}finally{s.close();}}findTasksByPromptHint(e,t){let r=this.resolveDbPaths(),s=new Set,i=[];for(let a of r){if(!existsSync(a))continue;let d=$(a);try{let c=t?and(like(o.prompt,`%${e}%`),eq(o.workspace_id,t)):like(o.prompt,`%${e}%`),l=d.db.select().from(o).where(c).orderBy(asc(o.started_at)).all();for(let h of l)s.has(h.id)||(s.add(h.id),i.push(h));}catch(c){throw new u("DB_ERROR","Failed to find tasks by prompt hint",c)}finally{d.close();}}return i}getProviderUsage(e,t,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let i=Lr(),a=sql`
|
|
216
216
|
COALESCE(${o.input_tokens}, 0)
|
|
217
217
|
+ CASE
|
|
218
|
-
WHEN ${o.started_at} >= ${
|
|
218
|
+
WHEN ${o.started_at} >= ${Ee}
|
|
219
219
|
AND (
|
|
220
220
|
${o.crewx_version} IS NULL
|
|
221
221
|
OR (${o.crewx_version} LIKE '0.8.%' AND ${o.crewx_version} NOT LIKE '0.8.9%')
|
|
222
|
-
OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${
|
|
222
|
+
OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${Re}) AS INTEGER) < ${Ie})
|
|
223
223
|
)
|
|
224
224
|
THEN COALESCE(${o.cached_input_tokens}, 0)
|
|
225
225
|
ELSE 0
|
|
226
226
|
END
|
|
227
|
-
`,d=r?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${
|
|
227
|
+
`,d=r?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${e} AND ${o.started_at} < ${t} AND ${o.workspace_id} = ${r}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${e} AND ${o.started_at} < ${t}`;return s.db.all(sql`
|
|
228
228
|
SELECT
|
|
229
229
|
${i} AS provider,
|
|
230
230
|
COUNT(*) AS total_tasks,
|
|
@@ -238,19 +238,19 @@ ${r.join(`
|
|
|
238
238
|
${d}
|
|
239
239
|
GROUP BY ${i}
|
|
240
240
|
ORDER BY (COALESCE(SUM(${a}), 0) + COALESCE(SUM(${o.output_tokens}), 0)) DESC
|
|
241
|
-
`).map(l=>({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}))}catch(i){throw new u("DB_ERROR","Failed to get provider usage",i)}finally{s.close();}}getModelUsage(t,
|
|
241
|
+
`).map(l=>({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}))}catch(i){throw new u("DB_ERROR","Failed to get provider usage",i)}finally{s.close();}}getModelUsage(e,t,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let i=Lr(),a=sql`
|
|
242
242
|
COALESCE(${o.input_tokens}, 0)
|
|
243
243
|
+ CASE
|
|
244
|
-
WHEN ${o.started_at} >= ${
|
|
244
|
+
WHEN ${o.started_at} >= ${Ee}
|
|
245
245
|
AND (
|
|
246
246
|
${o.crewx_version} IS NULL
|
|
247
247
|
OR (${o.crewx_version} LIKE '0.8.%' AND ${o.crewx_version} NOT LIKE '0.8.9%')
|
|
248
|
-
OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${
|
|
248
|
+
OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${Re}) AS INTEGER) < ${Ie})
|
|
249
249
|
)
|
|
250
250
|
THEN COALESCE(${o.cached_input_tokens}, 0)
|
|
251
251
|
ELSE 0
|
|
252
252
|
END
|
|
253
|
-
`,d=r?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${
|
|
253
|
+
`,d=r?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${e} AND ${o.started_at} < ${t} AND ${o.workspace_id} = ${r}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${e} AND ${o.started_at} < ${t}`,c=s.db.all(sql`
|
|
254
254
|
SELECT
|
|
255
255
|
${o.model} AS model,
|
|
256
256
|
${i} AS provider,
|
|
@@ -264,7 +264,7 @@ ${r.join(`
|
|
|
264
264
|
FROM ${o}
|
|
265
265
|
${d}
|
|
266
266
|
GROUP BY ${o.model}, ${i}
|
|
267
|
-
`),l=new Map;for(let
|
|
267
|
+
`),l=new Map;for(let h of c){let p=Nr(h.model??""),g=JSON.stringify([h.provider,p]),f=l.get(g);f?(f.totalTasks+=h.total_tasks,f.inputTokens+=h.input_tokens,f.outputTokens+=h.output_tokens,f.cachedInputTokens+=h.cached_input_tokens,f.costUsd+=h.cost_usd,f.totalTokens+=h.input_tokens+h.output_tokens,f.activeDurationMs+=h.active_duration_ms??0,h.last_active_at&&(!f.lastActiveAt||h.last_active_at>f.lastActiveAt)&&(f.lastActiveAt=h.last_active_at)):l.set(g,{model:p,provider:h.provider,totalTasks:h.total_tasks,inputTokens:h.input_tokens,outputTokens:h.output_tokens,cachedInputTokens:h.cached_input_tokens,costUsd:h.cost_usd,totalTokens:h.input_tokens+h.output_tokens,activeDurationMs:h.active_duration_ms??0,lastActiveAt:h.last_active_at??null});}return Array.from(l.values()).sort((h,p)=>p.costUsd-h.costUsd)}catch(i){throw new u("DB_ERROR","Failed to get model usage",i)}finally{s.close();}}getTasksForReport(e,t,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let i=r?sql`WHERE ${o.started_at} >= ${e} AND ${o.started_at} < ${t} AND ${o.workspace_id} = ${r}`:sql`WHERE ${o.started_at} >= ${e} AND ${o.started_at} < ${t}`;return s.db.all(sql`
|
|
268
268
|
SELECT
|
|
269
269
|
${o.thread_id} AS thread_id,
|
|
270
270
|
${o.agent_id} AS agent_id,
|
|
@@ -275,19 +275,19 @@ ${r.join(`
|
|
|
275
275
|
FROM ${o}
|
|
276
276
|
${i}
|
|
277
277
|
ORDER BY ${o.started_at} ASC
|
|
278
|
-
`).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 u("DB_ERROR","Failed to get tasks for report",i)}finally{s.close();}}getDelegationMatrix(t,
|
|
278
|
+
`).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 u("DB_ERROR","Failed to get tasks for report",i)}finally{s.close();}}getDelegationMatrix(e,t,r){if(!this.dbExists())return {edges:[],truncated:false};let s=this.openHandle(false);try{let i=sql`
|
|
279
279
|
COALESCE(${o.input_tokens}, 0)
|
|
280
280
|
+ CASE
|
|
281
|
-
WHEN ${o.started_at} >= ${
|
|
281
|
+
WHEN ${o.started_at} >= ${Ee}
|
|
282
282
|
AND (
|
|
283
283
|
${o.crewx_version} IS NULL
|
|
284
284
|
OR (${o.crewx_version} LIKE '0.8.%' AND ${o.crewx_version} NOT LIKE '0.8.9%')
|
|
285
|
-
OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${
|
|
285
|
+
OR (${o.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${o.crewx_version}, ${Re}) AS INTEGER) < ${Ie})
|
|
286
286
|
)
|
|
287
287
|
THEN COALESCE(${o.cached_input_tokens}, 0)
|
|
288
288
|
ELSE 0
|
|
289
289
|
END
|
|
290
|
-
`,a=r?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${
|
|
290
|
+
`,a=r?sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${e} AND ${o.started_at} < ${t} AND ${o.workspace_id} = ${r}`:sql`WHERE ${o.status} IN ('completed', 'success') AND ${o.started_at} >= ${e} AND ${o.started_at} < ${t}`,d=s.db.all(sql`
|
|
291
291
|
SELECT
|
|
292
292
|
${o.caller_agent_id} AS caller_agent_id,
|
|
293
293
|
${o.agent_id} AS agent_id,
|
|
@@ -298,12 +298,12 @@ ${r.join(`
|
|
|
298
298
|
${a}
|
|
299
299
|
GROUP BY ${o.caller_agent_id}, ${o.agent_id}
|
|
300
300
|
ORDER BY task_count DESC, ${o.caller_agent_id} ASC, ${o.agent_id} ASC
|
|
301
|
-
LIMIT ${
|
|
302
|
-
`),c=d.length>
|
|
301
|
+
LIMIT ${Bt+1}
|
|
302
|
+
`),c=d.length>Bt;return {edges:d.slice(0,Bt).map(h=>({callerAgentId:h.caller_agent_id??null,agentId:h.agent_id,taskCount:h.task_count,totalTokens:h.input_tokens+h.output_tokens,outputTokens:h.output_tokens})),truncated:c}}catch(i){throw new u("DB_ERROR","Failed to get delegation matrix",i)}finally{s.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(o.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(inArray(o.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(inArray(o.status,e.statuses)),e.from&&r.push(gte(o.started_at,e.from)),e.to&&r.push(lt(o.started_at,e.to));let s=r.length>0?and(...r):void 0,i=(e.order??"DESC")==="ASC"?asc(o.started_at):desc(o.started_at),a={id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id};return e.limit?t.db.select(a).from(o).where(s).orderBy(i).limit(e.limit).all():t.db.select(a).from(o).where(s).orderBy(i).all()}catch(r){throw new u("DB_ERROR","Failed to find task evidence",r)}finally{t.close();}}findThreadChains(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=e.maxThreads??8,s=e.maxTurnsPerThread??4,i=[isNotNull(o.thread_id),isNull(o.parent_task_id),isNull(o.caller_agent_id),or(isNull(o.platform),ne(o.platform,"workflow")),or(isNull(o.metadata),and(notLike(o.metadata,'%"kind":"workflow_card"%'),notLike(o.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(o.metadata),notLike(o.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&i.push(eq(o.workspace_id,e.workspaceId)),e.from&&i.push(gte(o.started_at,e.from)),e.to&&i.push(lt(o.started_at,e.to));let a=t.db.select({id:o.id,agent_id:o.agent_id,status:o.status,prompt:o.prompt,started_at:o.started_at,completed_at:o.completed_at,thread_id:o.thread_id}).from(o).where(and(...i)).orderBy(asc(o.started_at),asc(o.id)).all(),d=new Map;for(let l of a){if(!l.thread_id)continue;let h={id:l.id,agentId:l.agent_id,status:l.status,prompt:l.prompt,startedAt:l.started_at,completedAt:l.completed_at},p=d.get(l.thread_id);p?p.push(h):d.set(l.thread_id,[h]);}let c=[];for(let[l,h]of d){let p=h.filter(g=>g.agentId===e.targetAgentId).length;p<2||c.push({threadId:l,targetAgentTurnCount:p,turns:h});}return c.sort((l,h)=>{let p=l.turns[l.turns.length-1].startedAt,g=h.turns[h.turns.length-1].startedAt;return p<g?1:p>g?-1:0}),c.slice(0,r).map(l=>({threadId:l.threadId,targetAgentTurnCount:l.targetAgentTurnCount,turns:l.turns.slice(-s)}))}catch(r){throw new u("DB_ERROR","Failed to find thread chains",r)}finally{t.close();}}};var ys=200,Es=200;function Rs(n){if(typeof n!="object"||n===null||!("code"in n))return;let e=n.code;return typeof e=="string"&&e.length>0?e:void 0}function Is(n){let e=n instanceof u?n.code:void 0,t=n instanceof u?n.cause:n,r=Rs(t);return {code:e??r??"DB_ERROR",cause:r??(t instanceof Error?t.name:e??typeof t)}}function Pr(n){return Buffer.byteLength(JSON.stringify(n),"utf8")}var Ut=class extends Ne{name="sqlite-tracing";unsubs=[];dbPath;version;taskRepo;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super(),this.dbPath=join(e?.dbRoot??homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown";}attach(e){let t=new mt({dbPath:this.dbPath});this.taskRepo=t;let r=process.cwd(),i=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))?ar(r):null,a=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let c=d.callerAgentId??null,l=d.parentTaskId??null,h=d.rootTraceId??d.traceId,p=d.metadata?JSON.stringify(d.metadata):JSON.stringify({provider:d.provider??"cli/claude"});t.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:c,parentTaskId:l,traceId:h,metadata:p,threadId:d.threadId??null});}catch{}}),e.on("task:output",d=>{try{this.enqueueLog(d.traceId,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(c){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(c,[l],Pr(l));}}),e.on("task:end",d=>{try{this.flushTaskLogs(d.traceId);let c=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null,l=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{}}):null;t.finishTask({id:d.traceId,status:d.error?"failed":"success",result:d.result??null,error:l,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:c});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers(),this.unsubs.forEach(t=>t()),this.unsubs=[],this.queues.clear(),this.taskRepo=void 0;}}getMetrics(){let e=0,t=0;for(let r of this.queues.values())e+=r.entries.length,t+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:t}}enqueueLog(e,t){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(t),r.bytes+=Pr(t),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=ys){this.flushTaskLogs(e);return}if(!r.timer){let s=setTimeout(()=>{let i=this.queues.get(e);!i||i.timer!==s||(i.timer=void 0,this.flushTaskLogs(e));},Es);r.timer=s;}}flushTaskLogs(e){let t=this.queues.get(e);if(!t||t.entries.length===0){t?.timer&&clearTimeout(t.timer),this.queues.delete(e);return}t.timer&&(clearTimeout(t.timer),t.timer=void 0);let r=t.entries,s=t.bytes;t.entries=[],t.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(a){this.recordAppendFailure(a,r,s);}let i=this.queues.get(e);i&&i.entries.length===0&&(i.timer&&clearTimeout(i.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,t,r){let s=Is(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=t.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[s.code]=(this.metrics.appendFailureByCode[s.code]??0)+1,this.metrics.appendFailureByCause[s.cause]=(this.metrics.appendFailureByCause[s.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:s.code,cause:s.cause,pendingEntries:t.length,pendingBytes:r});}};var Be=class extends u{reason;constructor(e,t=e){super("VALIDATION",t),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function Ye(n){if(!n)return {};try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Cs(n){let t=Ye(n).threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return {priority:null,state:null};let r=t;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}var Tt=class extends Z{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let s=dirname(t);existsSync(s)||mkdirSync(s,{recursive:true});}else if(!existsSync(t))throw new u("NOT_FOUND","Database not found");let r=$(t);if(e)try{de(r.db,t);}catch(s){throw r.close(),s}return r}validateWorkspaceId(e,t){return e.db.select({id:Me.id}).from(Me).where(eq(Me.id,t)).limit(1).get()?t:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
303
303
|
SELECT 1 FROM tasks parent
|
|
304
|
-
WHERE parent.id = ${
|
|
305
|
-
AND parent.thread_id = ${
|
|
306
|
-
)`)}findAllThreads(
|
|
304
|
+
WHERE parent.id = ${e}.parent_task_id
|
|
305
|
+
AND parent.thread_id = ${e}.thread_id
|
|
306
|
+
)`)}findAllThreads(e){let t=this.resolveDbPaths(),r=new Set,s=[];for(let i of t){if(!existsSync(i))continue;let a=$(i);try{let d=e?eq(_.workspace_id,e):void 0,c=a.db.select().from(_).where(d).orderBy(desc(_.updated_at)).all();for(let l of c)r.has(l.id)||(r.add(l.id),s.push(l));}catch(d){throw new u("DB_ERROR","Failed to find all threads",d)}finally{a.close();}}return s}findThreadsByIdsOrTitles(e,t){if(e.length===0)return [];let r=this.resolveDbPaths(),s=new Set,i=[];for(let a of r){if(!existsSync(a))continue;let d=$(a);try{let c=or(inArray(_.id,e),inArray(_.title,e)),l=t?and(c,eq(_.workspace_id,t)):c,h=d.db.select().from(_).where(l).orderBy(desc(_.updated_at)).all();for(let p of h)s.has(p.id)||(s.add(p.id),i.push(p));}catch(c){throw new u("DB_ERROR","Failed to find threads by ids or titles",c)}finally{d.close();}}return i}findThreadById(e,t){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=$(s);try{let a=eq(_.id,e),d=t?and(a,eq(_.workspace_id,t)):a,c=i.db.select().from(_).where(d).limit(1).get()??void 0;if(c)return c}catch(a){throw new u("DB_ERROR","Failed to find thread by id",a)}finally{i.close();}}}threadExists(e,t){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=$(s);try{let a=eq(_.id,e),d=t?and(a,eq(_.workspace_id,t)):a;if(i.db.select({id:_.id}).from(_).where(d).limit(1).get())return !0}catch(a){throw new u("DB_ERROR","Failed to check thread existence",a)}finally{i.close();}}return false}aggregateTaskStats(e,t){let r=this.resolveDbPaths(),s=0,i=0,a=0,d=0,c=0,l=new Set;for(let h of r){if(!existsSync(h))continue;let p=$(h);try{let g=p.db.get(sql`
|
|
307
307
|
SELECT
|
|
308
308
|
count(*) AS cnt,
|
|
309
309
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -311,55 +311,55 @@ ${r.join(`
|
|
|
311
311
|
COALESCE(SUM(child.cached_input_tokens), 0) AS total_cached,
|
|
312
312
|
COALESCE(SUM(child.cost_usd), 0) AS total_cost
|
|
313
313
|
FROM tasks child
|
|
314
|
-
WHERE child.thread_id = ${
|
|
314
|
+
WHERE child.thread_id = ${e}
|
|
315
315
|
AND ${this.topLevelTaskPredicateSql()}
|
|
316
|
-
${
|
|
316
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
317
317
|
`);g&&(s+=g.cnt,i+=g.total_input,a+=g.total_output,d+=g.total_cached,c+=g.total_cost);let f=p.db.all(sql`
|
|
318
318
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
319
|
-
WHERE child.thread_id = ${
|
|
319
|
+
WHERE child.thread_id = ${e}
|
|
320
320
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
321
321
|
AND ${this.topLevelTaskPredicateSql()}
|
|
322
|
-
${
|
|
323
|
-
`);for(let
|
|
322
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
323
|
+
`);for(let L of f)l.add(L.agent_id);}catch(g){throw new u("DB_ERROR","Failed to aggregate task stats",g)}finally{p.close();}}return {taskCount:s,inputTokens:i,outputTokens:a,cachedInputTokens:d,costUsd:c,agentIds:Array.from(l)}}findTopLevelTasks(e,t,r){let s=this.resolveDbPaths(),i=new Set,a=[];for(let d of s){if(!existsSync(d))continue;let c=$(d);try{let l;r!==void 0?l=c.db.all(sql`
|
|
324
324
|
SELECT * FROM (
|
|
325
325
|
SELECT child.*,
|
|
326
326
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
327
327
|
FROM tasks child
|
|
328
|
-
WHERE child.thread_id = ${
|
|
328
|
+
WHERE child.thread_id = ${e}
|
|
329
329
|
AND ${this.topLevelTaskPredicateSql()}
|
|
330
|
-
${
|
|
330
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
331
331
|
) ranked
|
|
332
332
|
WHERE rn <= ${r}
|
|
333
333
|
ORDER BY started_at ASC
|
|
334
334
|
`):l=c.db.all(sql`
|
|
335
335
|
SELECT child.* FROM tasks child
|
|
336
|
-
WHERE child.thread_id = ${
|
|
336
|
+
WHERE child.thread_id = ${e}
|
|
337
337
|
AND ${this.topLevelTaskPredicateSql()}
|
|
338
|
-
${
|
|
338
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
339
339
|
ORDER BY child.started_at ASC
|
|
340
|
-
`);for(let
|
|
340
|
+
`);for(let h of l)i.has(h.id)||(i.add(h.id),a.push(h));}catch(l){throw new u("DB_ERROR","Failed to find top-level tasks",l)}finally{c.close();}}if(r!==void 0&&s.length>1){let d=new Map;for(let c of a){let l=c.agent_id??"";d.has(l)||d.set(l,[]),d.get(l).push(c);}a=[];for(let c of d.values())c.sort((l,h)=>(h.started_at??"").localeCompare(l.started_at??"")),a.push(...c.slice(0,r));a.sort((c,l)=>(c.started_at??"").localeCompare(l.started_at??""));}return a}findAllTasks(e,t){let r=this.resolveDbPaths(),s=new Set,i=[];for(let a of r){if(!existsSync(a))continue;let d=$(a);try{let c=eq(o.thread_id,e),l=t?and(c,eq(o.workspace_id,t)):c,h=d.db.select().from(o).where(l).orderBy(asc(o.started_at)).all();for(let p of h)s.has(p.id)||(s.add(p.id),i.push(p));}catch(c){throw new u("DB_ERROR","Failed to find all tasks for thread",c)}finally{d.close();}}return i}findTaskById(e,t,r){let s=this.resolveDbPaths();for(let i of s){if(!existsSync(i))continue;let a=$(i);try{let d=and(eq(o.id,t),eq(o.thread_id,e)),c=r?and(d,eq(o.workspace_id,r)):d,l=a.db.select().from(o).where(c).limit(1).get();if(!l)continue;let h=a.db.select().from(o).where(eq(o.parent_task_id,l.id)).orderBy(asc(o.started_at)).all();return {task:l,children:h}}catch(d){throw new u("DB_ERROR","Failed to find task by id",d)}finally{a.close();}}}batchFetchTasksQuery(e,t){return sql`
|
|
341
341
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
342
342
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
343
343
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
344
344
|
child.cost_usd, child.error
|
|
345
345
|
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
346
|
-
WHERE child.thread_id IN (${sql.join(
|
|
346
|
+
WHERE child.thread_id IN (${sql.join(e.map(r=>sql`${r}`),sql`, `)})
|
|
347
347
|
AND ${this.topLevelTaskPredicateSql()}
|
|
348
|
-
${
|
|
348
|
+
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
349
349
|
ORDER BY child.started_at ASC
|
|
350
|
-
`}batchFetchTasks(t
|
|
350
|
+
`}batchFetchTasks(e,t){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let i of s){if(!existsSync(i))continue;let a=$(i);try{let d=a.db.all(this.batchFetchTasksQuery(e,t));for(let c of d){let l=c.thread_id;r.has(l)||r.set(l,[]),r.get(l).push(c);}}catch(d){throw new u("DB_ERROR","Failed to batch fetch tasks",d)}finally{a.close();}}return r}explainBatchFetchTasksPlan(e,t){let r=this.resolveDbPaths();for(let s of r){if(!existsSync(s))continue;let i=$(s);try{return i.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,t)}`).map(d=>d.detail)}finally{i.close();}}return []}updateThreadTitle(e,t,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let i=eq(_.id,e),a=r?and(i,eq(_.workspace_id,r)):i;if(!s.db.select({id:_.id}).from(_).where(a).limit(1).get())return;s.db.update(_).set({title:t,title_locked:1,updated_at:new Date().toISOString()}).where(eq(_.id,e)).run();}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to update thread title",i)}finally{s.close();}}upsertThread(e,t){let r=this.openHandle(true);try{let s=t.workspaceId?this.validateWorkspaceId(r,t.workspaceId):null,i=new Date().toISOString();if(r.db.select({id:_.id,message_count:_.message_count}).from(_).where(eq(_.id,e)).limit(1).get()){let d={updated_at:i};t.title!==void 0&&(d.title=t.title),t.titleLocked!==void 0&&(d.title_locked=t.titleLocked?1:0),r.db.update(_).set(d).where(eq(_.id,e)).run();}else r.db.insert(_).values({id:e,platform:t.platform,workspace_id:s,title:t.title??null,title_locked:t.titleLocked?1:0,message_count:0,created_at:i,updated_at:i}).run();}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to upsert thread",s)}finally{r.close();}}ensureThread(e,t,r){let s=this.openHandle(true);try{let i=r?this.validateWorkspaceId(s,r):null,a=s.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(eq(_.id,e)).limit(1).get();if(a){i&&!a.workspace_id&&s.db.update(_).set({workspace_id:i}).where(eq(_.id,e)).run();return}let d=new Date().toISOString();s.db.insert(_).values({id:e,platform:t,workspace_id:i,message_count:0,created_at:d,updated_at:d}).run();}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to ensure thread",i)}finally{s.close();}}saveUserMessage(e,t,r){if(!this.dbExists())return {firstMessage:false};let s=this.openHandle(true);try{let i=new Date().toISOString();return {firstMessage:s.db.transaction(d=>{let l=d.select({message_count:_.message_count}).from(_).where(eq(_.id,e)).limit(1).get()?.message_count===0;return d.run(sql`
|
|
351
351
|
UPDATE threads
|
|
352
|
-
SET first_message = COALESCE(first_message, ${
|
|
353
|
-
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${
|
|
354
|
-
last_message = ${
|
|
352
|
+
SET first_message = COALESCE(first_message, ${t}),
|
|
353
|
+
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${t}, 1, 60) ELSE title END,
|
|
354
|
+
last_message = ${t},
|
|
355
355
|
message_count = message_count + 1,
|
|
356
356
|
updated_at = ${i}
|
|
357
|
-
WHERE id = ${
|
|
358
|
-
`),l},{behavior:"immediate"})}}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to save user message",i)}finally{s.close();}}saveAssistantMessage(t,e,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.update(h).set({last_message:e,updated_at:i}).where(eq(h.id,t)).run();}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to save assistant message",i)}finally{s.close();}}updateThread(t,e){if(!this.dbExists())return;let r=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};e.title!==void 0&&(s.title=e.title,s.title_locked=1),e.titleLocked!==void 0&&(s.title_locked=e.titleLocked?1:0),r.db.update(h).set(s).where(eq(h.id,t)).run();}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to update thread",s)}finally{r.close();}}patchThreadTitleMetadata(t,e,r){let s=e;if(!s||typeof s!="object"||Array.isArray(s))return new xt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(c=>c!=="priority"&&c!=="state"))return new xt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let a=s;if(a.priority===void 0&&a.state===void 0)return new xt("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let c of [a.priority,a.state])if(c!=null&&(typeof c!="string"||c.length===0))return new xt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let c=r?and(eq(h.id,t),eq(h.workspace_id,r)):eq(h.id,t);return d.db.transaction(l=>{let _=l.select({metadata:h.metadata}).from(h).where(c).get();if(!_)return null;let p=jt(_.metadata),g=p.threadTitle,f=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};a.priority===null?delete f.priority:a.priority!==void 0&&(f.priority=a.priority),a.state===null?delete f.state:a.state!==void 0&&(f.state=a.state),Object.keys(f).length>0?p.threadTitle=f:delete p.threadTitle;let x=Object.keys(p).length>0?JSON.stringify(p):null,O=new Date().toISOString();l.update(h).set({metadata:x,updated_at:O}).where(c).run();let N=l.select({metadata:h.metadata}).from(h).where(c).get();if(!N)throw new u("DB_ERROR","Thread-title metadata update could not be read back");let H=Ts(N.metadata);return {threadId:t,priority:H.priority,state:H.state}},{behavior:"immediate"})}catch(c){throw c instanceof u?c:new u("DB_ERROR","Failed to patch thread-title metadata",c)}finally{d.close();}}togglePin(t,e){let r=this.openHandle(true);try{let s=e?and(eq(h.id,t),eq(h.workspace_id,e)):eq(h.id,t);return r.db.transaction(i=>{let a=i.select({pinned:h.pinned,metadata:h.metadata}).from(h).where(s).get();if(!a)return null;let d=a.pinned?0:1,c=jt(a.metadata);if(d){let l=e?and(eq(h.pinned,1),eq(h.workspace_id,e)):eq(h.pinned,1),_=i.select({metadata:h.metadata}).from(h).where(l).all(),p=null;for(let g of _){let f=jt(g.metadata);typeof f.pinOrder=="number"&&(p===null||f.pinOrder<p)&&(p=f.pinOrder);}c.pinOrder=p===null?0:p-1;}else delete c.pinOrder;return i.update(h).set({pinned:d,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(s).run(),{pinned:!!d}},{behavior:"immediate"})}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to toggle pin",s)}finally{r.close();}}reorderPins(t,e){let r=this.openHandle(true);try{r.db.transaction(s=>{for(let i=0;i<t.length;i++){let a=e?and(eq(h.id,t[i]),eq(h.workspace_id,e)):eq(h.id,t[i]),d=s.select({metadata:h.metadata}).from(h).where(a).get();if(!d)continue;let c=jt(d.metadata);c.pinOrder=i+1,s.update(h).set({metadata:JSON.stringify(c)}).where(a).run();}},{behavior:"immediate"});}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to reorder pins",s)}finally{r.close();}}toggleStar(t,e){let r=this.openHandle(true);try{let s=e?and(eq(h.id,t),eq(h.workspace_id,e)):eq(h.id,t),i=r.db.select({starred:h.starred}).from(h).where(s).get();if(!i)return null;let a=i.starred?0:1;return r.db.update(h).set({starred:a}).where(s).run(),{starred:!!a}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to toggle star",s)}finally{r.close();}}resolveOverdriveForRequest(t,e,r,s){let a=this.openHandle(true);try{let d=e?and(eq(h.id,t),eq(h.workspace_id,e)):eq(h.id,t);return a.db.transaction(l=>{let _=l.select({metadata:h.metadata}).from(h).where(d).get();if(!_)return null;let p=_.metadata?JSON.parse(_.metadata):{},g=p.overdrive??{},f=s?.defaultTurns??g.defaultTurns??3,x=s?.updatedBy??"ui",O=new Date().toISOString(),N,H,j,$t;switch(r){case "enable-count":{let Pt=s?.turns??f,Mt=s?.consumeCurrent?Math.max(Pt-1,0):Pt;N=Mt>0?"count":"off",H=Mt,j=!0,$t="count";break}case "enable-latch":{N="latch",H=0,j=!0,$t="latch";break}case "disable":{N="off",H=0,j=!1;break}default:{let Pt=g.state??"off",Mt=typeof g.remaining=="number"?g.remaining:0;if(Pt==="count"&&Mt>0){let Ue=Mt-1;Ue<=0?(N="off",H=0):(N="count",H=Ue),j=!0,$t="count";}else Pt==="latch"?(N="latch",H=0,j=!0,$t="latch"):(N="off",H=0,j=!1);break}}return p.overdrive={state:N,remaining:H,defaultTurns:f,updatedAt:O,updatedBy:x},l.update(h).set({metadata:JSON.stringify(p),updated_at:O}).where(d).run(),{applied:j,appliedMode:$t,state:N,remaining:H}},{behavior:"immediate"})}catch(d){throw d instanceof u?d:new u("DB_ERROR","Failed to resolve overdrive",d)}finally{a.close();}}};var bn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ws(n){let t=randomBytes(n*2),e="";for(let r=0;r<t.length&&e.length<n;r++){let s=t[r];s<248&&(e+=bn[s%62]);}for(;e.length<n;)e+=bn[randomBytes(1)[0]%62];return e}function Oe(n){return `${n}_${ws(8)}`}var ys=["urgent","high","medium","low"],Es=["investigating","in-progress","in-review","on-hold","done"],xn="custom:";var Rs=new Set(ys),Ss=new Set(Es);function De(n){return typeof n=="string"&&Rs.has(n)}function Le(n){if(typeof n!="string")return false;if(Ss.has(n))return true;if(n.startsWith("c_"))return n.length>2;if(!n.startsWith(xn))return false;let t=n.slice(xn.length);return t.length>=1&&t.length<=20}function On(n){if(!n)return null;try{let t=JSON.parse(n);return !t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}function $e(n){let t=On(n);if(!t)return {};let e=t.threadTitle;if(!e||typeof e!="object"||Array.isArray(e))return {};let r=e,s={};return De(r.priority)&&(s.priority=r.priority),Le(r.state)&&(s.state=r.state),s}function Dn(n,t){let e=On(n)??{},r={...$e(n)};return t.priority===null?delete r.priority:t.priority!==void 0&&(r.priority=t.priority),t.state===null?delete r.state:t.state!==void 0&&(r.state=t.state),r.priority===void 0&&r.state===void 0?delete e.threadTitle:e.threadTitle=r,Object.keys(e).length===0?null:JSON.stringify(e)}var He=class extends u{threadId;highlightId;expectedRevision;currentRevision;constructor(t,e,r,s){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${s}`),this.name="ThreadHistoryConflictError",this.threadId=t,this.highlightId=e,this.expectedRevision=r,this.currentRevision=s;}},Gt=class extends He{},As=new Set(_n),Cs=new Set(un),bs=new Set(hn),xs=new Set(pn),Os=50,Mn=100,Hn=280;function $(n){throw new u("VALIDATION",n)}function Ot(n){throw new u("NOT_FOUND",n)}function M(n,t){(typeof n!="string"||n.trim().length===0)&&$(`${t} is required`);}function de(n={}){let t=n.actor??n,e=t.actorType??"system";return As.has(e)||$(`invalid actorType: ${String(e)}`),t.actorId!==void 0&&t.actorId!==null&&typeof t.actorId!="string"&&$("actorId must be a string or null"),{actorType:e,actorId:t.actorId??null}}function Ds(n){M(n.threadId,"threadId"),n.workspaceId!==void 0&&n.workspaceId!==null&&M(n.workspaceId,"workspaceId"),n.title!==void 0&&n.title!==null&&((typeof n.title!="string"||n.title.trim().length===0)&&$("title must not be empty"),n.title.length>120&&$("title must be at most 120 characters")),n.priority!==void 0&&n.priority!==null&&!De(n.priority)&&$(`invalid priority: ${String(n.priority)}`),n.state!==void 0&&n.state!==null&&!Le(n.state)&&$(`invalid state: ${String(n.state)}`);}function Ls(n){n.beforeSeq!==void 0&&n.afterSeq!==void 0&&$("beforeSeq and afterSeq cannot be used together");for(let[e,r]of [["beforeSeq",n.beforeSeq],["afterSeq",n.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&$(`${e} must be a non-negative integer`);let t=n.limit??Os;return (!Number.isInteger(t)||t<1||t>Mn)&&$(`limit must be between 1 and ${Mn}`),t}function qn(n){typeof n!="string"&&$("text is required");let t=n.trim();return t.length===0&&$("text must not be empty"),t.length>Hn&&$(`text must be at most ${Hn} characters`),t}function Dt(n,t){return M(n??"",t),n}function Bn(n){xs.has(n)||$(`invalid highlight kind: ${String(n)}`);}function $s(n){bs.has(n)||$(`invalid highlight source: ${String(n)}`);}function Ps(n){M(n.threadId,"threadId"),M(n.workspaceId,"workspaceId");let t=n.source??"manual";$s(t),Bn(n.kind);let e=qn(n.text),r=n.coversFromTaskId??n.fromTaskId??n.taskId,s=n.coversToTaskId??n.toTaskId??n.taskId;if(t==="manual"){let _=n.taskId??(r&&s&&r===s?r:void 0),p=Dt(_,"taskId");return (r!==p||s!==p)&&$("manual highlights must cover exactly one task"),{source:t,kind:n.kind,text:e,coversFromTaskId:p,coversToTaskId:p,agentId:n.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let i=Dt(r,"coversFromTaskId"),a=Dt(s,"coversToTaskId"),d=n.sourceTaskId??i,c=n.detectorVersion??(n.idempotencyKey!==void 0?"default":null),l=n.contentFingerprint??n.idempotencyKey??null;return Dt(d??void 0,"sourceTaskId"),Dt(c??void 0,"detectorVersion"),Dt(l??void 0,"contentFingerprint"),{source:t,kind:n.kind,text:e,coversFromTaskId:i,coversToTaskId:a,agentId:n.agentId??null,sourceTaskId:d,detectorVersion:c,contentFingerprint:l}}function Wt(n){let t=$e(n.metadata);return {threadId:n.id,workspaceId:n.workspace_id,title:n.title,priority:t.priority??null,state:t.state??null,metadata:n.metadata,titleLocked:n.title_locked===1,updatedAt:n.updated_at}}function Ms(n){try{let t=JSON.stringify(n);return (!t||t==="null"||t.startsWith("["))&&$("event payload must be a JSON object"),t}catch(t){throw new u("VALIDATION","event payload must be JSON serializable",t)}}function ce(n,t){return n.select({maxSeq:sql`COALESCE(MAX(${S.seq}), 0)`}).from(S).where(eq(S.thread_id,t)).get()?.maxSeq??0}function le(n,t){return !!n.select({id:S.id}).from(S).where(eq(S.thread_id,t)).limit(1).get()}function Kt(n,t){Cs.has(t.type)||$(`invalid thread event type: ${String(t.type)}`);let e=Oe("the");n.insert(S).values({id:e,thread_id:t.threadId,seq:t.seq,type:t.type,actor_type:t.actorType,actor_id:t.actorId,task_id:t.taskId??null,highlight_id:t.highlightId??null,payload_json:Ms(t.payload),created_at:t.createdAt}).run();let r=n.select().from(S).where(eq(S.id,e)).get();if(!r)throw new u("DB_ERROR","Thread event insert did not return a row");return r}function ue(n,t,e,r,s){let i=Wt(t);Kt(n,{threadId:t.id,seq:s,type:"thread.snapshot.imported",actorType:e.actorType,actorId:e.actorId,createdAt:r,payload:{title:i.title,priority:i.priority,state:i.state}});}function Pe(n){return {highlightId:n.id,source:n.source,kind:n.kind,status:n.status,coversFromTaskId:n.covers_from_task_id,coversToTaskId:n.covers_to_task_id,revision:n.revision,...n.dismissed_at===null?{}:{dismissedAt:n.dismissed_at}}}function Me(n,t,e,r,s,i,a){let d=s==="thread.highlight.created"?Pe(t):{before:a?Pe({...t,...a,id:t.id}):void 0,after:Pe(t)};return Kt(n,{threadId:t.thread_id,seq:i,type:s,actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.source==="manual"?t.covers_from_task_id:t.source_task_id??t.covers_from_task_id,highlightId:t.id,payload:d})}var _e=class extends Y{dbPath;constructor(t={}){super(),t.dbPath?this.dbPath=t.dbPath:t.dbRoot&&(this.dbPath=join(t.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(t){let e=this.resolveDbPath();if(!t&&!existsSync(e))throw new u("NOT_FOUND","Database not found");if(t){let s=dirname(e);existsSync(s)||mkdirSync(s,{recursive:true});}let r=A(e);if(t)try{nt(r.db,e);}catch(s){throw r.close(),s}return r}findThread(t,e,r){let s=eq(h.id,e),i=r===void 0?s:r===null?and(s,isNull(h.workspace_id)):and(s,eq(h.workspace_id,r));return t.select().from(h).where(i).limit(1).get()}resolveWorkspaceId(t){if(M(t,"threadId"),!existsSync(this.resolveDbPath()))return null;let e=this.openHandle(false);try{return e.db.select({workspaceId:h.workspace_id}).from(h).where(eq(h.id,t)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to resolve thread workspace",r)}finally{e.close();}}getSnapshot(t,e){if(M(t,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,t,e);return s?Wt(s):null}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(t){Ds(t);let e=de(t),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,t.threadId,t.workspaceId);a||Ot(`Thread ${t.threadId} not found`);let d=Wt(a),c=t.title!==void 0,l=c&&t.title!==d.title,_=c&&a.title_locked!==1,p=t.priority!==void 0&&t.priority!==d.priority,g=t.state!==void 0&&t.state!==d.state,f=l||p||g;if(!f&&!_)return d;let x=a.metadata;(p||g)&&(x=Dn(a.metadata,{priority:t.priority,state:t.state}));let O={};if(f&&(O.metadata=x,O.updated_at=r),l&&(O.title=t.title),c&&(O.title_locked=1),i.update(h).set(O).where(t.workspaceId===void 0?eq(h.id,t.threadId):t.workspaceId===null?and(eq(h.id,t.threadId),isNull(h.workspace_id)):and(eq(h.id,t.threadId),eq(h.workspace_id,t.workspaceId))).run(),!f){let j={...a,title_locked:1};return Wt(j)}let N=ce(i,a.id)+1;le(i,a.id)||(ue(i,a,e,r,N),N+=1),l&&(Kt(i,{threadId:a.id,seq:N,type:"thread.title.changed",actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.taskId,payload:{before:d.title,after:t.title}}),N+=1),p&&(Kt(i,{threadId:a.id,seq:N,type:"thread.priority.changed",actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.taskId,payload:{before:d.priority,after:t.priority}}),N+=1),g&&Kt(i,{threadId:a.id,seq:N,type:"thread.state.changed",actorType:e.actorType,actorId:e.actorId,createdAt:r,taskId:t.taskId,payload:{before:d.state,after:t.state}});let H={...a,title:l?t.title:a.title,metadata:x,title_locked:c?1:a.title_locked,updated_at:r};return Wt(H)},{behavior:"immediate"})}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to update thread snapshot",i)}finally{s.close();}}mutateSnapshot(t){return this.updateSnapshot(t)}updateThreadSnapshot(t){return this.updateSnapshot(t)}getLatestSeq(t,e){if(M(t,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,t,e)?r.db.select({maxSeq:sql`COALESCE(MAX(${S.seq}), 0)`}).from(S).where(eq(S.thread_id,t)).get()?.maxSeq??0:null}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to read latest thread event sequence",s)}finally{r.close();}}listTimeline(t,e,r={}){let s=typeof t=="string"?{...r,threadId:t,workspaceId:e}:t;M(s.threadId,"threadId"),M(s.workspaceId,"workspaceId");let i=Ls(s);if(!existsSync(this.resolveDbPath()))return null;let a=this.openHandle(false);try{if(!this.findThread(a.db,s.threadId,s.workspaceId))return null;let d=a.db.select({maxSeq:sql`COALESCE(MAX(${S.seq}), 0)`}).from(S).where(eq(S.thread_id,s.threadId)).get()?.maxSeq??0,c;s.beforeSeq!==void 0?c=a.db.select().from(S).where(and(eq(S.thread_id,s.threadId),lt(S.seq,s.beforeSeq))).orderBy(desc(S.seq)).limit(i+1).all().reverse():s.afterSeq!==void 0?c=a.db.select().from(S).where(and(eq(S.thread_id,s.threadId),sql`${S.seq} > ${s.afterSeq}`)).orderBy(asc(S.seq)).limit(i+1).all():c=a.db.select().from(S).where(eq(S.thread_id,s.threadId)).orderBy(desc(S.seq)).limit(i+1).all().reverse();let l=c.length>i,_=s.afterSeq!==void 0?c.slice(0,i):l?c.slice(1):c,p=!1,g=_[0];return g&&(p=!!a.db.select({id:S.id}).from(S).where(and(eq(S.thread_id,s.threadId),lt(S.seq,g.seq))).limit(1).get()),{items:_,latestSeq:d,hasMoreOlder:p}}catch(d){throw d instanceof u?d:new u("DB_ERROR","Failed to list thread timeline",d)}finally{a.close();}}listEvents(t,e,r){return this.listTimeline(t,e,r)}getTimeline(t,e,r){return this.listTimeline(t,e,r)}createHighlight(t){let e=Ps(t),r=de(t),s=new Date().toISOString(),i=this.openHandle(true);try{return i.db.transaction(a=>{let d=this.findThread(a,t.threadId,t.workspaceId);if(d||Ot(`Thread ${t.threadId} not found`),e.source==="auto"){let g=a.select().from(R).where(and(eq(R.thread_id,t.threadId),eq(R.source_task_id,e.sourceTaskId),eq(R.detector_version,e.detectorVersion),eq(R.content_fingerprint,e.contentFingerprint))).orderBy(asc(R.created_at),asc(R.id)).limit(1).get();if(g)return g}let c=t.id??Oe("thl"),l={id:c,thread_id:t.threadId,source:e.source,kind:e.kind,status:"active",text:e.text,covers_from_task_id:e.coversFromTaskId,covers_to_task_id:e.coversToTaskId,revision:0,created_at:s,updated_at:s,agent_id:e.agentId,source_task_id:e.sourceTaskId,detector_version:e.detectorVersion,content_fingerprint:e.contentFingerprint,dismissed_at:null};a.insert(R).values(l).run();let _=a.select().from(R).where(eq(R.id,c)).get();if(!_)throw new u("DB_ERROR","Highlight insert did not return a row");let p=ce(a,d.id)+1;return le(a,d.id)||(ue(a,d,r,s,p),p+=1),Me(a,_,r,s,"thread.highlight.created",p),_},{behavior:"immediate"})}catch(a){throw a instanceof u?a:new u("DB_ERROR","Failed to create thread highlight",a)}finally{i.close();}}updateHighlight(t){M(t.threadId,"threadId"),M(t.workspaceId,"workspaceId"),M(t.highlightId,"highlightId"),(!Number.isInteger(t.expectedRevision)||t.expectedRevision<0)&&$("expectedRevision must be a non-negative integer"),t.text===void 0&&t.kind===void 0&&t.coversFromTaskId===void 0&&t.coversToTaskId===void 0&&$("highlight update requires at least one field"),t.kind!==void 0&&Bn(t.kind);let e=t.text===void 0?void 0:qn(t.text),r=de(t),s=new Date().toISOString(),i=this.openHandle(true);try{return i.db.transaction(a=>{let d=this.findThread(a,t.threadId,t.workspaceId);d||Ot(`Thread ${t.threadId} not found`);let c=a.select().from(R).where(and(eq(R.id,t.highlightId),eq(R.thread_id,d.id))).limit(1).get();if(c||Ot(`Highlight ${t.highlightId} not found`),c.revision!==t.expectedRevision)throw new Gt(d.id,c.id,t.expectedRevision,c.revision);if(c.status!=="active")throw new Gt(d.id,c.id,t.expectedRevision,c.revision);let l=t.kind??c.kind,_=e??c.text,p=t.coversFromTaskId??c.covers_from_task_id,g=t.coversToTaskId??c.covers_to_task_id;(!_||p.length===0||g.length===0)&&$("highlight projection is incomplete");let f=l!==c.kind||_!==c.text||p!==c.covers_from_task_id||g!==c.covers_to_task_id,x=r.actorType==="user"&&c.source==="auto"&&f?"manual":c.source;if(!(f||x!==c.source))return c;let N=c.revision+1;a.update(R).set({source:x,kind:l,text:_,covers_from_task_id:p,covers_to_task_id:g,revision:N,updated_at:s}).where(and(eq(R.id,c.id),eq(R.revision,c.revision))).run();let H=a.select().from(R).where(eq(R.id,c.id)).get();if(!H)throw new u("DB_ERROR","Highlight update did not return a row");let j=ce(a,d.id)+1;return le(a,d.id)||(ue(a,d,r,s,j),j+=1),Me(a,H,r,s,"thread.highlight.updated",j,c),H},{behavior:"immediate"})}catch(a){throw a instanceof u?a:new u("DB_ERROR","Failed to update thread highlight",a)}finally{i.close();}}dismissHighlight(t){M(t.threadId,"threadId"),M(t.workspaceId,"workspaceId"),M(t.highlightId,"highlightId"),(!Number.isInteger(t.expectedRevision)||t.expectedRevision<0)&&$("expectedRevision must be a non-negative integer");let e=de(t),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,t.threadId,t.workspaceId);a||Ot(`Thread ${t.threadId} not found`);let d=i.select().from(R).where(and(eq(R.id,t.highlightId),eq(R.thread_id,a.id))).limit(1).get();if(d||Ot(`Highlight ${t.highlightId} not found`),d.revision!==t.expectedRevision)throw new Gt(a.id,d.id,t.expectedRevision,d.revision);if(d.status==="dismissed")return d;let c=d.revision+1;i.update(R).set({status:"dismissed",text:null,revision:c,updated_at:r,dismissed_at:r}).where(and(eq(R.id,d.id),eq(R.revision,d.revision))).run();let l=i.select().from(R).where(eq(R.id,d.id)).get();if(!l)throw new u("DB_ERROR","Highlight dismissal did not return a row");let _=ce(i,a.id)+1;return le(i,a.id)||(ue(i,a,e,r,_),_+=1),Me(i,l,e,r,"thread.highlight.deleted",_,d),l},{behavior:"immediate"})}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to dismiss thread highlight",i)}finally{s.close();}}listActiveHighlights(t,e,r={}){if(M(t,"threadId"),M(e,"workspaceId"),r.taskId!==void 0&&M(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&M(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&M(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{if(!this.findThread(s.db,t,e))return null;let a=s.db.select().from(R).where(and(eq(R.thread_id,t),eq(R.status,"active"))).orderBy(asc(R.created_at),asc(R.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return a;let d=s.db.all(sql`
|
|
359
|
-
SELECT id, started_at FROM tasks WHERE thread_id = ${
|
|
357
|
+
WHERE id = ${e}
|
|
358
|
+
`),l},{behavior:"immediate"})}}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to save user message",i)}finally{s.close();}}saveAssistantMessage(e,t,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.update(_).set({last_message:t,updated_at:i}).where(eq(_.id,e)).run();}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to save assistant message",i)}finally{s.close();}}updateThread(e,t){if(!this.dbExists())return;let r=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};t.title!==void 0&&(s.title=t.title,s.title_locked=1),t.titleLocked!==void 0&&(s.title_locked=t.titleLocked?1:0),r.db.update(_).set(s).where(eq(_.id,e)).run();}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to update thread",s)}finally{r.close();}}patchThreadTitleMetadata(e,t,r){let s=t;if(!s||typeof s!="object"||Array.isArray(s))return new Be("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(c=>c!=="priority"&&c!=="state"))return new Be("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let a=s;if(a.priority===void 0&&a.state===void 0)return new Be("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let c of [a.priority,a.state])if(c!=null&&(typeof c!="string"||c.length===0))return new Be("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let c=r?and(eq(_.id,e),eq(_.workspace_id,r)):eq(_.id,e);return d.db.transaction(l=>{let h=l.select({metadata:_.metadata}).from(_).where(c).get();if(!h)return null;let p=Ye(h.metadata),g=p.threadTitle,f=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};a.priority===null?delete f.priority:a.priority!==void 0&&(f.priority=a.priority),a.state===null?delete f.state:a.state!==void 0&&(f.state=a.state),Object.keys(f).length>0?p.threadTitle=f:delete p.threadTitle;let L=Object.keys(p).length>0?JSON.stringify(p):null,N=new Date().toISOString();l.update(_).set({metadata:L,updated_at:N}).where(c).run();let v=l.select({metadata:_.metadata}).from(_).where(c).get();if(!v)throw new u("DB_ERROR","Thread-title metadata update could not be read back");let q=Cs(v.metadata);return {threadId:e,priority:q.priority,state:q.state}},{behavior:"immediate"})}catch(c){throw c instanceof u?c:new u("DB_ERROR","Failed to patch thread-title metadata",c)}finally{d.close();}}togglePin(e,t){let r=this.openHandle(true);try{let s=t?and(eq(_.id,e),eq(_.workspace_id,t)):eq(_.id,e);return r.db.transaction(i=>{let a=i.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(s).get();if(!a)return null;let d=a.pinned?0:1,c=Ye(a.metadata);if(d){let l=t?and(eq(_.pinned,1),eq(_.workspace_id,t)):eq(_.pinned,1),h=i.select({metadata:_.metadata}).from(_).where(l).all(),p=null;for(let g of h){let f=Ye(g.metadata);typeof f.pinOrder=="number"&&(p===null||f.pinOrder<p)&&(p=f.pinOrder);}c.pinOrder=p===null?0:p-1;}else delete c.pinOrder;return i.update(_).set({pinned:d,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(s).run(),{pinned:!!d}},{behavior:"immediate"})}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to toggle pin",s)}finally{r.close();}}reorderPins(e,t){let r=this.openHandle(true);try{r.db.transaction(s=>{for(let i=0;i<e.length;i++){let a=t?and(eq(_.id,e[i]),eq(_.workspace_id,t)):eq(_.id,e[i]),d=s.select({metadata:_.metadata}).from(_).where(a).get();if(!d)continue;let c=Ye(d.metadata);c.pinOrder=i+1,s.update(_).set({metadata:JSON.stringify(c)}).where(a).run();}},{behavior:"immediate"});}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to reorder pins",s)}finally{r.close();}}toggleStar(e,t){let r=this.openHandle(true);try{let s=t?and(eq(_.id,e),eq(_.workspace_id,t)):eq(_.id,e),i=r.db.select({starred:_.starred}).from(_).where(s).get();if(!i)return null;let a=i.starred?0:1;return r.db.update(_).set({starred:a}).where(s).run(),{starred:!!a}}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to toggle star",s)}finally{r.close();}}resolveOverdriveForRequest(e,t,r,s){let a=this.openHandle(true);try{let d=t?and(eq(_.id,e),eq(_.workspace_id,t)):eq(_.id,e);return a.db.transaction(l=>{let h=l.select({metadata:_.metadata}).from(_).where(d).get();if(!h)return null;let p=h.metadata?JSON.parse(h.metadata):{},g=p.overdrive??{},f=s?.defaultTurns??g.defaultTurns??3,L=s?.updatedBy??"ui",N=new Date().toISOString(),v,q,U,Pe;switch(r){case "enable-count":{let ge=s?.turns??f,ve=s?.consumeCurrent?Math.max(ge-1,0):ge;v=ve>0?"count":"off",q=ve,U=!0,Pe="count";break}case "enable-latch":{v="latch",q=0,U=!0,Pe="latch";break}case "disable":{v="off",q=0,U=!1;break}default:{let ge=g.state??"off",ve=typeof g.remaining=="number"?g.remaining:0;if(ge==="count"&&ve>0){let C=ve-1;C<=0?(v="off",q=0):(v="count",q=C),U=!0,Pe="count";}else ge==="latch"?(v="latch",q=0,U=!0,Pe="latch"):(v="off",q=0,U=!1);break}}return p.overdrive={state:v,remaining:q,defaultTurns:f,updatedAt:N,updatedBy:L},l.update(_).set({metadata:JSON.stringify(p),updated_at:N}).where(d).run(),{applied:U,appliedMode:Pe,state:v,remaining:q}},{behavior:"immediate"})}catch(d){throw d instanceof u?d:new u("DB_ERROR","Failed to resolve overdrive",d)}finally{a.close();}}};var jt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Os(n){let e=randomBytes(n*2),t="";for(let r=0;r<e.length&&t.length<n;r++){let s=e[r];s<248&&(t+=jt[s%62]);}for(;t.length<n;)t+=jt[randomBytes(1)[0]%62];return t}function Je(n){return `${n}_${Os(8)}`}function Ur(n,e){let{createHash:t}=Ge("crypto"),r=t("sha256").update(e).digest(),s=Buffer.alloc(8);for(let a=0;a<32;a++)s[a%8]^=r[a];let i="";for(let a of s)i+=jt[a%62];return `${n}_${i}`}var bs=["urgent","high","medium","low"],xs=["investigating","in-progress","in-review","on-hold","done"],jr="custom:";var Ds=new Set(bs),Ls=new Set(xs);function Gt(n){return typeof n=="string"&&Ds.has(n)}function zt(n){if(typeof n!="string")return false;if(Ls.has(n))return true;if(n.startsWith("c_"))return n.length>2;if(!n.startsWith(jr))return false;let e=n.slice(jr.length);return e.length>=1&&e.length<=20}function Gr(n){if(!n)return null;try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function Wt(n){let e=Gr(n);if(!e)return {};let t=e.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return {};let r=t,s={};return Gt(r.priority)&&(s.priority=r.priority),zt(r.state)&&(s.state=r.state),s}function zr(n,e){let t=Gr(n)??{},r={...Wt(n)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete t.threadTitle:t.threadTitle=r,Object.keys(t).length===0?null:JSON.stringify(t)}var qs="regeneration_replaced";var Bs="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Fs="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Xt=class extends u{threadId;highlightId;expectedRevision;currentRevision;constructor(e,t,r,s){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${s}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=t,this.expectedRevision=r,this.currentRevision=s;}},st=class extends Xt{},Yt=class extends u{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Us=new Set(Rr),js=new Set(Er),Gs=new Set(Ir),zs=new Set(Sr),Ws=50,Kr=100,Vr=280,Xr=40,Ks=new Set(vr),kt=["queued","running"],Vs=["success","completed","done","failed","error"];function Vt(n){return Ks.has(n)}function x(n){throw new u("VALIDATION",n)}function ae(n){throw new u("NOT_FOUND",n)}function k(n,e){(typeof n!="string"||n.trim().length===0)&&x(`${e} is required`);}function Ze(n={}){let e=n.actor??n,t=e.actorType??"system";return Us.has(t)||x(`invalid actorType: ${String(t)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&x("actorId must be a string or null"),{actorType:t,actorId:e.actorId??null}}function Xs(n){k(n.threadId,"threadId"),n.workspaceId!==void 0&&n.workspaceId!==null&&k(n.workspaceId,"workspaceId"),n.title!==void 0&&n.title!==null&&((typeof n.title!="string"||n.title.trim().length===0)&&x("title must not be empty"),n.title.length>120&&x("title must be at most 120 characters")),n.priority!==void 0&&n.priority!==null&&!Gt(n.priority)&&x(`invalid priority: ${String(n.priority)}`),n.state!==void 0&&n.state!==null&&!zt(n.state)&&x(`invalid state: ${String(n.state)}`);}function Ys(n){n.beforeSeq!==void 0&&n.afterSeq!==void 0&&x("beforeSeq and afterSeq cannot be used together");for(let[t,r]of [["beforeSeq",n.beforeSeq],["afterSeq",n.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&x(`${t} must be a non-negative integer`);let e=n.limit??Ws;return (!Number.isInteger(e)||e<1||e>Kr)&&x(`limit must be between 1 and ${Kr}`),e}function Jt(n){typeof n!="string"&&x("text is required");let e=n.trim();return e.length===0&&x("text must not be empty"),e.length>Vr&&x(`text must be at most ${Vr} characters`),e}function Se(n,e){return k(n??"",e),n}function Qt(n){zs.has(n)||x(`invalid highlight kind: ${String(n)}`);}function Js(n){Gs.has(n)||x(`invalid highlight source: ${String(n)}`);}function Qs(n){k(n.threadId,"threadId"),k(n.workspaceId,"workspaceId");let e=n.source??"manual";Js(e),Qt(n.kind);let t=Jt(n.text),r=n.coversFromTaskId??n.fromTaskId??n.taskId,s=n.coversToTaskId??n.toTaskId??n.taskId;if(e==="manual"){let h=n.taskId??(r&&s&&r===s?r:void 0),p=Se(h,"taskId");return (r!==p||s!==p)&&x("manual highlights must cover exactly one task"),{source:e,kind:n.kind,text:t,coversFromTaskId:p,coversToTaskId:p,agentId:n.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let i=Se(r,"coversFromTaskId"),a=Se(s,"coversToTaskId"),d=n.sourceTaskId??i,c=n.detectorVersion??(n.idempotencyKey!==void 0?"default":null),l=n.contentFingerprint??n.idempotencyKey??null;return Se(d??void 0,"sourceTaskId"),Se(c??void 0,"detectorVersion"),Se(l??void 0,"contentFingerprint"),{source:e,kind:n.kind,text:t,coversFromTaskId:i,coversToTaskId:a,agentId:n.agentId??null,sourceTaskId:d,detectorVersion:c,contentFingerprint:l}}function Zs(n,e){(!n||typeof n!="object")&&x(`candidates[${e}] is required`),Qt(n.kind);let t=Jt(n.text),r=Se(n.anchorTaskId,`candidates[${e}].anchorTaskId`),s=Se(n.coversFromTaskId,`candidates[${e}].coversFromTaskId`),i=Se(n.coversToTaskId,`candidates[${e}].coversToTaskId`),a=n.contentFingerprint?.trim()||Ur("thl",JSON.stringify({kind:n.kind,text:t,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:i}));return k(a,`candidates[${e}].contentFingerprint`),{kind:n.kind,text:t,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:i,contentFingerprint:a}}function eo(n){Array.isArray(n)||x("candidates must be an array"),n.length>Xr&&x(`candidates must contain at most ${Xr} items`);let e=new Map;for(let[t,r]of n.entries()){let s=Zs(r,t);e.set(s.contentFingerprint,s);}return [...e.values()]}function nt(n){let e=Wt(n.metadata);return {threadId:n.id,workspaceId:n.workspace_id,title:n.title,priority:e.priority??null,state:e.state??null,metadata:n.metadata,titleLocked:n.title_locked===1,updatedAt:n.updated_at}}function to(n){try{let e=JSON.stringify(n);return (!e||e==="null"||e.startsWith("["))&&x("event payload must be a JSON object"),e}catch(e){throw new u("VALIDATION","event payload must be JSON serializable",e)}}function et(n,e){return n.select({maxSeq:sql`COALESCE(MAX(${O.seq}), 0)`}).from(O).where(eq(O.thread_id,e)).get()?.maxSeq??0}function tt(n,e){return !!n.select({id:O.id}).from(O).where(eq(O.thread_id,e)).limit(1).get()}function He(n,e){js.has(e.type)||x(`invalid thread event type: ${String(e.type)}`);let t=Je("the");n.insert(O).values({id:t,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:to(e.payload),created_at:e.createdAt}).run();let r=n.select().from(O).where(eq(O.id,t)).get();if(!r)throw new u("DB_ERROR","Thread event insert did not return a row");return r}function rt(n,e,t,r,s){let i=nt(e);He(n,{threadId:e.id,seq:s,type:"thread.snapshot.imported",actorType:t.actorType,actorId:t.actorId,createdAt:r,payload:{title:i.title,priority:i.priority,state:i.state}});}function yt(n){return {highlightId:n.id,source:n.source,kind:n.kind,status:n.status,coversFromTaskId:n.covers_from_task_id,coversToTaskId:n.covers_to_task_id,revision:n.revision,...n.dismissed_at===null?{}:{dismissedAt:n.dismissed_at}}}function wt(n,e,t,r,s,i,a){let d=s==="thread.highlight.created"?yt(e):{before:a?yt({...e,...a,id:e.id}):void 0,after:yt(e)};return He(n,{threadId:e.thread_id,seq:i,type:s,actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:d})}function ro(n,e,t,r,s,i){return He(n,{threadId:e.thread_id,seq:s,type:"thread.highlight.deleted",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:yt(e),...i??{}}})}var Et=class extends Z{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new u("NOT_FOUND","Database not found");if(e){let s=dirname(t);existsSync(s)||mkdirSync(s,{recursive:true});}let r=$(t);if(e)try{de(r.db,t);}catch(s){throw r.close(),s}return r}findThread(e,t,r){let s=eq(_.id,t),i=r===void 0?s:r===null?and(s,isNull(_.workspace_id)):and(s,eq(_.workspace_id,r));return e.select().from(_).where(i).limit(1).get()}findRegenerationRun(e,t,r){let s=e.select().from(S).where(eq(S.id,t)).limit(1).get();if(s&&!(r!==void 0&&!this.findThread(e,s.thread_id,r)))return s}resolveWorkspaceId(e){if(k(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let t=this.openHandle(false);try{return t.db.select({workspaceId:_.workspace_id}).from(_).where(eq(_.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof u?r:new u("DB_ERROR","Failed to resolve thread workspace",r)}finally{t.close();}}getSnapshot(e,t){if(k(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,t);return s?nt(s):null}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){Xs(e);let t=Ze(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,e.threadId,e.workspaceId);a||ae(`Thread ${e.threadId} not found`);let d=nt(a),c=e.title!==void 0,l=c&&e.title!==d.title,h=c&&a.title_locked!==1,p=e.priority!==void 0&&e.priority!==d.priority,g=e.state!==void 0&&e.state!==d.state,f=l||p||g;if(!f&&!h)return d;let L=a.metadata;(p||g)&&(L=zr(a.metadata,{priority:e.priority,state:e.state}));let N={};if(f&&(N.metadata=L,N.updated_at=r),l&&(N.title=e.title),c&&(N.title_locked=1),i.update(_).set(N).where(e.workspaceId===void 0?eq(_.id,e.threadId):e.workspaceId===null?and(eq(_.id,e.threadId),isNull(_.workspace_id)):and(eq(_.id,e.threadId),eq(_.workspace_id,e.workspaceId))).run(),!f){let U={...a,title_locked:1};return nt(U)}let v=et(i,a.id)+1;tt(i,a.id)||(rt(i,a,t,r,v),v+=1),l&&(He(i,{threadId:a.id,seq:v,type:"thread.title.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),v+=1),p&&(He(i,{threadId:a.id,seq:v,type:"thread.priority.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),v+=1),g&&He(i,{threadId:a.id,seq:v,type:"thread.state.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let q={...a,title:l?e.title:a.title,metadata:L,title_locked:c?1:a.title_locked,updated_at:r};return nt(q)},{behavior:"immediate"})}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to update thread snapshot",i)}finally{s.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,t){if(k(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,t)?r.db.select({maxSeq:sql`COALESCE(MAX(${O.seq}), 0)`}).from(O).where(eq(O.thread_id,e)).get()?.maxSeq??0:null}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to read latest thread event sequence",s)}finally{r.close();}}listCompletedThreadHighlightTurns(e,t){if(k(e,"threadId"),k(t,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,t)?r.db.select({taskId:o.id,prompt:o.prompt,result:o.result,status:o.status,startedAt:o.started_at,completedAt:o.completed_at}).from(o).where(and(eq(o.thread_id,e),eq(o.workspace_id,t),inArray(o.status,Vs),or(isNull(o.parent_task_id),eq(o.parent_task_id,"")),sql`${o.result} IS NOT NULL AND length(trim(${o.result})) > 0`)).orderBy(asc(o.started_at),asc(o.id)).all().map(a=>({taskId:a.taskId,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.startedAt,completedAt:a.completedAt})):null}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to read completed thread highlight turns",s)}finally{r.close();}}createHighlightRegenerationRun(e){k(e.threadId,"threadId"),k(e.workspaceId,"workspaceId"),k(e.requestId,"requestId"),k(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&k(e.runId,"runId");let t=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||ae(`Thread ${e.threadId} not found`);let a=s.select().from(S).where(and(eq(S.thread_id,i.id),eq(S.request_id,e.requestId))).orderBy(desc(S.requested_at),desc(S.id)).limit(1).get();if(a)return {run:a,created:!1};let d=s.select().from(S).where(and(eq(S.thread_id,i.id),inArray(S.status,kt))).orderBy(asc(S.requested_at),asc(S.id)).limit(1).get();if(d)throw new Yt(d);let c=e.runId??Je("thr");s.insert(S).values({id:c,thread_id:i.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:t,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let l=s.select().from(S).where(eq(S.id,c)).get();if(!l)throw new u("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:l,created:!0}},{behavior:"immediate"})}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to create highlight regeneration run",s)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,t){if(k(e,"runId"),t!==void 0&&k(t,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,t)??null}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to read highlight regeneration run",s)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,t,r){if(k(e,"threadId"),k(t,"workspaceId"),k(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{return this.findThread(s.db,e,t)?s.db.select().from(S).where(and(eq(S.thread_id,e),eq(S.request_id,r))).orderBy(desc(S.requested_at),desc(S.id)).limit(1).get()??null:null}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to read highlight regeneration request",i)}finally{s.close();}}findHighlightRegenerationRun(e,t,r){return this.getHighlightRegenerationRunByRequest(e,t,r)}startHighlightRegenerationRun(e,t){k(e,"runId"),t!==void 0&&k(t,"workspaceId");let r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findRegenerationRun(i,e,t);if(a||ae(`Highlight regeneration run ${e} not found`),Vt(a.status)||x(`invalid highlight regeneration status: ${a.status}`),a.status!=="queued")return a;i.update(S).set({status:"running",started_at:r}).where(and(eq(S.id,a.id),eq(S.status,"queued"))).run();let d=i.select().from(S).where(eq(S.id,a.id)).get();if(!d)throw new u("DB_ERROR","Highlight regeneration run start did not return a row");return d},{behavior:"immediate"})}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to start highlight regeneration run",i)}finally{s.close();}}startHighlightRegeneration(e,t){return this.startHighlightRegenerationRun(e,t)}failHighlightRegenerationRun(e){k(e.runId,"runId"),k(e.errorCode,"errorCode"),e.workspaceId!==void 0&&k(e.workspaceId,"workspaceId");let t=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let i=this.findRegenerationRun(s,e.runId,e.workspaceId);if(i||ae(`Highlight regeneration run ${e.runId} not found`),Vt(i.status)||x(`invalid highlight regeneration status: ${i.status}`),i.status==="completed"||i.status==="failed")return i;s.update(S).set({status:"failed",completed_at:t,error_code:e.errorCode}).where(and(eq(S.id,i.id),inArray(S.status,kt))).run();let a=s.select().from(S).where(eq(S.id,i.id)).get();if(!a)throw new u("DB_ERROR","Highlight regeneration run failure did not return a row");return a},{behavior:"immediate"})}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to fail highlight regeneration run",s)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=Bs){k(e,"errorCode");let t=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update(S).set({status:"failed",completed_at:t,error_code:e}).where(inArray(S.status,kt)).run().changes,{behavior:"immediate"})}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to recover interrupted highlight runs",s)}finally{r.close();}}completeHighlightRegenerationRun(e){k(e.runId,"runId"),k(e.threadId,"threadId"),k(e.workspaceId,"workspaceId"),k(e.detectorVersion,"detectorVersion");let t=eo(e.candidates),r=Ze(e),s=this.openHandle(true),i=false;try{return s.db.transaction(a=>{let d=this.findRegenerationRun(a,e.runId,e.workspaceId);if((!d||d.thread_id!==e.threadId)&&ae(`Highlight regeneration run ${e.runId} not found`),Vt(d.status)||x(`invalid highlight regeneration status: ${d.status}`),d.status==="failed")throw new u("CONFLICT","Highlight regeneration run has already failed");if(d.status==="completed")return {run:d,deletedCount:0,createdCount:0,previousAutoCount:d.previous_auto_count??0,newAutoCount:d.new_auto_count??0};i=!0;let c=this.findThread(a,e.threadId,e.workspaceId);c||ae(`Thread ${e.threadId} not found`),d.detector_version!==e.detectorVersion&&x("detectorVersion does not match the regeneration run");let l=a.select().from(w).where(eq(w.thread_id,c.id)).orderBy(asc(w.created_at),asc(w.id)).all(),h=new Set(t.map(C=>C.contentFingerprint)),p=l.filter(C=>C.source==="auto"&&C.status==="active"&&C.revision===0&&!h.has(C.content_fingerprint??"")),g=l.filter(C=>C.source==="auto"&&C.status==="active").length,f=new Set(l.filter(C=>!p.includes(C)&&C.content_fingerprint).map(C=>C.content_fingerprint)),L=t.filter(C=>!f.has(C.contentFingerprint)),N=new Date().toISOString(),v=et(a,c.id)+1;tt(a,c.id)||(rt(a,c,r,N,v),v+=1);for(let C of p)a.delete(w).where(eq(w.id,C.id)).run(),ro(a,C,r,N,v,{runId:e.runId,reason:qs}),v+=1;let q=0,U=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let C of L){let tr=Je("thl");a.insert(w).values({id:tr,thread_id:c.id,source:"auto",kind:C.kind,status:"active",text:C.text,covers_from_task_id:C.coversFromTaskId,covers_to_task_id:C.coversToTaskId,revision:0,created_at:N,updated_at:N,agent_id:U,source_task_id:C.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:C.contentFingerprint,dismissed_at:null}).run();let rr=a.select().from(w).where(eq(w.id,tr)).get();if(!rr)throw new u("DB_ERROR","Regenerated highlight insert did not return a row");wt(a,rr,r,N,"thread.highlight.created",v),v+=1,q+=1;}let ge=a.select().from(w).where(eq(w.thread_id,c.id)).all().filter(C=>C.source==="auto"&&C.status==="active").length;He(a,{threadId:c.id,seq:v,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:N,payload:{runId:d.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:ge,deletedCount:p.length,createdCount:q}}),a.update(S).set({status:"completed",started_at:d.started_at??N,completed_at:N,error_code:null,previous_auto_count:g,new_auto_count:ge}).where(and(eq(S.id,d.id),inArray(S.status,kt))).run();let ve=a.select().from(S).where(eq(S.id,d.id)).get();if(!ve)throw new u("DB_ERROR","Highlight regeneration completion did not return a row");return {run:ve,deletedCount:p.length,createdCount:q,previousAutoCount:g,newAutoCount:ge}},{behavior:"immediate"})}catch(a){if(i)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Fs});}catch{}throw a instanceof u?a:new u("DB_ERROR","Failed to complete highlight regeneration",a)}finally{s.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,t,r={}){let s=typeof e=="string"?{...r,threadId:e,workspaceId:t}:e;k(s.threadId,"threadId"),k(s.workspaceId,"workspaceId");let i=Ys(s);if(!existsSync(this.resolveDbPath()))return null;let a=this.openHandle(false);try{if(!this.findThread(a.db,s.threadId,s.workspaceId))return null;let d=a.db.select({maxSeq:sql`COALESCE(MAX(${O.seq}), 0)`}).from(O).where(eq(O.thread_id,s.threadId)).get()?.maxSeq??0,c;s.beforeSeq!==void 0?c=a.db.select().from(O).where(and(eq(O.thread_id,s.threadId),lt(O.seq,s.beforeSeq))).orderBy(desc(O.seq)).limit(i+1).all().reverse():s.afterSeq!==void 0?c=a.db.select().from(O).where(and(eq(O.thread_id,s.threadId),sql`${O.seq} > ${s.afterSeq}`)).orderBy(asc(O.seq)).limit(i+1).all():c=a.db.select().from(O).where(eq(O.thread_id,s.threadId)).orderBy(desc(O.seq)).limit(i+1).all().reverse();let l=c.length>i,h=s.afterSeq!==void 0?c.slice(0,i):l?c.slice(1):c,p=!1,g=h[0];return g&&(p=!!a.db.select({id:O.id}).from(O).where(and(eq(O.thread_id,s.threadId),lt(O.seq,g.seq))).limit(1).get()),{items:h,latestSeq:d,hasMoreOlder:p}}catch(d){throw d instanceof u?d:new u("DB_ERROR","Failed to list thread timeline",d)}finally{a.close();}}listEvents(e,t,r){return this.listTimeline(e,t,r)}getTimeline(e,t,r){return this.listTimeline(e,t,r)}createHighlight(e){let t=Qs(e),r=Ze(e),s=new Date().toISOString(),i=this.openHandle(true);try{return i.db.transaction(a=>{let d=this.findThread(a,e.threadId,e.workspaceId);if(d||ae(`Thread ${e.threadId} not found`),t.source==="auto"){let g=a.select().from(w).where(and(eq(w.thread_id,e.threadId),eq(w.source_task_id,t.sourceTaskId),eq(w.detector_version,t.detectorVersion),eq(w.content_fingerprint,t.contentFingerprint))).orderBy(asc(w.created_at),asc(w.id)).limit(1).get();if(g)return g}let c=e.id??Je("thl"),l={id:c,thread_id:e.threadId,source:t.source,kind:t.kind,status:"active",text:t.text,covers_from_task_id:t.coversFromTaskId,covers_to_task_id:t.coversToTaskId,revision:0,created_at:s,updated_at:s,agent_id:t.agentId,source_task_id:t.sourceTaskId,detector_version:t.detectorVersion,content_fingerprint:t.contentFingerprint,dismissed_at:null};a.insert(w).values(l).run();let h=a.select().from(w).where(eq(w.id,c)).get();if(!h)throw new u("DB_ERROR","Highlight insert did not return a row");let p=et(a,d.id)+1;return tt(a,d.id)||(rt(a,d,r,s,p),p+=1),wt(a,h,r,s,"thread.highlight.created",p),h},{behavior:"immediate"})}catch(a){throw a instanceof u?a:new u("DB_ERROR","Failed to create thread highlight",a)}finally{i.close();}}updateHighlight(e){k(e.threadId,"threadId"),k(e.workspaceId,"workspaceId"),k(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&x("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&x("highlight update requires at least one field"),e.kind!==void 0&&Qt(e.kind);let t=e.text===void 0?void 0:Jt(e.text),r=Ze(e),s=new Date().toISOString(),i=this.openHandle(true);try{return i.db.transaction(a=>{let d=this.findThread(a,e.threadId,e.workspaceId);d||ae(`Thread ${e.threadId} not found`);let c=a.select().from(w).where(and(eq(w.id,e.highlightId),eq(w.thread_id,d.id))).limit(1).get();if(c||ae(`Highlight ${e.highlightId} not found`),c.revision!==e.expectedRevision)throw new st(d.id,c.id,e.expectedRevision,c.revision);if(c.status!=="active")throw new st(d.id,c.id,e.expectedRevision,c.revision);let l=e.kind??c.kind,h=t??c.text,p=e.coversFromTaskId??c.covers_from_task_id,g=e.coversToTaskId??c.covers_to_task_id;(!h||p.length===0||g.length===0)&&x("highlight projection is incomplete");let f=l!==c.kind||h!==c.text||p!==c.covers_from_task_id||g!==c.covers_to_task_id,L=r.actorType==="user"&&c.source==="auto"&&f?"manual":c.source;if(!(f||L!==c.source))return c;let v=c.revision+1;a.update(w).set({source:L,kind:l,text:h,covers_from_task_id:p,covers_to_task_id:g,revision:v,updated_at:s}).where(and(eq(w.id,c.id),eq(w.revision,c.revision))).run();let q=a.select().from(w).where(eq(w.id,c.id)).get();if(!q)throw new u("DB_ERROR","Highlight update did not return a row");let U=et(a,d.id)+1;return tt(a,d.id)||(rt(a,d,r,s,U),U+=1),wt(a,q,r,s,"thread.highlight.updated",U,c),q},{behavior:"immediate"})}catch(a){throw a instanceof u?a:new u("DB_ERROR","Failed to update thread highlight",a)}finally{i.close();}}dismissHighlight(e){k(e.threadId,"threadId"),k(e.workspaceId,"workspaceId"),k(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&x("expectedRevision must be a non-negative integer");let t=Ze(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,e.threadId,e.workspaceId);a||ae(`Thread ${e.threadId} not found`);let d=i.select().from(w).where(and(eq(w.id,e.highlightId),eq(w.thread_id,a.id))).limit(1).get();if(d||ae(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new st(a.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let c=d.revision+1;i.update(w).set({status:"dismissed",text:null,revision:c,updated_at:r,dismissed_at:r}).where(and(eq(w.id,d.id),eq(w.revision,d.revision))).run();let l=i.select().from(w).where(eq(w.id,d.id)).get();if(!l)throw new u("DB_ERROR","Highlight dismissal did not return a row");let h=et(i,a.id)+1;return tt(i,a.id)||(rt(i,a,t,r,h),h+=1),wt(i,l,t,r,"thread.highlight.deleted",h,d),l},{behavior:"immediate"})}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to dismiss thread highlight",i)}finally{s.close();}}listActiveHighlights(e,t,r={}){if(k(e,"threadId"),k(t,"workspaceId"),r.taskId!==void 0&&k(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&k(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&k(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{if(!this.findThread(s.db,e,t))return null;let a=s.db.select().from(w).where(and(eq(w.thread_id,e),eq(w.status,"active"))).orderBy(asc(w.created_at),asc(w.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return a;let d=s.db.all(sql`
|
|
359
|
+
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
360
360
|
ORDER BY started_at ASC, id ASC
|
|
361
|
-
`),c=new Map(d.map((g,f)=>[g.id,f])),l=r.taskId===void 0?void 0:c.get(r.taskId),
|
|
361
|
+
`),c=new Map(d.map((g,f)=>[g.id,f])),l=r.taskId===void 0?void 0:c.get(r.taskId),h=r.coversFromTaskId===void 0?void 0:c.get(r.coversFromTaskId),p=r.coversToTaskId===void 0?void 0:c.get(r.coversToTaskId);return a.filter(g=>{let f=c.get(g.covers_from_task_id),L=c.get(g.covers_to_task_id);if(f===void 0||L===void 0)return !1;let N=Math.min(f,L),v=Math.max(f,L);return !(l!==void 0&&(l<N||l>v)||h!==void 0&&v<h||p!==void 0&&N>p)})}catch(i){throw i instanceof u?i:new u("DB_ERROR","Failed to list active thread highlights",i)}finally{s.close();}}listHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}getActiveHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}};var j=class extends u{reason;constructor(e,t="VALIDATION",r=e,s){super(t,r,s),this.name="CommonCodeRepositoryError",this.reason=e;}},Jr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ho(){let n=randomBytes(16),e="";for(let t of n)e+=Jr[t%Jr.length];return e.slice(0,12)}function Qr(){return `c_${ho()}`}function _o(n){return typeof n=="string"&&Ht.includes(n)}function po(n){return typeof n=="string"&&Pt.includes(n)}function ot(n){if(!_o(n))throw new j("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${n}`)}function Zr(n){if(!po(n))throw new j("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${n}`)}function en(n){let e=typeof n=="string"?n.trim():"",t=[...e].length;if(t<1||t>20)throw new j("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function it(n){if(typeof n!="string"||n.trim().length===0)throw new j("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Zt(n){if(typeof n!="string"||n.trim().length===0)throw new j("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function je(n,e){return and(eq(m.code_group,n),or(isNull(m.workspace_id),eq(m.workspace_id,e)))}var It=class extends Z{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new u("NOT_FOUND","Database not found");e&&mkdirSync(dirname(t),{recursive:true});let r=$(t);if(e)try{de(r.db,t);}catch(s){throw r.close(),s}return r}listSelectable(e,t){if(ot(e),it(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(and(je(e,t),eq(m.is_archived,0))).orderBy(asc(m.sort_order),asc(m.code)).all()}catch(s){throw new u("DB_ERROR","Failed to list selectable common codes",s)}finally{r.close();}}listForHistory(e,t){if(ot(e),it(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(je(e,t)).orderBy(asc(m.sort_order),asc(m.code)).all()}catch(s){throw new u("DB_ERROR","Failed to list common-code history",s)}finally{r.close();}}resolve(e,t){if(ot(e),Zt(t),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(m).where(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get()??null}catch(s){throw new u("DB_ERROR","Failed to resolve common code",s)}finally{r.close();}}createThreadState(e){it(e.workspaceId);let t=en(e.name);Zr(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{if(s.select({code:m.code}).from(m).where(and(je("THREAD_STATE",e.workspaceId),eq(m.is_archived,0),eq(m.code_name,t))).limit(1).get())throw new j("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${t}`);let a=s.select({maxSortOrder:sql`max(${m.sort_order})`}).from(m).where(je("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),c=Qr();for(;s.select({code:m.code}).from(m).where(and(eq(m.code_group,"THREAD_STATE"),eq(m.code,c))).limit(1).get();)c=Qr();s.insert(m).values({code_group:"THREAD_STATE",code:c,code_name:t,color:e.color,sort_order:(a?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:d,updated_at:d}).run();let l=s.select().from(m).where(and(eq(m.code_group,"THREAD_STATE"),eq(m.code,c))).limit(1).get();if(!l)throw new u("DB_ERROR","Created common code could not be read back");return l},{behavior:"immediate"})}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to create thread state common code",s)}finally{r.close();}}updateDisplay(e){if(ot(e.group),Zt(e.code),it(e.workspaceId),e.name===void 0&&e.color===void 0)throw new j("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let t=e.name===void 0||e.name===null?e.name:en(e.name);e.color!==void 0&&Zr(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{let i=s.select().from(m).where(and(eq(m.code_group,e.group),eq(m.code,e.code))).limit(1).get();if(!i)throw new j("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(i,e.workspaceId),t===null&&i.is_builtin!==1)throw new j("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof t=="string"&&i.is_archived===0){let c=and(je(e.group,e.workspaceId),eq(m.is_archived,0));if(s.select({code:m.code}).from(m).where(and(c,eq(m.code_name,t),sql`${m.code} <> ${e.code}`)).limit(1).get())throw new j("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${t}`)}let a={updated_at:new Date().toISOString()};e.name!==void 0&&(a.code_name=t??null),e.color!==void 0&&(a.color=e.color),s.update(m).set(a).where(and(eq(m.code_group,e.group),eq(m.code,e.code))).run();let d=s.select().from(m).where(and(eq(m.code_group,e.group),eq(m.code,e.code))).limit(1).get();if(!d)throw new u("DB_ERROR","Updated common code could not be read back");return d},{behavior:"immediate"})}catch(s){throw s instanceof u?s:new u("DB_ERROR","Failed to update common-code display values",s)}finally{r.close();}}archive(e,t,r,s=true){if(ot(e),Zt(t),it(r),typeof s!="boolean")throw new j("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let i=this.openHandle(true);try{return i.db.transaction(a=>{let d=a.select().from(m).where(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get();if(!d)throw new j("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${t}`);if(d.is_builtin===1)throw new j("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(d,r),!s&&d.code_name!==null&&a.select({code:m.code}).from(m).where(and(je(e,r),eq(m.is_archived,0),eq(m.code_name,d.code_name),ne(m.code,t))).limit(1).get())throw new j("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${d.code_name}`);a.update(m).set({is_archived:s?1:0,updated_at:new Date().toISOString()}).where(and(eq(m.code_group,e),eq(m.code,t))).run();let c=a.select().from(m).where(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get();if(!c)throw new u("DB_ERROR","Archived common code could not be read back");return c},{behavior:"immediate"})}catch(a){throw a instanceof u?a:new u("DB_ERROR","Failed to archive common code",a)}finally{i.close();}}assertOwnership(e,t){if(e.workspace_id!==null&&e.workspace_id!==t)throw new j("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function mo(n){return n.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
362
362
|
`).filter(s=>!(s.startsWith("Loaded ")&&s.includes("layouts from")||s.includes("[dotenv@")||s.includes("[Nest]")&&s.includes("DEBUG")||s.startsWith("Registered custom layout:")||s.startsWith("Updated custom layout:"))).join(`
|
|
363
|
-
`).trim()}function
|
|
364
|
-
`):
|
|
365
|
-
`)[0].slice(0,200)),
|
|
363
|
+
`).trim()}function To(n){if(!n)return "";let e=n;try{let t=JSON.parse(e);Array.isArray(t)?e=t.filter(r=>r?.type==="text"&&r?.text).map(r=>r.text).join(`
|
|
364
|
+
`):t&&typeof t=="object"&&t.result!==void 0&&(e=t.result||"");}catch{e=mo(e);}return e}var St=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Tt({dbPath:this.dbPath})}getThreadHistoryRepo(){return new Et({dbPath:this.dbPath})}updateThread(e,t){this.getThreadRepo().updateThread(e,{title:t.title});}async ensureThread(e,t,r){let s=this.getThreadRepo(),i=s.findThreadById(e);if(i){if(i.platform!==t)throw new Error(`Thread '${e}' already exists with platform '${i.platform}' \u2014 cannot change to '${t}' (platform is immutable)`);return {created:false}}return s.ensureThread(e,t,r),{created:true}}async fetchHistory(e,t){let r=t?.limit??100,s=this.getThreadRepo(),i=s.findThreadById(e),a=s.findTopLevelTasks(e,void 0,r),d=new Set(["queued","cancelled"]);a=a.filter(p=>(!p.status||!d.has(p.status))&&(!t?.currentTraceId||p.trace_id!==t.currentTraceId));let c=i?.platform??"cli",l=this.rowsToMessages(a),h=t?.includeHighlights===false?void 0:this.readActiveHighlights(e,i?.workspace_id??null);return {threadId:e,platform:c,messages:l,...h?{highlights:h}:{},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 fetchThreadState(e){try{let t=this.getThreadHistoryRepo().getSnapshot(e);if(!t)return;let r=new It({dbPath:this.dbPath}),s=(i,a)=>{try{return r.resolve(i,a)?.code_name||a}catch{return a}};return {...t.title?{title:t.title}:{},...t.priority?{priority:{code:t.priority,name:s("THREAD_PRIORITY",t.priority)}}:{},...t.state?{state:{code:t.state,name:s("THREAD_STATE",t.state)}}:{}}}catch{return}}async fetchHighlights(e){let t=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,t?.workspace_id??null)}async saveUserMessage(e,t,r,s){let{firstMessage:i}=this.getThreadRepo().saveUserMessage(e,t);return {id:e,firstMessage:i}}async saveAssistantMessage(e,t,r,s){return this.getThreadRepo().saveAssistantMessage(e,t),{id:e}}close(){}normalizeStatus(e){if(e&&!["success","completed","done"].includes(e)){if(["failed","error"].includes(e))return "failed";if(e==="running")return "running"}}readActiveHighlights(e,t){if(!t)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,t)??[]).filter(s=>typeof s.text=="string"&&s.text.length>0).map(s=>({id:s.id,text:s.text,kind:s.kind,source:s.source,coversFromTaskId:s.covers_from_task_id,coversToTaskId:s.covers_to_task_id,createdAt:s.created_at}))}catch{return}}rowsToMessages(e){let t=[];for(let r of e){r.prompt&&t.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let s=To(r.result),i=this.normalizeStatus(r.status);if(s||i==="running"||i==="failed"){let a={agent_id:r.agent_id,task_id:r.id};i&&(a.status=i),i==="failed"&&r.error&&(a.reason=r.error.split(`
|
|
365
|
+
`)[0].slice(0,200)),t.push({id:`${r.id}-assistant`,text:s,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:a});}}return t}};var er=class extends Ne{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new St(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,t,r,s){}async afterAssistantMessage(e,t,r){}attach(e){this.unsubStart=e.on("task:start",async t=>{if(!t.threadId)return;let r=t.platform??"cli";try{let s=await this._provider.ensureThread(t.threadId,r,t.workspaceId),i=await this._provider.saveUserMessage(t.threadId,t.message??"");await this.afterUserMessage(t.threadId,i.id,s.created||i.firstMessage,t);}catch{}}),this.unsubEnd=e.on("task:end",async t=>{if(!t.result)return;let r=t.metadata?.threadId;if(!r)return;let s=t.agentRef?.replace(/^@/,"")??"";try{let{id:i}=await this._provider.saveAssistantMessage(r,t.result,s);await this.afterAssistantMessage(r,i,t);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{er as ConversationPlugin,Nt as FileLoggerPlugin,Ut as SqliteTracingPlugin};
|