@crewx/sdk 0.9.0-rc.80 → 0.9.0-rc.82
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 +157 -161
- package/dist/esm/plugins/index.js +154 -142
- package/dist/esm/repository/index.js +61 -64
- package/dist/index.d.ts +2 -0
- package/dist/index.js +159 -163
- package/dist/plugins/index.js +160 -148
- package/dist/plugins/sqlite-tracing.d.ts +1 -0
- package/dist/provider/cli/adapter.types.d.ts +1 -1
- package/dist/repository/index.js +61 -64
- package/dist/repository/task.repository.d.ts +1 -0
- package/dist/task-log/anchor-child-tasks.d.ts +7 -0
- package/package.json +1 -1
|
@@ -1,59 +1,56 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as Re from'path';import Re__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import Po,{homedir}from'os';import {createHash,randomUUID,randomBytes}from'crypto';import {sql,eq,desc,and,isNull,lt,or,notLike,asc,like,inArray,gte,isNotNull,ne as ne$1}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey}from'drizzle-orm/sqlite-core';var st=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var vo=()=>fileURLToPath(import.meta.url),Ao=()=>Re__default.dirname(vo()),_=Ao();var Le=class{detach(e){}};function Bn(t){let e=n=>String(n).padStart(2,"0");return `${t.getFullYear()}${e(t.getMonth()+1)}${e(t.getDate())}T${e(t.getHours())}${e(t.getMinutes())}${e(t.getSeconds())}`}function Xt(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var Qt=class extends Le{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",n=>{try{existsSync(this.logsDir)||mkdirSync(this.logsDir,{recursive:!0});let r=Bn(n.timestamp),o=join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,o);let s=`=== TASK LOG: ${n.traceId} ===
|
|
2
2
|
CrewX Version: ${this.version}
|
|
3
|
-
Mode: ${
|
|
4
|
-
Agent: ${
|
|
5
|
-
Started: ${
|
|
6
|
-
Message: ${
|
|
3
|
+
Mode: ${n.mode}
|
|
4
|
+
Agent: ${n.agentRef}
|
|
5
|
+
Started: ${Xt(n.timestamp)}
|
|
6
|
+
Message: ${n.message}
|
|
7
7
|
|
|
8
|
-
`;writeFileSync(s,
|
|
9
|
-
`,"utf8");}catch{}}),e.on("task:end",
|
|
10
|
-
[${
|
|
11
|
-
`;appendFileSync(r,
|
|
8
|
+
`;writeFileSync(o,s,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=new Date().toISOString();appendFileSync(r,`[${o}] STDOUT: ${n.output}
|
|
9
|
+
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=Xt(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
|
|
10
|
+
[${o}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
11
|
+
`;appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};function Co(t){let e=Re.resolve(t);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(n,r)=>`${r.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function zn(t){let e=Co(t);return createHash("sha256").update(e).digest("hex")}var p=class extends Error{code;cause;constructor(e,n,r){super(n),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};var ne=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Po.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 Mo=32*1024*1024;function L(t){let e=st("better-sqlite3"),{drizzle:n}=st("drizzle-orm/better-sqlite3"),r=new e(t);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Mo}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),{db:n(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}var Vn=new Set,$o={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 Zt(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Ho(t,e){if(e>0||!Zt(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,s]of Object.entries($o))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var Uo={"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 Fo(t,e,n){if(!Zt(t,"__drizzle_migrations")||!Zt(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(Re__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=Uo[i.tag];if(!a)continue;let l=Re__default.join(e,`${i.tag}.sql`);if(!existsSync(l))continue;let c=readFileSync(l,"utf-8"),u=createHash("sha256").update(c).digest("hex");if(o.has(u))continue;let g=t.all("PRAGMA table_info(tasks)"),h=new Set(g.map(m=>m.name));for(let[m,b]of Object.entries(a))h.has(m)||(t.run(`ALTER TABLE tasks ADD COLUMN ${m} ${b}`),h.add(m));}}function qo(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(Re__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=Re__default.join(e,`${i.tag}.sql`);if(!existsSync(a))continue;let l=readFileSync(a,"utf-8"),c=createHash("sha256").update(l).digest("hex");if(o.has(c))continue;let u=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,g=[],h;for(;(h=u.exec(l))!==null;)g.push({table:h[1],column:h[2]});if(g.length===0||!l.split(/-->\s*statement-breakpoint/).map(v=>v.trim()).filter(Boolean).every(v=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(v)))continue;g.every(({table:v,column:A})=>t.all(`PRAGMA table_info("${v}")`).some(B=>B.name===A))&&t.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function Bo(t){let{migrate:e}=st("drizzle-orm/better-sqlite3/migrator"),{sql:n}=st("drizzle-orm"),r=[Re__default.join(_,"../migrations"),Re__default.join(_,"migrations"),Re__default.join(_,"../../../../drizzle/migrations"),Re__default.join(process.cwd(),"drizzle/migrations")],o=r.find(c=>existsSync(Re__default.join(c,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
12
12
|
${r.join(`
|
|
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
|
-
(${
|
|
13
|
+
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ho(t,i),s?.cnt&&(qo(t,o,n),Fo(t,o,n)),e(t,{migrationsFolder:o});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${l} migration${l>1?"s":""} applied).`);}}function ge(t,e){Vn.has(e)||(Bo(t),Vn.add(e));}var Je=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 d=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)},t=>({log_storage_check:check("tasks_log_storage_ck",sql`${t.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:index("idx_tasks_status").on(t.status),idx_tasks_started_at:index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(t.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(t.workspace_id,t.started_at)}));var fe=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>d.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},t=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq)}));var Qo="json_extract(metadata, '$.threadTitle.state')",Zo="json_extract(metadata, '$.threadTitle.priority')",f=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Je.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)},t=>({idx_threads_updated_at:index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_title:index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(t.workspace_id,sql.raw(Qo)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(Zo))}));var ns=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>d.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>ns.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")},t=>({idx_spans_task_id:index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(t.parent_span_id)}));sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>d.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()},t=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(t.timestamp)}));sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>f.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()},t=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:unique().on(t.thread_id,t.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")},t=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(t.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")},t=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.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")},t=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.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")},t=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(t.workspace_id,sql`${t.created_at} DESC`)}));sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},t=>({pk:primaryKey({columns:[t.notification_id,t.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()},t=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.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()},t=>({idCheck:check("ui_instances_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${t.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${t.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${t.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.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")},t=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${t.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${t.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${t.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${t.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
14
|
+
(${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
|
|
15
15
|
OR
|
|
16
|
-
(${
|
|
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`
|
|
16
|
+
(${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
|
|
17
|
+
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));var ir=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")},t=>({idCheck:check("projects_id_ck",sql`${t.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${t.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(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${t.stage_index} >= 1`)}));sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>ir.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()},t=>({idCheck:check("project_criteria_id_ck",sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)}));sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>ir.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()},t=>({idCheck:check("project_events_id_ck",sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));var dn=["THREAD_STATE","THREAD_PRIORITY"],ln=["gray","blue","violet","green","amber","orange","red","pink"],T=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()},t=>({pk:primaryKey({columns:[t.code_group,t.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${t.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));var ar=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],dr=["user","agent","system"],lr=["auto","manual"],cr=["decision","judgment","issue","result","pivot"];var ur=["queued","running","completed","failed"],C=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>f.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")},t=>({typeCheck:check("thread_events_type_ck",sql`${t.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`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),S=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>f.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")},t=>({statusCheck:check("thread_highlight_runs_status_ck",sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:check("thread_highlight_runs_counts_ck",sql`(${t.previous_auto_count} IS NULL OR ${t.previous_auto_count} >= 0) AND (${t.new_auto_count} IS NULL OR ${t.new_auto_count} >= 0)`),threadRequestUnique:uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),E=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>f.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")},t=>({sourceCheck:check("thread_highlights_source_ck",sql`${t.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${t.source} = 'manual' OR (${t.source} = 'auto' AND ${t.source_task_id} IS NOT NULL AND ${t.detector_version} IS NOT NULL AND ${t.content_fingerprint} IS NOT NULL AND length(${t.source_task_id}) > 0 AND length(${t.detector_version}) > 0 AND length(${t.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(sql`${t.source} = 'auto'`)}));function pr(t){let e=t.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let n=e.lastIndexOf("/");return n>=0&&(e=e.slice(n+1)),e=e.replace(/-\d{8}$/,""),e}function _r(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new p("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new p("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function hr(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new p("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new p("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>_r(r,o))}catch(r){throw r instanceof p?new p("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function kr(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new p("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new p("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new p("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function mr(t){return {taskId:t.id,source:kr(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Ds(t){if(!Number.isInteger(t)||t<0)throw new p("VALIDATION","Task log tail limit must be a non-negative integer")}var Lt=class extends ne{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 n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(eq(d.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:d.id,log_storage:d.log_storage,last_log_seq:d.last_log_seq,log_revision:d.log_revision,logs:d.logs}).from(d).where(eq(d.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new p("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,i)=>_r(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new p("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let a=this.requireStateRowInTransaction(i,e),l=kr(a);if(l==="blob"){let h=hr(e,a.logs);if(i.update(d).set({logs:JSON.stringify([...h,...r]),log_revision:sql`${d.log_revision} + 1`}).where(eq(d.id,e)).run().changes!==1)throw new p("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:a.log_revision+1,lastSeq:a.last_log_seq}}let c=a.last_log_seq+1,u=a.last_log_seq+r.length;if(i.insert(fe).values(r.map((h,m)=>({task_id:e,seq:c+m,timestamp:h.timestamp,level:h.level,message:h.message}))).run(),i.update(d).set({last_log_seq:u,log_revision:sql`${d.log_revision} + 1`}).where(eq(d.id,e)).run().changes!==1)throw new p("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:a.log_revision+1,lastSeq:u}},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?mr(r):void 0}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Ds(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=mr(s);if(i.source==="blob"){let u=hr(e,s.logs);return {...i,entries:n===void 0?u:u.slice(Math.max(0,u.length-n))}}let a=o.select({seq:fe.seq,timestamp:fe.timestamp,level:fe.level,message:fe.message}).from(fe).where(eq(fe.task_id,e)).orderBy(n===void 0?asc(fe.seq):desc(fe.seq)),c=(n===void 0?a.all():a.limit(n).all()).map(({timestamp:u,level:g,message:h})=>({timestamp:u,level:g,message:h}));return n!==void 0&&c.reverse(),{...i,entries:c}},{behavior:"deferred"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};var pn=40,Oe="2026-05-09",Us="0.8.9-rc.13",be=10,Ce=parseInt(Us.split("rc.")[1]);function Tr(){let t=sql`
|
|
18
18
|
CASE
|
|
19
|
-
WHEN ${
|
|
20
|
-
WHEN ${
|
|
21
|
-
WHEN ${
|
|
22
|
-
WHEN ${
|
|
23
|
-
WHEN ${
|
|
24
|
-
WHEN ${
|
|
25
|
-
WHEN ${
|
|
19
|
+
WHEN ${d.model} LIKE 'claude-%' OR ${d.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
20
|
+
WHEN ${d.model} LIKE 'gpt-%' OR ${d.model} LIKE 'codex-%' THEN 'codex'
|
|
21
|
+
WHEN ${d.model} LIKE 'gemini-%' THEN 'gemini'
|
|
22
|
+
WHEN ${d.model} LIKE 'grok-%' THEN 'grok'
|
|
23
|
+
WHEN ${d.model} LIKE 'zai-%' OR ${d.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
24
|
+
WHEN ${d.model} LIKE 'minimax/%' THEN 'minimax'
|
|
25
|
+
WHEN ${d.model} LIKE 'qwen%' THEN 'qwen'
|
|
26
26
|
ELSE 'unknown'
|
|
27
27
|
END
|
|
28
|
-
`,e=sql`json_extract(${
|
|
28
|
+
`,e=sql`json_extract(${d.metadata}, '$.provider')`,n=sql`trim(${e})`,r=sql`substr(${n}, 1, instr(${n}, '/') - 1)`,o=sql`
|
|
29
29
|
CASE
|
|
30
|
-
WHEN instr(${
|
|
30
|
+
WHEN instr(${n}, '/') > 0
|
|
31
31
|
AND ${r} IN ('cli', 'acp', 'api', 'plugin', 'remote')
|
|
32
|
-
THEN substr(${
|
|
33
|
-
ELSE ${
|
|
32
|
+
THEN substr(${n}, instr(${n}, '/') + 1)
|
|
33
|
+
ELSE ${n}
|
|
34
34
|
END
|
|
35
35
|
`;return sql`
|
|
36
36
|
CASE
|
|
37
|
-
WHEN ${
|
|
38
|
-
WHEN json_valid(${
|
|
39
|
-
WHEN json_type(${
|
|
40
|
-
WHEN json_type(${
|
|
41
|
-
WHEN json_type(${
|
|
42
|
-
WHEN ${
|
|
43
|
-
WHEN trim(${
|
|
44
|
-
ELSE ${
|
|
37
|
+
WHEN ${d.metadata} IS NULL THEN ${t}
|
|
38
|
+
WHEN json_valid(${d.metadata}) = 0 THEN 'unknown'
|
|
39
|
+
WHEN json_type(${d.metadata}, '$') IS NOT 'object' THEN 'unknown'
|
|
40
|
+
WHEN json_type(${d.metadata}, '$.provider') IS NULL THEN ${t}
|
|
41
|
+
WHEN json_type(${d.metadata}, '$.provider') IS NOT 'text' THEN 'unknown'
|
|
42
|
+
WHEN ${n} = '' THEN 'unknown'
|
|
43
|
+
WHEN trim(${o}) = '' THEN 'unknown'
|
|
44
|
+
ELSE ${o}
|
|
45
45
|
END
|
|
46
|
-
`}var
|
|
46
|
+
`}var Fs=new Set(["workflow","mcp"]),gn="usageByEpoch";function fn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function yr(t){if(!t)return {};try{let e=JSON.parse(t);return fn(e)?{...e}:{}}catch{return {}}}function se(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function wr(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function qs(t){return {inputTokens:se(t.inputTokens??0),outputTokens:se(t.outputTokens??0),cachedInputTokens:se(t.cachedInputTokens??0),costUsd:se(t.costUsd??0)}}function Bs(t){if(fn(t))return {inputTokens:se(t.inputTokens),outputTokens:se(t.outputTokens),cachedInputTokens:se(t.cachedInputTokens),costUsd:se(t.costUsd)}}function js(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=Bs(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Gs(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}var Er=600*1e3,$t=class extends ne{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 Lt({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}startTask(e){let n=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"},o=s=>{n.db.insert(d).values(s).onConflictDoUpdate({target:d.id,set:{pid:sql`COALESCE(excluded.pid, ${d.pid})`},setWhere:eq(d.status,"running")}).run();};try{o(r);}catch(s){let i=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage/i.test(i)||!/no such column|no column named/i.test(i))throw s;n.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
|
|
54
|
-
exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
|
|
55
|
-
model=COALESCE(?, model)
|
|
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`
|
|
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 p?r:new p("DB_ERROR","Failed to start task",r)}finally{n.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(d).where(eq(d.project_id,e)).orderBy(desc(d.started_at)).all()}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true);try{n.db.transaction(r=>{let o=r.select({status:d.status,run_epoch:d.run_epoch,started_at:d.started_at,metadata:d.metadata}).from(d).where(eq(d.id,e.id)).limit(1).get();if(!o)return;let s=wr(o.run_epoch),i=wr(e.runEpoch),a=o.status==="running"&&s===i,l=s>0||i>0||e.runEpoch!==void 0&&e.runEpoch!==null||s!==i,c={},u;if(l){u=yr(o.metadata);let g=fn(u[gn])?{...u[gn]}:{};g[String(i)]=qs(e),u[gn]=g;let h=js(g);c.metadata=JSON.stringify(u),c.input_tokens=h.inputTokens,c.output_tokens=h.outputTokens,c.cached_input_tokens=h.cachedInputTokens,c.cost_usd=h.costUsd;}else a&&(c.input_tokens=se(e.inputTokens??0),c.output_tokens=se(e.outputTokens??0),c.cached_input_tokens=se(e.cachedInputTokens??0),c.cost_usd=se(e.costUsd??0));a&&e.model!==void 0&&e.model!==null&&(c.model=e.model),e.partialResultRecovered===!0&&a&&(u??=yr(o.metadata),u.partialResultRecovered=!0,c.metadata=JSON.stringify(u)),a&&(c.status=e.status,c.result=e.result??null,c.error=e.error??null,c.completed_at=e.completedAt,c.duration_ms=s>0?Gs(o.started_at,e.completedAt,e.durationMs):e.durationMs??null,c.exit_code=e.exitCode??null),Object.keys(c).length>0&&r.update(d).set(c).where(eq(d.id,e.id)).run();},{behavior:"immediate"});}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to finish task",r)}finally{n.close();}}appendLog(e,n){this.taskLogRepository.appendLog(e,n);}appendLogs(e,n){this.taskLogRepository.appendLogs(e,n);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,n){return this.taskLogRepository.readLogsTail(e,n)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(d).where(eq(d.status,"running")).orderBy(desc(d.started_at)).all()}catch(n){throw new p("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(d).orderBy(desc(d.started_at)).limit(100).all()}catch(n){throw new p("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(d).where(eq(d.id,e)).limit(1).get()??void 0}catch(r){throw new p("DB_ERROR","Failed to get task",r)}finally{n.close();}}killTask(e){if(!this.dbExists())return {killed:false};let n=this.openHandle(true);try{let r=n.db.select({id:d.id,status:d.status,pid:d.pid}).from(d).where(eq(d.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return n.db.update(d).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(d.id,e),eq(d.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to kill task",r)}finally{n.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let n=e.db.select({id:d.id,pid:d.pid,platform:d.platform,run_epoch:d.run_epoch}).from(d).where(eq(d.status,"running")).all(),r=Date.now(),o=new Set,s=0;for(let i of n){if(i.pid){let c=!1;try{process.kill(i.pid,0),c=!0;}catch{}c||(e.db.update(d).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(d.id,i.id),eq(d.status,"running"))).run(),s++);continue}if(Fs.has(i.platform??"cli"))continue;let a=`${i.id}:${i.run_epoch??0}`;o.add(a);let l=this.pidNullObservedSince.get(a);if(l===void 0){this.pidNullObservedSince.set(a,r);continue}r-l>=Er&&(e.db.update(d).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(d.id,i.id),eq(d.status,"running"))).run(),s++,this.pidNullObservedSince.delete(a));}for(let i of Array.from(this.pidNullObservedSince.keys()))o.has(i)||this.pidNullObservedSince.delete(i);return s}finally{e.close();}}reapRunningWorkflowTasks(e=Er){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString();return n.db.update(d).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(d.status,"running"),eq(d.platform,"workflow"),isNull(d.pid),lt(d.started_at,r),or(isNull(d.metadata),and(notLike(d.metadata,'%"kind":"workflow_card"%'),notLike(d.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=L(o);try{let i=n?eq(d.workspace_id,n):void 0,a=i?and(eq(d.id,e),i):eq(d.id,e),l=s.db.select().from(d).where(a).limit(1).get()??void 0;if(!l){let c=i?and(eq(d.thread_id,e),i):eq(d.thread_id,e);l=s.db.select().from(d).where(c).orderBy(desc(d.started_at)).limit(1).get()??void 0;}if(l)return l}catch(i){throw new p("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let a=L(i);try{let l=n?and(eq(d.parent_task_id,e),eq(d.workspace_id,n)):eq(d.parent_task_id,e),c=a.db.select().from(d).where(l).orderBy(asc(d.started_at)).all();for(let u of c)o.has(u.id)||(o.add(u.id),s.push(u));}catch(l){throw new p("DB_ERROR","Failed to find child tasks",l)}finally{a.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?sql`
|
|
57
54
|
SELECT
|
|
58
55
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
59
56
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -74,7 +71,7 @@ ${r.join(`
|
|
|
74
71
|
FROM tasks
|
|
75
72
|
GROUP BY workspace_id
|
|
76
73
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
77
|
-
`)}catch(r){throw new
|
|
74
|
+
`)}catch(r){throw new p("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,a=0;for(let l of r){if(!existsSync(l))continue;let c=L(l);try{let u=eq(d.thread_id,e),g=n?and(u,eq(d.workspace_id,n)):u,h=c.db.select({id:d.id,input_tokens:d.input_tokens,output_tokens:d.output_tokens,cost_usd:d.cost_usd}).from(d).where(g).all();for(let m of h)o.has(m.id)||(o.add(m.id),s+=m.input_tokens??0,i+=m.output_tokens??0,a+=m.cost_usd??0);}catch(u){throw new p("DB_ERROR","Failed to get thread token usage",u)}finally{c.close();}}return {inputTokens:s,outputTokens:i,costUsd:a}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],a=r?.projection==="activity-log";for(let l of o){if(!existsSync(l))continue;let c=L(l);try{let u=eq(d.thread_id,e),g=n?and(u,eq(d.workspace_id,n)):u,h=a?c.db.select({id:d.id,thread_id:d.thread_id,agent_id:d.agent_id,parent_task_id:d.parent_task_id,started_at:d.started_at,completed_at:d.completed_at}).from(d).where(g).orderBy(asc(d.started_at)).all():c.db.select().from(d).where(g).orderBy(asc(d.started_at)).all();for(let m of h)s.has(m.id)||(s.add(m.id),i.push(m));}catch(u){throw new p("DB_ERROR","Failed to find tasks by thread",u)}finally{c.close();}}return i}parseWorkflowCardMetadata(e){if(!e)return {};try{let n=JSON.parse(e);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.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 n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=L(n);try{e.push(...r.db.select({id:d.id,agent_id:d.agent_id,thread_id:d.thread_id,workspace_id:d.workspace_id,platform:d.platform,status:d.status,error:d.error,completed_at:d.completed_at,duration_ms:d.duration_ms,started_at:d.started_at,metadata:d.metadata}).from(d).where(and(eq(d.platform,"workflow"),or(like(d.metadata,'%"kind":"workflow_card"%'),like(d.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(d.started_at)).all());}catch(o){throw new p("DB_ERROR","Failed to find workflow parent tasks",o)}finally{r.close();}}return e}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let o=new Set(e),s=new Map,i=n?eq(d.workspace_id,n):void 0,a=(l,c)=>{if(!l)return;let u=s.get(l);if(u&&c.started_at<=u)return;let g=this.parseWorkflowCardMetadata(c.metadata);g.kind!=="workflow_card"&&g.kind!=="workflow_ui_instance"||(s.set(l,c.started_at),r.set(l,{taskId:c.id,workflowRunId:g.workflowRunId,raw:c.result??void 0}));};for(let l of this.resolveDbPaths()){if(!existsSync(l))continue;let c=L(l);try{let u=and(inArray(d.thread_id,e),or(like(d.metadata,'%"kind":"workflow_card"%'),like(d.metadata,'%"kind":"workflow_ui_instance"%'))),g=c.db.select({id:d.id,thread_id:d.thread_id,metadata:d.metadata,result:d.result,started_at:d.started_at}).from(d).where(i?and(u,i):u).all();for(let b of g)a(b.thread_id,b);let h=and(isNull(d.thread_id),or(like(d.metadata,'%"kind":"workflow_card"%'),like(d.metadata,'%"kind":"workflow_ui_instance"%'))),m=c.db.select({id:d.id,command:d.command,metadata:d.metadata,result:d.result,started_at:d.started_at}).from(d).where(i?and(h,i):h).all();for(let b of m){let v=this.extractThreadIdFromCommand(b.command);!v||!o.has(v)||a(v,b);}}catch(u){throw new p("DB_ERROR","Failed to batch fetch workflow cards",u)}finally{c.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(d.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(inArray(d.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(inArray(d.status,s));let i=e.q??e.search;i&&r.push(like(d.prompt,`%${i}%`)),e.from&&r.push(gte(d.started_at,e.from)),e.to&&r.push(lt(d.started_at,e.to));let a=r.length>0?and(...r):void 0,l=n.db.select({count:sql`count(*)`}).from(d).where(a).get(),c=(e.sortDir??"DESC")==="ASC"?asc(d.started_at):desc(d.started_at);return {rows:n.db.select().from(d).where(a).orderBy(c).limit(e.limit).offset(e.offset).all(),total:l?.count??0}}catch(r){throw new p("DB_ERROR","Failed to find all tasks",r)}finally{n.close();}}getAgentUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(r?sql`
|
|
78
75
|
SELECT
|
|
79
76
|
t.agent_id,
|
|
80
77
|
t.workspace_id,
|
|
@@ -82,11 +79,11 @@ ${r.join(`
|
|
|
82
79
|
COALESCE(SUM(
|
|
83
80
|
COALESCE(t.input_tokens, 0)
|
|
84
81
|
+ CASE
|
|
85
|
-
WHEN t.started_at >= ${
|
|
82
|
+
WHEN t.started_at >= ${Oe}
|
|
86
83
|
AND (
|
|
87
84
|
t.crewx_version IS NULL
|
|
88
85
|
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, ${
|
|
86
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ce})
|
|
90
87
|
)
|
|
91
88
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
92
89
|
ELSE 0
|
|
@@ -98,18 +95,18 @@ ${r.join(`
|
|
|
98
95
|
FROM tasks t
|
|
99
96
|
WHERE t.status IN ('completed', 'success')
|
|
100
97
|
AND t.started_at >= ${e}
|
|
101
|
-
AND t.started_at < ${
|
|
98
|
+
AND t.started_at < ${n}
|
|
102
99
|
AND t.workspace_id = ${r}
|
|
103
100
|
GROUP BY t.agent_id, t.workspace_id
|
|
104
101
|
ORDER BY (
|
|
105
102
|
COALESCE(SUM(
|
|
106
103
|
COALESCE(t.input_tokens, 0)
|
|
107
104
|
+ CASE
|
|
108
|
-
WHEN t.started_at >= ${
|
|
105
|
+
WHEN t.started_at >= ${Oe}
|
|
109
106
|
AND (
|
|
110
107
|
t.crewx_version IS NULL
|
|
111
108
|
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, ${
|
|
109
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ce})
|
|
113
110
|
)
|
|
114
111
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
115
112
|
ELSE 0
|
|
@@ -125,11 +122,11 @@ ${r.join(`
|
|
|
125
122
|
COALESCE(SUM(
|
|
126
123
|
COALESCE(t.input_tokens, 0)
|
|
127
124
|
+ CASE
|
|
128
|
-
WHEN t.started_at >= ${
|
|
125
|
+
WHEN t.started_at >= ${Oe}
|
|
129
126
|
AND (
|
|
130
127
|
t.crewx_version IS NULL
|
|
131
128
|
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, ${
|
|
129
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ce})
|
|
133
130
|
)
|
|
134
131
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
135
132
|
ELSE 0
|
|
@@ -141,17 +138,17 @@ ${r.join(`
|
|
|
141
138
|
FROM tasks t
|
|
142
139
|
WHERE t.status IN ('completed', 'success')
|
|
143
140
|
AND t.started_at >= ${e}
|
|
144
|
-
AND t.started_at < ${
|
|
141
|
+
AND t.started_at < ${n}
|
|
145
142
|
GROUP BY t.agent_id, t.workspace_id
|
|
146
143
|
ORDER BY (
|
|
147
144
|
COALESCE(SUM(
|
|
148
145
|
COALESCE(t.input_tokens, 0)
|
|
149
146
|
+ CASE
|
|
150
|
-
WHEN t.started_at >= ${
|
|
147
|
+
WHEN t.started_at >= ${Oe}
|
|
151
148
|
AND (
|
|
152
149
|
t.crewx_version IS NULL
|
|
153
150
|
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, ${
|
|
151
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ce})
|
|
155
152
|
)
|
|
156
153
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
157
154
|
ELSE 0
|
|
@@ -159,18 +156,18 @@ ${r.join(`
|
|
|
159
156
|
), 0)
|
|
160
157
|
+ COALESCE(SUM(t.output_tokens), 0)
|
|
161
158
|
) DESC
|
|
162
|
-
`).map(
|
|
159
|
+
`).map(i=>({agentId:i.agent_id,workspaceId:i.workspace_id??null,totalTasks:i.total_tasks,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new p("DB_ERROR","Failed to get agent usage",s)}finally{o.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(r?sql`
|
|
163
160
|
SELECT
|
|
164
161
|
date(t.started_at) AS date,
|
|
165
162
|
t.agent_id,
|
|
166
163
|
COALESCE(SUM(
|
|
167
164
|
COALESCE(t.input_tokens, 0)
|
|
168
165
|
+ CASE
|
|
169
|
-
WHEN t.started_at >= ${
|
|
166
|
+
WHEN t.started_at >= ${Oe}
|
|
170
167
|
AND (
|
|
171
168
|
t.crewx_version IS NULL
|
|
172
169
|
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, ${
|
|
170
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ce})
|
|
174
171
|
)
|
|
175
172
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
176
173
|
ELSE 0
|
|
@@ -182,7 +179,7 @@ ${r.join(`
|
|
|
182
179
|
FROM tasks t
|
|
183
180
|
WHERE t.status IN ('completed', 'success')
|
|
184
181
|
AND t.started_at >= ${e}
|
|
185
|
-
AND t.started_at < ${
|
|
182
|
+
AND t.started_at < ${n}
|
|
186
183
|
AND t.workspace_id = ${r}
|
|
187
184
|
GROUP BY date(t.started_at), t.agent_id
|
|
188
185
|
ORDER BY date(t.started_at) ASC
|
|
@@ -193,11 +190,11 @@ ${r.join(`
|
|
|
193
190
|
COALESCE(SUM(
|
|
194
191
|
COALESCE(t.input_tokens, 0)
|
|
195
192
|
+ CASE
|
|
196
|
-
WHEN t.started_at >= ${
|
|
193
|
+
WHEN t.started_at >= ${Oe}
|
|
197
194
|
AND (
|
|
198
195
|
t.crewx_version IS NULL
|
|
199
196
|
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, ${
|
|
197
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ce})
|
|
201
198
|
)
|
|
202
199
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
203
200
|
ELSE 0
|
|
@@ -209,101 +206,116 @@ ${r.join(`
|
|
|
209
206
|
FROM tasks t
|
|
210
207
|
WHERE t.status IN ('completed', 'success')
|
|
211
208
|
AND t.started_at >= ${e}
|
|
212
|
-
AND t.started_at < ${
|
|
209
|
+
AND t.started_at < ${n}
|
|
213
210
|
GROUP BY date(t.started_at), t.agent_id
|
|
214
211
|
ORDER BY date(t.started_at) ASC
|
|
215
|
-
`).map(
|
|
216
|
-
COALESCE(${
|
|
212
|
+
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new p("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(d).where(and(eq(d.id,e),eq(d.workspace_id,n))).limit(1).get()??void 0}catch(o){throw new p("DB_ERROR","Failed to find task for stop",o)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:d.id,thread_id:d.thread_id,status:d.status,result:d.result,error:d.error,started_at:d.started_at,completed_at:d.completed_at,metadata:d.metadata}).from(d).where(and(eq(d.agent_id,e.agentId),eq(d.workspace_id,e.workspaceId),sql`${d.metadata} IS NOT NULL AND json_valid(${d.metadata}) AND json_extract(${d.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(d.started_at)).limit(1).get()??null}catch(r){throw new p("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString(),i=r?and(eq(d.id,e),eq(d.status,"running"),eq(d.workspace_id,r)):and(eq(d.id,e),eq(d.status,"running"));o.db.update(d).set({status:"failed",error:n,completed_at:s}).where(i).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to mark task failed",s)}finally{o.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let a=L(i);try{let l=n?and(like(d.prompt,`%${e}%`),eq(d.workspace_id,n)):like(d.prompt,`%${e}%`),c=a.db.select().from(d).where(l).orderBy(asc(d.started_at)).all();for(let u of c)o.has(u.id)||(o.add(u.id),s.push(u));}catch(l){throw new p("DB_ERROR","Failed to find tasks by prompt hint",l)}finally{a.close();}}return s}getProviderUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Tr(),i=sql`
|
|
213
|
+
COALESCE(${d.input_tokens}, 0)
|
|
217
214
|
+ CASE
|
|
218
|
-
WHEN ${
|
|
215
|
+
WHEN ${d.started_at} >= ${Oe}
|
|
219
216
|
AND (
|
|
220
|
-
${
|
|
221
|
-
OR (${
|
|
222
|
-
OR (${
|
|
217
|
+
${d.crewx_version} IS NULL
|
|
218
|
+
OR (${d.crewx_version} LIKE '0.8.%' AND ${d.crewx_version} NOT LIKE '0.8.9%')
|
|
219
|
+
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${be}) AS INTEGER) < ${Ce})
|
|
223
220
|
)
|
|
224
|
-
THEN COALESCE(${
|
|
221
|
+
THEN COALESCE(${d.cached_input_tokens}, 0)
|
|
225
222
|
ELSE 0
|
|
226
223
|
END
|
|
227
|
-
`,
|
|
224
|
+
`,a=r?sql`WHERE ${d.status} IN ('completed', 'success') AND ${d.started_at} >= ${e} AND ${d.started_at} < ${n} AND ${d.workspace_id} = ${r}`:sql`WHERE ${d.status} IN ('completed', 'success') AND ${d.started_at} >= ${e} AND ${d.started_at} < ${n}`;return o.db.all(sql`
|
|
228
225
|
SELECT
|
|
229
|
-
${
|
|
226
|
+
${s} AS provider,
|
|
230
227
|
COUNT(*) AS total_tasks,
|
|
231
|
-
COALESCE(SUM(${
|
|
232
|
-
COALESCE(SUM(${
|
|
233
|
-
COALESCE(SUM(${
|
|
234
|
-
COALESCE(SUM(${
|
|
235
|
-
COALESCE(SUM(${
|
|
236
|
-
MAX(${
|
|
237
|
-
FROM ${
|
|
238
|
-
${
|
|
239
|
-
GROUP BY ${
|
|
240
|
-
ORDER BY (COALESCE(SUM(${
|
|
241
|
-
`).map(
|
|
242
|
-
COALESCE(${
|
|
228
|
+
COALESCE(SUM(${i}), 0) AS input_tokens,
|
|
229
|
+
COALESCE(SUM(${d.output_tokens}), 0) AS output_tokens,
|
|
230
|
+
COALESCE(SUM(${d.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
231
|
+
COALESCE(SUM(${d.cost_usd}), 0) AS cost_usd,
|
|
232
|
+
COALESCE(SUM(${d.duration_ms}), 0) AS active_duration_ms,
|
|
233
|
+
MAX(${d.completed_at}) AS last_active_at
|
|
234
|
+
FROM ${d}
|
|
235
|
+
${a}
|
|
236
|
+
GROUP BY ${s}
|
|
237
|
+
ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${d.output_tokens}), 0)) DESC
|
|
238
|
+
`).map(c=>({provider:c.provider,totalTasks:c.total_tasks,inputTokens:c.input_tokens,outputTokens:c.output_tokens,cachedInputTokens:c.cached_input_tokens,costUsd:c.cost_usd,totalTokens:c.input_tokens+c.output_tokens,activeDurationMs:c.active_duration_ms??0,lastActiveAt:c.last_active_at??null}))}catch(s){throw new p("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Tr(),i=sql`
|
|
239
|
+
COALESCE(${d.input_tokens}, 0)
|
|
243
240
|
+ CASE
|
|
244
|
-
WHEN ${
|
|
241
|
+
WHEN ${d.started_at} >= ${Oe}
|
|
245
242
|
AND (
|
|
246
|
-
${
|
|
247
|
-
OR (${
|
|
248
|
-
OR (${
|
|
243
|
+
${d.crewx_version} IS NULL
|
|
244
|
+
OR (${d.crewx_version} LIKE '0.8.%' AND ${d.crewx_version} NOT LIKE '0.8.9%')
|
|
245
|
+
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${be}) AS INTEGER) < ${Ce})
|
|
249
246
|
)
|
|
250
|
-
THEN COALESCE(${
|
|
247
|
+
THEN COALESCE(${d.cached_input_tokens}, 0)
|
|
251
248
|
ELSE 0
|
|
252
249
|
END
|
|
253
|
-
`,
|
|
250
|
+
`,a=r?sql`WHERE ${d.status} IN ('completed', 'success') AND ${d.started_at} >= ${e} AND ${d.started_at} < ${n} AND ${d.workspace_id} = ${r}`:sql`WHERE ${d.status} IN ('completed', 'success') AND ${d.started_at} >= ${e} AND ${d.started_at} < ${n}`,l=o.db.all(sql`
|
|
254
251
|
SELECT
|
|
255
|
-
${
|
|
256
|
-
${
|
|
252
|
+
${d.model} AS model,
|
|
253
|
+
${s} AS provider,
|
|
257
254
|
COUNT(*) AS total_tasks,
|
|
258
|
-
COALESCE(SUM(${
|
|
259
|
-
COALESCE(SUM(${
|
|
260
|
-
COALESCE(SUM(${
|
|
261
|
-
COALESCE(SUM(${
|
|
262
|
-
COALESCE(SUM(${
|
|
263
|
-
MAX(${
|
|
264
|
-
FROM ${
|
|
265
|
-
${
|
|
266
|
-
GROUP BY ${
|
|
267
|
-
`),
|
|
255
|
+
COALESCE(SUM(${i}), 0) AS input_tokens,
|
|
256
|
+
COALESCE(SUM(${d.output_tokens}), 0) AS output_tokens,
|
|
257
|
+
COALESCE(SUM(${d.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
258
|
+
COALESCE(SUM(${d.cost_usd}), 0) AS cost_usd,
|
|
259
|
+
COALESCE(SUM(${d.duration_ms}), 0) AS active_duration_ms,
|
|
260
|
+
MAX(${d.completed_at}) AS last_active_at
|
|
261
|
+
FROM ${d}
|
|
262
|
+
${a}
|
|
263
|
+
GROUP BY ${d.model}, ${s}
|
|
264
|
+
`),c=new Map;for(let u of l){let g=pr(u.model??""),h=JSON.stringify([u.provider,g]),m=c.get(h);m?(m.totalTasks+=u.total_tasks,m.inputTokens+=u.input_tokens,m.outputTokens+=u.output_tokens,m.cachedInputTokens+=u.cached_input_tokens,m.costUsd+=u.cost_usd,m.totalTokens+=u.input_tokens+u.output_tokens,m.activeDurationMs+=u.active_duration_ms??0,u.last_active_at&&(!m.lastActiveAt||u.last_active_at>m.lastActiveAt)&&(m.lastActiveAt=u.last_active_at)):c.set(h,{model:g,provider:u.provider,totalTasks:u.total_tasks,inputTokens:u.input_tokens,outputTokens:u.output_tokens,cachedInputTokens:u.cached_input_tokens,costUsd:u.cost_usd,totalTokens:u.input_tokens+u.output_tokens,activeDurationMs:u.active_duration_ms??0,lastActiveAt:u.last_active_at??null});}return Array.from(c.values()).sort((u,g)=>g.costUsd-u.costUsd)}catch(s){throw new p("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=r?sql`WHERE ${d.started_at} >= ${e} AND ${d.started_at} < ${n} AND ${d.workspace_id} = ${r}`:sql`WHERE ${d.started_at} >= ${e} AND ${d.started_at} < ${n}`;return o.db.all(sql`
|
|
268
265
|
SELECT
|
|
269
|
-
${
|
|
270
|
-
${
|
|
271
|
-
${
|
|
272
|
-
${
|
|
273
|
-
${
|
|
274
|
-
${
|
|
275
|
-
FROM ${
|
|
276
|
-
${
|
|
277
|
-
ORDER BY ${
|
|
278
|
-
`).map(
|
|
279
|
-
COALESCE(${
|
|
266
|
+
${d.thread_id} AS thread_id,
|
|
267
|
+
${d.agent_id} AS agent_id,
|
|
268
|
+
${d.started_at} AS started_at,
|
|
269
|
+
${d.status} AS status,
|
|
270
|
+
${d.error} AS error,
|
|
271
|
+
${d.exit_code} AS exit_code
|
|
272
|
+
FROM ${d}
|
|
273
|
+
${s}
|
|
274
|
+
ORDER BY ${d.started_at} ASC
|
|
275
|
+
`).map(a=>({threadId:a.thread_id,agentId:a.agent_id,startedAt:a.started_at,status:a.status,error:a.error,exitCode:a.exit_code}))}catch(s){throw new p("DB_ERROR","Failed to get tasks for report",s)}finally{o.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let o=this.openHandle(false);try{let s=sql`
|
|
276
|
+
COALESCE(${d.input_tokens}, 0)
|
|
280
277
|
+ CASE
|
|
281
|
-
WHEN ${
|
|
278
|
+
WHEN ${d.started_at} >= ${Oe}
|
|
282
279
|
AND (
|
|
283
|
-
${
|
|
284
|
-
OR (${
|
|
285
|
-
OR (${
|
|
280
|
+
${d.crewx_version} IS NULL
|
|
281
|
+
OR (${d.crewx_version} LIKE '0.8.%' AND ${d.crewx_version} NOT LIKE '0.8.9%')
|
|
282
|
+
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${be}) AS INTEGER) < ${Ce})
|
|
286
283
|
)
|
|
287
|
-
THEN COALESCE(${
|
|
284
|
+
THEN COALESCE(${d.cached_input_tokens}, 0)
|
|
288
285
|
ELSE 0
|
|
289
286
|
END
|
|
290
|
-
`,
|
|
287
|
+
`,i=r?sql`WHERE ${d.status} IN ('completed', 'success') AND ${d.started_at} >= ${e} AND ${d.started_at} < ${n} AND ${d.workspace_id} = ${r}`:sql`WHERE ${d.status} IN ('completed', 'success') AND ${d.started_at} >= ${e} AND ${d.started_at} < ${n}`,a=o.db.all(sql`
|
|
291
288
|
SELECT
|
|
292
|
-
${
|
|
293
|
-
${
|
|
289
|
+
${d.caller_agent_id} AS caller_agent_id,
|
|
290
|
+
${d.agent_id} AS agent_id,
|
|
294
291
|
COUNT(*) AS task_count,
|
|
295
|
-
COALESCE(SUM(${
|
|
296
|
-
COALESCE(SUM(${
|
|
297
|
-
FROM ${
|
|
298
|
-
${
|
|
299
|
-
GROUP BY ${
|
|
300
|
-
ORDER BY task_count DESC, ${
|
|
301
|
-
LIMIT ${
|
|
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 (
|
|
292
|
+
COALESCE(SUM(${s}), 0) AS input_tokens,
|
|
293
|
+
COALESCE(SUM(${d.output_tokens}), 0) AS output_tokens
|
|
294
|
+
FROM ${d}
|
|
295
|
+
${i}
|
|
296
|
+
GROUP BY ${d.caller_agent_id}, ${d.agent_id}
|
|
297
|
+
ORDER BY task_count DESC, ${d.caller_agent_id} ASC, ${d.agent_id} ASC
|
|
298
|
+
LIMIT ${pn+1}
|
|
299
|
+
`),l=a.length>pn;return {edges:a.slice(0,pn).map(u=>({callerAgentId:u.caller_agent_id??null,agentId:u.agent_id,taskCount:u.task_count,totalTokens:u.input_tokens+u.output_tokens,outputTokens:u.output_tokens})),truncated:l}}catch(s){throw new p("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(d.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(inArray(d.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(inArray(d.status,e.statuses)),e.from&&r.push(gte(d.started_at,e.from)),e.to&&r.push(lt(d.started_at,e.to));let o=r.length>0?and(...r):void 0,s=(e.order??"DESC")==="ASC"?asc(d.started_at):desc(d.started_at),i={id:d.id,agent_id:d.agent_id,status:d.status,prompt:d.prompt,started_at:d.started_at,completed_at:d.completed_at,thread_id:d.thread_id};return e.limit?n.db.select(i).from(d).where(o).orderBy(s).limit(e.limit).all():n.db.select(i).from(d).where(o).orderBy(s).all()}catch(r){throw new p("DB_ERROR","Failed to find task evidence",r)}finally{n.close();}}findThreadChains(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[isNotNull(d.thread_id),isNull(d.parent_task_id),isNull(d.caller_agent_id),or(isNull(d.platform),ne$1(d.platform,"workflow")),or(isNull(d.metadata),and(notLike(d.metadata,'%"kind":"workflow_card"%'),notLike(d.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(d.metadata),notLike(d.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(d.workspace_id,e.workspaceId)),e.from&&s.push(gte(d.started_at,e.from)),e.to&&s.push(lt(d.started_at,e.to));let i=n.db.select({id:d.id,agent_id:d.agent_id,status:d.status,prompt:d.prompt,started_at:d.started_at,completed_at:d.completed_at,thread_id:d.thread_id}).from(d).where(and(...s)).orderBy(asc(d.started_at),asc(d.id)).all(),a=new Map;for(let c of i){if(!c.thread_id)continue;let u={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},g=a.get(c.thread_id);g?g.push(u):a.set(c.thread_id,[u]);}let l=[];for(let[c,u]of a){let g=u.filter(h=>h.agentId===e.targetAgentId).length;g<2||l.push({threadId:c,targetAgentTurnCount:g,turns:u});}return l.sort((c,u)=>{let g=c.turns[c.turns.length-1].startedAt,h=u.turns[u.turns.length-1].startedAt;return g<h?1:g>h?-1:0}),l.slice(0,r).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-o)}))}catch(r){throw new p("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}};var z=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};var Ne=class extends z{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};function Te(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function ye(t,e){let n=e.match(/@(\S+)/);return {timestamp:t,type:"agent_call",targetAgent:n?.[1]?.replace(/["']/g,""),toolInput:e}}function we(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var hn={claude:{models:[{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship",recommended:true},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindowTokens:4e5,tier:"speed"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",contextWindowTokens:4e5,tier:"flagship"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",contextWindowTokens:128e3,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-5.6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["minimal","low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-6-thinking",name:"Claude Opus 4.6 Thinking",contextWindowTokens:1e6,tier:"flagship"},{id:"gpt-oss-120b",name:"GPT-OSS 120B",contextWindowTokens:128e3,tier:"balanced"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}};Object.fromEntries(Object.entries(hn).map(([t,e])=>[t,e.models]));var Ws=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],zs={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};function mn(t){return zs[t]??t}var Vs=new Map(Ws.map(({baseModelId:t,catalogModelId:e})=>[t,e]));function Ks(t){return Vs.get(t)??t}var Js=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],Ys=new Map(Js.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));function _n(t){if(!t)return {};let e=Ys.get(t);return e?{...e}:{model:t}}function kn(t,e){return t==="antigravity"||t==="cli/antigravity"?_n(e):e===void 0?{}:{model:Ks(e)}}var Xs={};function Qs(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function qe(t){return Ht(t).models}function Ht(t){return Xs[t]??hn[t]??Qs()}function ut(t,e){let n=Ht(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=kn(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Rr(t){return Ht(t).modelOverrides}function Ir(){return qe("claude")}function vr(){return qe("codex")}function Ar(){return qe("copilot")}function Sr(){return qe("antigravity")}var Zs={auto:"default"};function xr(t){return Zs[t]??t}var ei=new Set(["minimal","low","medium","high","xhigh","max"]);function Be(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return ei.has(n)?{model:e[1],effort:e[2]}:{model:t}}return {model:t}}function Or(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["--sandbox","workspace-write"];default:return []}}function br(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Cr(t){return t?["-c",`model_reasoning_effort=${t}`]:[]}function Nr(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=xr(t);return e.has(n)?["--permission-mode",n]:[]}function Dr(t){return t?new Set(["low","medium","high","xhigh","max"]).has(t)?["--effort",t]:[]:[]}var ti=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);function Pr(t){return t==="default"?[]:t&&ti.has(t)?["--permission-mode",t]:[]}function Lr(t){return t===true?["--always-approve"]:[]}function Mr(t,e=n=>console.warn(n)){return t===void 0?[]:t==="workspace"||t==="read-only"||t==="off"?["--sandbox",t]:(e(`[grok] Invalid sandbox value ${JSON.stringify(t)}; using workspace.`),["--sandbox","workspace"])}function $r(t){return t?new Set(["low","medium","high","xhigh"]).has(t)?["--effort",t]:[]:[]}function Hr(t){if(!t)return [];switch(mn(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Ur(t){return t?new Set(["low","medium","high"]).has(t)?["--effort",t]:[]:[]}function ni(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function ri(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,a="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,l=i!==void 0?i:a??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:l}}function oi(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function Fr(t){let e=new Map,n;for(let s of t.split(`
|
|
300
|
+
`))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let a=i.message,l=a?.id,c=a?.usage;if(typeof l!="string"||!c)continue;let u=Number(c.input_tokens??0),g=Number(c.cache_read_input_tokens??0);e.set(l,{inputTokens:u+g,cachedInputTokens:g});let h=a?.model;typeof h=="string"&&h&&(n=h);}catch{}if(e.size===0)return;let r=0,o=0;for(let s of e.values())r+=s.inputTokens,o+=s.cachedInputTokens;return {inputTokens:r,cachedInputTokens:o,model:n}}function Xe(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
301
|
+
`))if(r.trim())try{let o=JSON.parse(r),s=oi(o);if(s){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedInputTokens+=s.cachedInputTokens;continue}let i=ni(o)??ri(o);i&&(e=i);}catch{}return n||(e??void 0)}var si=new Set(["tool_progress"]),Tn={command:"claude",meta:{displayName:"Claude",models:Ir(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Be(e.model),s=e.effort??o,i=Nr(e.mode),a=Dr(s),l=r?["--model",r]:[],c=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let g=[...e.additionalArgs];return g.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...c,...i,...a,...l,...g],stdinMessage:t}:{args:["--output-format","stream-json","--verbose",...c,...i,...a,...l,...g],stdinMessage:t}}return {args:["-p","--output-format","stream-json","--verbose",...c,...i,...a,...l],stdinMessage:t}},extractText(t){let e=t.split(`
|
|
302
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}return n.length>0?n[n.length-1]:r||t.trim()},extractFailure(t){try{let e=JSON.parse(t);if(e.type==="rate_limit_event"){let n=e.rate_limit_info??{};if(n.status==="rejected")return new Ne(`Claude rate limit: ${n.rateLimitType??"unknown"} (status: ${n.status})`)}if(e.error==="rate_limit"){let n=ii(e);return new Ne(n?`Claude rate limit: ${n}`:"Claude rate limit")}if(e.type==="result"&&e.is_error===!0){let n=typeof e.result=="string"?e.result:"";if(ai(n))return new Ne(`Claude rate limit: ${n}`)}}catch{}return null},parseResultMeta(t){let e=t.split(`
|
|
303
|
+
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,a=o.modelUsage,l=a?Object.keys(a)[0]??null:null;return {usage:i,model:l}}}catch{}let n=Fr(t);return n?{usage:{inputTokens:n.inputTokens,outputTokens:0,cachedInputTokens:n.cachedInputTokens,costUsd:0},model:n.model??null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(r!=="assistant"&&r!=="user")return [];let s=n.message?.content;if(!Array.isArray(s))return [];let i=e??new Date().toISOString(),a=[];for(let l of s){let c=di(i,l);c&&a.push(c);}return a},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?si.has(r):!1}catch{return false}}};function ii(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
304
|
+
|
|
305
|
+
`):""}function ai(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function di(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),o=e.id,s=e.input,i=we(s);return r==="Bash"&&Te(i)?ye(t,i):{timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(`
|
|
306
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,resultPreview:i,isError:r}}return null}var li=new Set(["interactive","plan","autopilot"]),ci=new Set(["none","low","medium","high","xhigh","max"]),yn={command:"copilot",meta:{displayName:"Copilot",models:Ar()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&li.has(e.mode)&&r.push("--mode",e.mode),e.effort&&ci.has(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=t.split(`
|
|
307
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}return n.length>0?n[n.length-1]:r||t.trim()},parseResultMeta(t){let e=Xe(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(!r.startsWith("tool.execution")&&!r.startsWith("assistant.")&&r!=="user.message")return [];let o=n.data;if(!o)return [];let s=e??new Date().toISOString(),i=o.toolCallId;if(r==="tool.execution_start"){let a=String(o.toolName||""),l=o.arguments,c=we(l);return (a==="bash"||a==="Bash")&&Te(c)?[ye(s,c)]:[{timestamp:s,type:"tool_use",toolName:a,toolInput:c,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let a=o.error;if(a)return [{timestamp:s,type:"tool_result",isError:true,resultPreview:String(a.message||""),...i&&{toolUseId:i}}];let l=o.result,c=String(l?.content||"");return [{timestamp:s,type:"tool_result",resultPreview:c,isError:false,...i&&{toolUseId:i}}]}if(r==="assistant.message"){let a=String(o.content||"");return a?[{timestamp:s,type:"text",content:a}]:[]}return []}};var ui=new Set(["turn.started","turn.completed","item.updated"]);function pi(t){let e=[],n=0,r=false,o=false,s=0;for(let a=0;a<t.length;a++){let l=t[a];if(o){o=false;continue}if(l==="\\"&&r){o=true;continue}if(l==='"'){r=!r;continue}if(!r){if(l==="{")n++;else if(l==="}"&&(n--,n===0)){let c=t.slice(s,a+1).trim();c&&e.push(c),s=a+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function gi(t){return t[0]==="exec"?t.slice(1):t}var wn={command:"codex",meta:{displayName:"Codex",models:vr(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Be(e.model),s=e.effort??o,i=e.resumeSessionId?br(e.mode):Or(e.mode),a=Cr(s),l=r?["-m",r]:[],c=gi(e.additionalArgs??[]),g=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...g,...i,...a,...l,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...g,...i,...a,...l,...c],stdinMessage:t}},extractText(t){let e=t.split(`
|
|
308
|
+
`).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}return n.length>0?n[n.length-1]:r||t.trim()},parseResultMeta(t){let e=Xe(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=pi(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let a=i.type;if(!a||!a.startsWith("item.")&&!a.startsWith("turn.")&&!a.startsWith("thread."))continue;let l=i.item;if(l){if(a==="item.started"){r.push(...fi(n,l));continue}if(a==="item.completed"){let c=hi(n,l);c&&r.push(c);continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?ui.has(r):!1}catch{return false}}};function fi(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return Te(r)?[ye(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function hi(t,e){let n=e.type;if(n==="message"||n==="text"){let r=e.content;if(Array.isArray(r))for(let o of r){let s=mi(t,o);if(s)return s}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(n==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(n==="reasoning"){let r=typeof e.text=="string"?e.text.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="command_execution"){let r=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:t,type:"tool_result",resultPreview:r,isError:o}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=we(o);return r==="Bash"&&Te(s)?ye(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}if(n==="tool_result"){let r=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",resultPreview:o,isError:r}}if(n==="web_search"){let r=e.action,o;if(r?.type==="search"){let s=r.queries;o=String(r.query||"")||(s?.length?s.join(", "):"")||String(e.query||"");}else o=e.query?"open: "+String(e.query):"";return o?{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:o}:null}if(n==="file_change"){let r=e.changes;if(!Array.isArray(r)||r.length===0)return null;let o=r.map(i=>String(i.path||"")).filter(Boolean);if(o.length===0)return null;let s=o.length===1?o[0]:`${o.slice(0,2).join(", ")}${o.length>2?` (+${o.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:s}}return null}function mi(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=we(o);return r==="Bash"&&Te(s)?ye(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var _i=new Set(["step_start","step_finish"]),Qe="cli/opencode",jr="OpenCode provider error",Gr=240,ki={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};function Ti(t){return t?ki[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Ut(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Wr(t){let e=[],n=0,r=false,o=false,s=0;for(let a=0;a<t.length;a++){let l=t[a];if(o){o=false;continue}if(l==="\\"&&r){o=true;continue}if(l==='"'){r=!r;continue}if(!r){if(l==="{")n++;else if(l==="}"&&(n--,n===0)){let c=t.slice(s,a+1).trim();c&&e.push(c),s=a+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function Ze(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function yi(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let i=JSON.parse(o);Ze(i)?e.push(i):n=!0;continue}catch{}let s=Wr(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let a=JSON.parse(i);Ze(a)?e.push(a):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function ze(t){if(typeof t!="string")return;let e=t.split(/\r?\n/).map(n=>n.trim()).find(n=>n&&!/^at\s+/.test(n));if(e)return e.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").replace(/(?:[A-Za-z]:[\\/]|\/)(?:[^\s"'`()\[\]{}]+[\\/])*[^\s"'`()\[\]{}]+/g,"[path]").slice(0,Gr).trim()}function zr(t){let e=Ze(t.error)?t.error:void 0,n=e&&Ze(e.data)?e.data:void 0,r=ze(e?.name),o=ze(n?.message)??ze(e?.message)??ze(t.message)??ze(t.errorMessage)??ze(t.error),s=ze(t.ref),i=r&&o&&r!==o?`${r}: ${o}`:r??o??jr;return (s?`${i} (ref: ${s})`:i).slice(0,Gr)}function qr(t){let e=yi(t),n=[],r=null,o=0,s=[],i,a=false;for(let l of e.events){let c=typeof l.type=="string"?l.type:void 0;if(c){if(c==="text"){let u=Ze(l.part)?l.part:void 0,g=typeof u?.text=="string"?u.text:void 0;g?.trim()&&n.push(g.trim());continue}if(c==="result"){typeof l.result=="string"&&(r=l.result);continue}if(c==="tool_use"){o++;continue}if(c==="error"){s.push(zr(l));continue}if(c==="step_finish"){a=true;let u=Ze(l.part)?l.part:void 0;i=typeof u?.reason=="string"?u.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorMessages:s,terminalReason:i,hasTerminal:a}}function Vr(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Ft(){return new z("OpenCode returned no assistant output.",Qe,{code:"EMPTY_OUTPUT",kind:"transient"})}function wi(){return new z("OpenCode emitted malformed JSON output.",Qe,{code:"PROVIDER_CRASHED",kind:"transient"})}function Br(t,e){switch(Vr(t)){case "length":return new z("OpenCode stopped because the context window was exceeded.",Qe,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new z("OpenCode stopped because the content filter blocked the response.",Qe,{code:"UNKNOWN",kind:"permanent"});case "error":return new z(e?`OpenCode error: ${e}`:`${jr} while generating a response.`,Qe,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var En={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Ut(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=Ti(e.mode);Ut(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!Ut(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!Ut(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let a;return !n&&!i&&!e.env?.OPENCODE_PERMISSION&&(a={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:a}},extractText(t){let e=qr(t),n=e.errorMessages[0];if(n){let i=Br("error",n);if(i)throw i}let r=Br(e.terminalReason??"",void 0);if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0){if(!e.hasTerminal)throw Ft();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Ft();return e.resultText}if(e.malformed)throw wi();if(!e.hasTerminal)throw Ft();let s=Vr(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Ft()},interpretExit(t,e,n=""){if(t===0)return null;let o=qr(n).errorMessages[0];return o?new z(`OpenCode error: ${o}`,Qe,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=Xe(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=Wr(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let a=i.type;if(a){if(a==="text"){let c=i.part?.text;c&&r.push({timestamp:n,type:"text",content:c});continue}if(a==="tool_use"){let l=i.part;if(!l)continue;let c=String(l.tool||""),u=String(l.callID||""),g=l.state,h=String(g?.status||""),m=g?.input,b=we(m);if(r.push({timestamp:n,type:"tool_use",toolName:c,toolUseId:u,toolInput:b}),h==="completed"&&g?.output!==void 0){let v=g.output,A=typeof v=="string"?v:JSON.stringify(v);r.push({timestamp:n,type:"tool_result",toolUseId:u,resultPreview:A,isError:false});}else h==="error"&&r.push({timestamp:n,type:"tool_result",toolUseId:u,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(a==="error"){let l=zr(i);r.push({timestamp:n,type:"error",content:l,errorMessage:l});continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?_i.has(r):!1}catch{return false}}};var Rn="antigravity";function pt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ei(t,e){if(!(t?qe(Rn).some(s=>s.id===t):false)||!t)return e;let r=ut(Rn,t),o=Rr(Rn)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var In={command:"agy",meta:{displayName:"Antigravity",models:Sr(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=Be(e.model),s=_n(r),i=s.model,a=e.effort??o??s.effort,l=Ei(i,a),c=e.additionalArgs??[],u=i&&!pt(c,"--model")?["--model",i]:[],g=pt(c,"--effort")?[]:Ur(l),h=pt(c,"--mode")||pt(c,"--dangerously-skip-permissions")?[]:Hr(e.mode),m=pt(c,"--print")?[]:["--print",t];return {args:[...u,...g,...h,...c,...m]}},extractText(t){let e=t.trim();if(!e)throw new z("Antigravity CLI returned empty output with exit code 0. agy may have hidden an auth/quota/model error in its log file; inspect ~/.gemini/antigravity-cli/log for details.","cli/antigravity",{code:"EMPTY_OUTPUT",kind:"transient"});return e},parseResultMeta(t){return {usage:null,model:null}},parseEvent(t,e){return []}};var qt="cli/grok",Ii=new Set(["available_commands","usage","end"]),vi=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,Ai=/\u001b\[[0-?]*[ -/]*[@-~]/g,Kr=20,Jr=4e3,Yr="\u2026";function et(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Bt(t){return et(t)?t:void 0}function Y(t){return typeof t=="string"?t:void 0}function Ve(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Si(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let a=t[i];if(n===-1){(a==="{"||a==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(a==="\\"&&o){s=true;continue}if(a==='"'){o=!o;continue}o||(a==="{"||a==="["?r+=1:(a==="}"||a==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function gt(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return et(n)?[n]:[]}catch{return Si(e).flatMap(n=>{try{let r=JSON.parse(n);return et(r)?[r]:[]}catch{return []}})}}function ft(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function ht(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(ht).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
309
|
+
`):void 0}if(et(t)){if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(t.type==="text"&&typeof t.data=="string")return t.data;for(let e of ["content","FileContent","rawOutput"]){let n=ht(t[e]);if(n!==void 0)return n}}}function xi(t){if(t.rawOutput!==null&&t.rawOutput!==void 0)return ht(t.rawOutput)??ft(t.rawOutput);if(t.content!==null&&t.content!==void 0)return ht(t.content)??ft(t.content);if(t.result!==null&&t.result!==void 0)return ht(t.result)??ft(t.result)}function Qr(t){let e=Bt(t.error),n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0].find(r=>typeof r=="string"&&r.trim().length>0);return n?Zr(n):"Grok CLI reported an error."}function Zr(t){return (t.replace(Ai,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Xr(t){return vi.test(t)}function Oi(t){let e=Bt(t.modelUsage);return e?Object.keys(e)[0]??null:null}function bi(t){let e=Bt(t.usage);if(!e)return null;let n=Ve(e.cache_read_input_tokens);return {inputTokens:Ve(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Ve(e.output_tokens),costUsd:Ve(t.total_cost_usd)}}function Ci(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
310
|
+
`).flatMap(gt)){if(i.type!=="usage")continue;let a=Bt(i.usage);if(!a)continue;let l=Y(i.signature);if(l&&l.length>0){let u=`signature:${l}`;if(s.has(u))continue;s.add(u);}let c=Ve(a.cache_read_input_tokens);e+=Ve(a.input_tokens)+c,n+=c,r+=Ve(a.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function Ni(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,Kr)){if(!et(s))continue;let i=Y(s.content)?.trim();if(!i)continue;let a=Y(s.status)?.trim(),l=Y(s.priority)?.trim(),c=[a?`status=${a}`:void 0,l?`priority=${l}`:void 0].filter(g=>!!g),u=c.length>0?` (${c.join(", ")})`:"";n.push(`- ${i}${u}`);}if(n.length===0)return [];e.entries.length>Kr&&n.push(Yr);let r=n.join(`
|
|
311
|
+
`),o=r.length>Jr?`${r.slice(0,Jr-1)}${Yr}`:r;return [{timestamp:t,type:"info",content:o}]}function Di(t,e){let n=Y(e.type);if(n==="thought"){let r=Y(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=Y(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return Ni(t,e);if(n==="tool_call"){let r=Y(e.toolCallId),o=Y(e.toolName)??Y(e.title),s=e.rawInput===void 0?void 0:ft(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=Y(e.status);return r!=="completed"&&r!=="failed"&&r!=="error"?[]:[{timestamp:t,type:"tool_result",toolUseId:Y(e.toolCallId),toolName:Y(e.toolName)??Y(e.title),resultPreview:xi(e),isError:r!=="completed"||e.isError===true}]}if(n==="error"){let r=Qr(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var vn={command:"grok",createSessionId:()=>randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=Be(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],a=n?qe("grok").some(ae=>ae.id===n):false,l=n&&a?ut("grok",n):[],c=!o||l.length===0||l.includes(o)?o:void 0,u=$r(c),g=e.additionalArgs??[],h=ae=>g.some(te=>te===ae||te.startsWith(`${ae}=`)),m=e.providerOptions,b=m?.alwaysApprove,v=m?.sandbox,A=h("--permission-mode")?[]:Pr(e.mode),H=h("--always-approve")?[]:Lr(b),B=h("--sandbox")?[]:Mr(v);return {args:["--no-auto-update",...s,"--single",t,"--output-format","streaming-json","--no-alt-screen",...i,...u,...A,...H,...B,...g]}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
312
|
+
`).flatMap(gt))typeof r.type=="string"&&(n=true),r.type==="text"&&typeof r.data=="string"&&e.push(r.data);return e.length>0?e.join(""):n?"":t.trim()},extractFailure(t){for(let e of gt(t))if(e.type==="error"){let n=Qr(e);return Xr(ft(e))?new Ne(n,qt):new z(n,qt)}return null},interpretExit(t,e){if(t===0)return null;let n=Zr(e)||`Grok CLI exited with code ${t}.`;return Xr(e)?new Ne(n,qt):new z(n,qt)},parseResultMeta(t){let n=t.split(`
|
|
313
|
+
`).flatMap(gt).find(r=>r.type==="end");return n?{usage:bi(n),model:Oi(n)}:{usage:Ci(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return gt(t).flatMap(r=>Di(n,r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return et(n)&&typeof n.type=="string"?Ii.has(n.type):!1}catch{return false}}};var eo={codex:wn,claude:Tn,opencode:En,antigravity:In,copilot:yn,grok:vn};function to(t){if(t.startsWith("cli/"))return eo[t.slice(4)]}var Li=200,Mi=200;function $i(t){if(typeof t!="object"||t===null||!("code"in t))return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function Hi(t){let e=t instanceof p?t.code:void 0,n=t instanceof p?t.cause:t,r=$i(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function ro(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Ui(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Fi(t){if(!t)return {};try{let e=JSON.parse(t);return Ui(e)?e:{}}catch{return {}}}function oo(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Sn=class extends Le{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 n=new $t({dbPath:this.dbPath});this.taskRepo=n;let r=process.cwd(),s=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))?zn(r):null,i=process.argv.join(" ");this.unsubs.push(e.on("task:start",a=>{try{let l=a.callerAgentId??null,c=a.parentTaskId??null,u=a.rootTraceId??a.traceId,g=a.metadata?JSON.stringify(a.metadata):JSON.stringify({provider:a.provider??"cli/claude"});n.startTask({id:a.traceId,agentId:a.agentRef.replace(/^@/,""),prompt:a.message,mode:a.mode,status:"running",pid:a.pid??null,startedAt:a.timestamp.toISOString(),crewxVersion:this.version,platform:a.platform??"cli",model:a.model??null,renderedPrompt:a.renderedPrompt??null,command:i,codingAgentCommand:a.codingAgentCommand??null,workspaceId:a.workspaceId??s,projectId:a.projectId??null,callerAgentId:l,parentTaskId:c,traceId:u,metadata:g,threadId:a.threadId??null});}catch{}}),e.on("task:output",a=>{try{this.enqueueLog(a.traceId,{timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output});}catch(l){let c={timestamp:a.timestamp.toISOString(),level:a.level??"stdout",message:a.output};this.recordAppendFailure(l,[c],ro(c));}}),e.on("task:end",a=>{try{this.flushTaskLogs(a.traceId);let l=typeof a.metadata?.runEpoch=="number"?a.metadata.runEpoch:null,c=a.error?JSON.stringify({code:a.error.code,message:a.error.message,...a.error.providerCode?{providerCode:a.error.providerCode}:{}}):null,u=a.result??null,g=!1;if(a.error&&(!u||u.trim()==="")){let h=this.recoverPartialResult(a.traceId,a,l);h&&(u=h,g=!0);}n.finishTask({id:a.traceId,status:a.error?"failed":"success",result:u,error:c,completedAt:a.timestamp.toISOString(),durationMs:a.durationMs,exitCode:a.exitCode??null,inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,cachedInputTokens:a.cachedInputTokens??0,costUsd:a.costUsd??0,model:a.model??null,runEpoch:l,partialResultRecovered:g});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.taskRepo=void 0;}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=ro(n),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=Li){this.flushTaskLogs(e);return}if(!r.timer){let o=setTimeout(()=>{let s=this.queues.get(e);!s||s.timer!==o||(s.timer=void 0,this.flushTaskLogs(e));},Mi);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo?.getTask(e);if(!o||o.status!=="running"||oo(o.run_epoch)!==oo(r))return;let s=Fi(o.metadata),i=typeof s.provider=="string"?s.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!i)return;let a=to(i);if(!a)return;let c=this.taskRepo?.readLogs(e)?.entries.filter(g=>g.level==="stdout").map(g=>g.message).join(`
|
|
314
|
+
`)??"";if(!c.trim())return;let u=a.extractText(c);return u.trim()?u:void 0}catch{return}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,o=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,o);}let s=this.queues.get(e);s&&s.entries.length===0&&(s.timer&&clearTimeout(s.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,n,r){let o=Hi(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[o.code]=(this.metrics.appendFailureByCode[o.code]??0)+1,this.metrics.appendFailureByCause[o.cause]=(this.metrics.appendFailureByCause[o.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:o.code,cause:o.cause,pendingEntries:n.length,pendingBytes:r});}};var tt=class extends p{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function mt(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Wi(t){let n=mt(t).threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {priority:null,state:null};let r=n;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}var jt=class extends ne{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 n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,n){return e.db.select({id:Je.id}).from(Je).where(eq(Je.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
303
315
|
SELECT 1 FROM tasks parent
|
|
304
316
|
WHERE parent.id = ${e}.parent_task_id
|
|
305
317
|
AND parent.thread_id = ${e}.thread_id
|
|
306
|
-
)`)}findAllThreads(e){let
|
|
318
|
+
)`)}findAllThreads(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!existsSync(s))continue;let i=L(s);try{let a=e?eq(f.workspace_id,e):void 0,l=i.db.select().from(f).where(a).orderBy(desc(f.updated_at)).all();for(let c of l)r.has(c.id)||(r.add(c.id),o.push(c));}catch(a){throw new p("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return o}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let a=L(i);try{let l=or(inArray(f.id,e),inArray(f.title,e)),c=n?and(l,eq(f.workspace_id,n)):l,u=a.db.select().from(f).where(c).orderBy(desc(f.updated_at)).all();for(let g of u)o.has(g.id)||(o.add(g.id),s.push(g));}catch(l){throw new p("DB_ERROR","Failed to find threads by ids or titles",l)}finally{a.close();}}return s}findThreadById(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=L(o);try{let i=eq(f.id,e),a=n?and(i,eq(f.workspace_id,n)):i,l=s.db.select().from(f).where(a).limit(1).get()??void 0;if(l)return l}catch(i){throw new p("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=L(o);try{let i=eq(f.id,e),a=n?and(i,eq(f.workspace_id,n)):i;if(s.db.select({id:f.id}).from(f).where(a).limit(1).get())return !0}catch(i){throw new p("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),o=0,s=0,i=0,a=0,l=0,c=new Set;for(let u of r){if(!existsSync(u))continue;let g=L(u);try{let h=g.db.get(sql`
|
|
307
319
|
SELECT
|
|
308
320
|
count(*) AS cnt,
|
|
309
321
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -313,31 +325,31 @@ ${r.join(`
|
|
|
313
325
|
FROM tasks child
|
|
314
326
|
WHERE child.thread_id = ${e}
|
|
315
327
|
AND ${this.topLevelTaskPredicateSql()}
|
|
316
|
-
${
|
|
317
|
-
`);
|
|
328
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
329
|
+
`);h&&(o+=h.cnt,s+=h.total_input,i+=h.total_output,a+=h.total_cached,l+=h.total_cost);let m=g.db.all(sql`
|
|
318
330
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
319
331
|
WHERE child.thread_id = ${e}
|
|
320
332
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
321
333
|
AND ${this.topLevelTaskPredicateSql()}
|
|
322
|
-
${
|
|
323
|
-
`);for(let
|
|
334
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
335
|
+
`);for(let b of m)c.add(b.agent_id);}catch(h){throw new p("DB_ERROR","Failed to aggregate task stats",h)}finally{g.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:a,costUsd:l,agentIds:Array.from(c)}}findTopLevelTasks(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[];for(let a of o){if(!existsSync(a))continue;let l=L(a);try{let c;r!==void 0?c=l.db.all(sql`
|
|
324
336
|
SELECT * FROM (
|
|
325
337
|
SELECT child.*,
|
|
326
338
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
327
339
|
FROM tasks child
|
|
328
340
|
WHERE child.thread_id = ${e}
|
|
329
341
|
AND ${this.topLevelTaskPredicateSql()}
|
|
330
|
-
${
|
|
342
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
331
343
|
) ranked
|
|
332
344
|
WHERE rn <= ${r}
|
|
333
345
|
ORDER BY started_at ASC
|
|
334
|
-
`):l
|
|
346
|
+
`):c=l.db.all(sql`
|
|
335
347
|
SELECT child.* FROM tasks child
|
|
336
348
|
WHERE child.thread_id = ${e}
|
|
337
349
|
AND ${this.topLevelTaskPredicateSql()}
|
|
338
|
-
${
|
|
350
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
339
351
|
ORDER BY child.started_at ASC
|
|
340
|
-
`);for(let
|
|
352
|
+
`);for(let u of c)s.has(u.id)||(s.add(u.id),i.push(u));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}if(r!==void 0&&o.length>1){let a=new Map;for(let l of i){let c=l.agent_id??"";a.has(c)||a.set(c,[]),a.get(c).push(l);}i=[];for(let l of a.values())l.sort((c,u)=>(u.started_at??"").localeCompare(c.started_at??"")),i.push(...l.slice(0,r));i.sort((l,c)=>(l.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let a=L(i);try{let l=eq(d.thread_id,e),c=n?and(l,eq(d.workspace_id,n)):l,u=a.db.select().from(d).where(c).orderBy(asc(d.started_at)).all();for(let g of u)o.has(g.id)||(o.add(g.id),s.push(g));}catch(l){throw new p("DB_ERROR","Failed to find all tasks for thread",l)}finally{a.close();}}return s}findTaskById(e,n,r){let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=L(s);try{let a=and(eq(d.id,n),eq(d.thread_id,e)),l=r?and(a,eq(d.workspace_id,r)):a,c=i.db.select().from(d).where(l).limit(1).get();if(!c)continue;let u=i.db.select().from(d).where(eq(d.parent_task_id,c.id)).orderBy(asc(d.started_at)).all();return {task:c,children:u}}catch(a){throw new p("DB_ERROR","Failed to find task by id",a)}finally{i.close();}}}batchFetchTasksQuery(e,n){return sql`
|
|
341
353
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
342
354
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
343
355
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -345,21 +357,21 @@ ${r.join(`
|
|
|
345
357
|
FROM tasks child INDEXED BY idx_tasks_thread_id
|
|
346
358
|
WHERE child.thread_id IN (${sql.join(e.map(r=>sql`${r}`),sql`, `)})
|
|
347
359
|
AND ${this.topLevelTaskPredicateSql()}
|
|
348
|
-
${
|
|
360
|
+
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
349
361
|
ORDER BY child.started_at ASC
|
|
350
|
-
`}batchFetchTasks(e,
|
|
362
|
+
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=L(s);try{let a=i.db.all(this.batchFetchTasksQuery(e,n));for(let l of a){let c=l.thread_id;r.has(c)||r.set(c,[]),r.get(c).push(l);}}catch(a){throw new p("DB_ERROR","Failed to batch fetch tasks",a)}finally{i.close();}}return r}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=L(o);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(a=>a.detail)}finally{s.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=eq(f.id,e),i=r?and(s,eq(f.workspace_id,r)):s;if(!o.db.select({id:f.id}).from(f).where(i).limit(1).get())return;o.db.update(f).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(f.id,e)).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,n){let r=this.openHandle(true);try{let o=n.workspaceId?this.validateWorkspaceId(r,n.workspaceId):null,s=new Date().toISOString();if(r.db.select({id:f.id,message_count:f.message_count}).from(f).where(eq(f.id,e)).limit(1).get()){let a={updated_at:s};n.title!==void 0&&(a.title=n.title),n.titleLocked!==void 0&&(a.title_locked=n.titleLocked?1:0),r.db.update(f).set(a).where(eq(f.id,e)).run();}else r.db.insert(f).values({id:e,platform:n.platform,workspace_id:o,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to upsert thread",o)}finally{r.close();}}ensureThread(e,n,r){let o=this.openHandle(true);try{let s=r?this.validateWorkspaceId(o,r):null,i=o.db.select({id:f.id,platform:f.platform,workspace_id:f.workspace_id}).from(f).where(eq(f.id,e)).limit(1).get();if(i){s&&!i.workspace_id&&o.db.update(f).set({workspace_id:s}).where(eq(f.id,e)).run();return}let a=new Date().toISOString();o.db.insert(f).values({id:e,platform:n,workspace_id:s,message_count:0,created_at:a,updated_at:a}).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to ensure thread",s)}finally{o.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(a=>{let c=a.select({message_count:f.message_count}).from(f).where(eq(f.id,e)).limit(1).get()?.message_count===0;return a.run(sql`
|
|
351
363
|
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 = ${
|
|
364
|
+
SET first_message = COALESCE(first_message, ${n}),
|
|
365
|
+
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
366
|
+
last_message = ${n},
|
|
355
367
|
message_count = message_count + 1,
|
|
356
|
-
updated_at = ${
|
|
368
|
+
updated_at = ${s}
|
|
357
369
|
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`
|
|
370
|
+
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(f).set({last_message:n,updated_at:s}).where(eq(f.id,e)).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};n.title!==void 0&&(o.title=n.title,o.title_locked=1),n.titleLocked!==void 0&&(o.title_locked=n.titleLocked?1:0),r.db.update(f).set(o).where(eq(f.id,e)).run();}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let o=n;if(!o||typeof o!="object"||Array.isArray(o))return new tt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new tt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new tt("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let l of [i.priority,i.state])if(l!=null&&(typeof l!="string"||l.length===0))return new tt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let a=this.openHandle(true);try{let l=r?and(eq(f.id,e),eq(f.workspace_id,r)):eq(f.id,e);return a.db.transaction(c=>{let u=c.select({metadata:f.metadata}).from(f).where(l).get();if(!u)return null;let g=mt(u.metadata),h=g.threadTitle,m=h&&typeof h=="object"&&!Array.isArray(h)?{...h}:{};i.priority===null?delete m.priority:i.priority!==void 0&&(m.priority=i.priority),i.state===null?delete m.state:i.state!==void 0&&(m.state=i.state),Object.keys(m).length>0?g.threadTitle=m:delete g.threadTitle;let b=Object.keys(g).length>0?JSON.stringify(g):null,v=new Date().toISOString();c.update(f).set({metadata:b,updated_at:v}).where(l).run();let A=c.select({metadata:f.metadata}).from(f).where(l).get();if(!A)throw new p("DB_ERROR","Thread-title metadata update could not be read back");let H=Wi(A.metadata);return {threadId:e,priority:H.priority,state:H.state}},{behavior:"immediate"})}catch(l){throw l instanceof p?l:new p("DB_ERROR","Failed to patch thread-title metadata",l)}finally{a.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?and(eq(f.id,e),eq(f.workspace_id,n)):eq(f.id,e);return r.db.transaction(s=>{let i=s.select({pinned:f.pinned,metadata:f.metadata}).from(f).where(o).get();if(!i)return null;let a=i.pinned?0:1,l=mt(i.metadata);if(a){let c=n?and(eq(f.pinned,1),eq(f.workspace_id,n)):eq(f.pinned,1),u=s.select({metadata:f.metadata}).from(f).where(c).all(),g=null;for(let h of u){let m=mt(h.metadata);typeof m.pinOrder=="number"&&(g===null||m.pinOrder<g)&&(g=m.pinOrder);}l.pinOrder=g===null?0:g-1;}else delete l.pinOrder;return s.update(f).set({pinned:a,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(o).run(),{pinned:!!a}},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{for(let s=0;s<e.length;s++){let i=n?and(eq(f.id,e[s]),eq(f.workspace_id,n)):eq(f.id,e[s]),a=o.select({metadata:f.metadata}).from(f).where(i).get();if(!a)continue;let l=mt(a.metadata);l.pinOrder=s+1,o.update(f).set({metadata:JSON.stringify(l)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?and(eq(f.id,e),eq(f.workspace_id,n)):eq(f.id,e),s=r.db.select({starred:f.starred}).from(f).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(f).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let a=n?and(eq(f.id,e),eq(f.workspace_id,n)):eq(f.id,e);return i.db.transaction(c=>{let u=c.select({metadata:f.metadata}).from(f).where(a).get();if(!u)return null;let g=u.metadata?JSON.parse(u.metadata):{},h=g.overdrive??{},m=o?.defaultTurns??h.defaultTurns??3,b=o?.updatedBy??"ui",v=new Date().toISOString(),A,H,B,ae;switch(r){case "enable-count":{let te=o?.turns??m,Pe=o?.consumeCurrent?Math.max(te-1,0):te;A=Pe>0?"count":"off",H=Pe,B=!0,ae="count";break}case "enable-latch":{A="latch",H=0,B=!0,ae="latch";break}case "disable":{A="off",H=0,B=!1;break}default:{let te=h.state??"off",Pe=typeof h.remaining=="number"?h.remaining:0;if(te==="count"&&Pe>0){let O=Pe-1;O<=0?(A="off",H=0):(A="count",H=O),B=!0,ae="count";}else te==="latch"?(A="latch",H=0,B=!0,ae="latch"):(A="off",H=0,B=!1);break}}return g.overdrive={state:A,remaining:H,defaultTurns:m,updatedAt:v,updatedBy:b},c.update(f).set({metadata:JSON.stringify(g),updated_at:v}).where(a).run(),{applied:B,appliedMode:ae,state:A,remaining:H}},{behavior:"immediate"})}catch(a){throw a instanceof p?a:new p("DB_ERROR","Failed to resolve overdrive",a)}finally{i.close();}}};var xn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function zi(t){let e=randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=xn[o%62]);}for(;n.length<t;)n+=xn[randomBytes(1)[0]%62];return n}function _t(t){return `${t}_${zi(8)}`}function co(t,e){let{createHash:n}=st("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=xn[i%62];return `${t}_${s}`}var Vi=["urgent","high","medium","low"],Ki=["investigating","in-progress","in-review","on-hold","done"],uo="custom:";var Ji=new Set(Vi),Yi=new Set(Ki);function On(t){return typeof t=="string"&&Ji.has(t)}function bn(t){if(typeof t!="string")return false;if(Yi.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(uo))return false;let e=t.slice(uo.length);return e.length>=1&&e.length<=20}function po(t){if(!t)return null;try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function Cn(t){let e=po(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return On(r.priority)&&(o.priority=r.priority),bn(r.state)&&(o.state=r.state),o}function go(t,e){let n=po(t)??{},r={...Cn(t)};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 n.threadTitle:n.threadTitle=r,Object.keys(n).length===0?null:JSON.stringify(n)}var ta="regeneration_replaced";var na="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var ra="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Pn=class extends p{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=o;}},It=class extends Pn{},Ln=class extends p{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},oa=new Set(dr),sa=new Set(ar),ia=new Set(lr),aa=new Set(cr),da=50,ho=100,mo=280,_o=40,la=new Set(ur),Gt=["queued","running"],ca=["success","completed","done","failed","error"];function Dn(t){return la.has(t)}function D(t){throw new p("VALIDATION",t)}function pe(t){throw new p("NOT_FOUND",t)}function w(t,e){(typeof t!="string"||t.trim().length===0)&&D(`${e} is required`);}function Tt(t={}){let e=t.actor??t,n=e.actorType??"system";return oa.has(n)||D(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&D("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function ua(t){w(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&w(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&D("title must not be empty"),t.title.length>120&&D("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!On(t.priority)&&D(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!bn(t.state)&&D(`invalid state: ${String(t.state)}`);}function pa(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&D("beforeSeq and afterSeq cannot be used together");for(let[n,r]of [["beforeSeq",t.beforeSeq],["afterSeq",t.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&D(`${n} must be a non-negative integer`);let e=t.limit??da;return (!Number.isInteger(e)||e<1||e>ho)&&D(`limit must be between 1 and ${ho}`),e}function Mn(t){typeof t!="string"&&D("text is required");let e=t.trim();return e.length===0&&D("text must not be empty"),e.length>mo&&D(`text must be at most ${mo} characters`),e}function De(t,e){return w(t??"",e),t}function $n(t){aa.has(t)||D(`invalid highlight kind: ${String(t)}`);}function ga(t){ia.has(t)||D(`invalid highlight source: ${String(t)}`);}function fa(t){w(t.threadId,"threadId"),w(t.workspaceId,"workspaceId");let e=t.source??"manual";ga(e),$n(t.kind);let n=Mn(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let u=t.taskId??(r&&o&&r===o?r:void 0),g=De(u,"taskId");return (r!==g||o!==g)&&D("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:g,coversToTaskId:g,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=De(r,"coversFromTaskId"),i=De(o,"coversToTaskId"),a=t.sourceTaskId??s,l=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return De(a??void 0,"sourceTaskId"),De(l??void 0,"detectorVersion"),De(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:a,detectorVersion:l,contentFingerprint:c}}function ha(t,e){(!t||typeof t!="object")&&D(`candidates[${e}] is required`),$n(t.kind);let n=Mn(t.text),r=De(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=De(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=De(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||co("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return w(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function ma(t){Array.isArray(t)||D("candidates must be an array"),t.length>_o&&D(`candidates must contain at most ${_o} items`);let e=new Map;for(let[n,r]of t.entries()){let o=ha(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function Rt(t){let e=Cn(t.metadata);return {threadId:t.id,workspaceId:t.workspace_id,title:t.title,priority:e.priority??null,state:e.state??null,metadata:t.metadata,titleLocked:t.title_locked===1,updatedAt:t.updated_at}}function _a(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&D("event payload must be a JSON object"),e}catch(e){throw new p("VALIDATION","event payload must be JSON serializable",e)}}function yt(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${C.seq}), 0)`}).from(C).where(eq(C.thread_id,e)).get()?.maxSeq??0}function wt(t,e){return !!t.select({id:C.id}).from(C).where(eq(C.thread_id,e)).limit(1).get()}function Ke(t,e){sa.has(e.type)||D(`invalid thread event type: ${String(e.type)}`);let n=_t("the");t.insert(C).values({id:n,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:_a(e.payload),created_at:e.createdAt}).run();let r=t.select().from(C).where(eq(C.id,n)).get();if(!r)throw new p("DB_ERROR","Thread event insert did not return a row");return r}function Et(t,e,n,r,o){let s=Rt(e);Ke(t,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function zt(t){return {highlightId:t.id,source:t.source,kind:t.kind,status:t.status,coversFromTaskId:t.covers_from_task_id,coversToTaskId:t.covers_to_task_id,revision:t.revision,...t.dismissed_at===null?{}:{dismissedAt:t.dismissed_at}}}function Wt(t,e,n,r,o,s,i){let a=o==="thread.highlight.created"?zt(e):{before:i?zt({...e,...i,id:e.id}):void 0,after:zt(e)};return Ke(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.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:a})}function ka(t,e,n,r,o,s){return Ke(t,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:zt(e),...s??{}}})}var Vt=class extends ne{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 n=this.resolveDbPath();if(!e&&!existsSync(n))throw new p("NOT_FOUND","Database not found");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=eq(f.id,n),s=r===void 0?o:r===null?and(o,isNull(f.workspace_id)):and(o,eq(f.workspace_id,r));return e.select().from(f).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(S).where(eq(S.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(w(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:f.workspace_id}).from(f).where(eq(f.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(w(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?Rt(o):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){ua(e);let n=Tt(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||pe(`Thread ${e.threadId} not found`);let a=Rt(i),l=e.title!==void 0,c=l&&e.title!==a.title,u=l&&i.title_locked!==1,g=e.priority!==void 0&&e.priority!==a.priority,h=e.state!==void 0&&e.state!==a.state,m=c||g||h;if(!m&&!u)return a;let b=i.metadata;(g||h)&&(b=go(i.metadata,{priority:e.priority,state:e.state}));let v={};if(m&&(v.metadata=b,v.updated_at=r),c&&(v.title=e.title),l&&(v.title_locked=1),s.update(f).set(v).where(e.workspaceId===void 0?eq(f.id,e.threadId):e.workspaceId===null?and(eq(f.id,e.threadId),isNull(f.workspace_id)):and(eq(f.id,e.threadId),eq(f.workspace_id,e.workspaceId))).run(),!m){let B={...i,title_locked:1};return Rt(B)}let A=yt(s,i.id)+1;wt(s,i.id)||(Et(s,i,n,r,A),A+=1),c&&(Ke(s,{threadId:i.id,seq:A,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.title,after:e.title}}),A+=1),g&&(Ke(s,{threadId:i.id,seq:A,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.priority,after:e.priority}}),A+=1),h&&Ke(s,{threadId:i.id,seq:A,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.state,after:e.state}});let H={...i,title:c?e.title:i.title,metadata:b,title_locked:l?1:i.title_locked,updated_at:r};return Rt(H)},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(w(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:sql`COALESCE(MAX(${C.seq}), 0)`}).from(C).where(eq(C.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(w(e,"threadId"),w(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:d.id,prompt:d.prompt,result:d.result,status:d.status,startedAt:d.started_at,completedAt:d.completed_at}).from(d).where(and(eq(d.thread_id,e),eq(d.workspace_id,n),inArray(d.status,ca),or(isNull(d.parent_task_id),eq(d.parent_task_id,"")),sql`${d.result} IS NOT NULL AND length(trim(${d.result})) > 0`)).orderBy(asc(d.started_at),asc(d.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){w(e.threadId,"threadId"),w(e.workspaceId,"workspaceId"),w(e.requestId,"requestId"),w(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&w(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||pe(`Thread ${e.threadId} not found`);let i=o.select().from(S).where(and(eq(S.thread_id,s.id),eq(S.request_id,e.requestId))).orderBy(desc(S.requested_at),desc(S.id)).limit(1).get();if(i)return {run:i,created:!1};let a=o.select().from(S).where(and(eq(S.thread_id,s.id),inArray(S.status,Gt))).orderBy(asc(S.requested_at),asc(S.id)).limit(1).get();if(a)throw new Ln(a);let l=e.runId??_t("thr");o.insert(S).values({id:l,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let c=o.select().from(S).where(eq(S.id,l)).get();if(!c)throw new p("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(w(e,"runId"),n!==void 0&&w(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(w(e,"threadId"),w(n,"workspaceId"),w(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.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(s){throw s instanceof p?s:new p("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){w(e,"runId"),n!==void 0&&w(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,n);if(i||pe(`Highlight regeneration run ${e} not found`),Dn(i.status)||D(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(S).set({status:"running",started_at:r}).where(and(eq(S.id,i.id),eq(S.status,"queued"))).run();let a=s.select().from(S).where(eq(S.id,i.id)).get();if(!a)throw new p("DB_ERROR","Highlight regeneration run start did not return a row");return a},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){w(e.runId,"runId"),w(e.errorCode,"errorCode"),e.workspaceId!==void 0&&w(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||pe(`Highlight regeneration run ${e.runId} not found`),Dn(s.status)||D(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(S).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(S.id,s.id),inArray(S.status,Gt))).run();let i=o.select().from(S).where(eq(S.id,s.id)).get();if(!i)throw new p("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=na){w(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(S).set({status:"failed",completed_at:n,error_code:e}).where(inArray(S.status,Gt)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){w(e.runId,"runId"),w(e.threadId,"threadId"),w(e.workspaceId,"workspaceId"),w(e.detectorVersion,"detectorVersion");let n=ma(e.candidates),r=Tt(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let a=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!a||a.thread_id!==e.threadId)&&pe(`Highlight regeneration run ${e.runId} not found`),Dn(a.status)||D(`invalid highlight regeneration status: ${a.status}`),a.status==="failed")throw new p("CONFLICT","Highlight regeneration run has already failed");if(a.status==="completed")return {run:a,deletedCount:0,createdCount:0,previousAutoCount:a.previous_auto_count??0,newAutoCount:a.new_auto_count??0};s=!0;let l=this.findThread(i,e.threadId,e.workspaceId);l||pe(`Thread ${e.threadId} not found`),a.detector_version!==e.detectorVersion&&D("detectorVersion does not match the regeneration run");let c=i.select().from(E).where(eq(E.thread_id,l.id)).orderBy(asc(E.created_at),asc(E.id)).all(),u=new Set(n.map(O=>O.contentFingerprint)),g=c.filter(O=>O.source==="auto"&&O.status==="active"&&O.revision===0&&!u.has(O.content_fingerprint??"")),h=c.filter(O=>O.source==="auto"&&O.status==="active").length,m=new Set(c.filter(O=>!g.includes(O)&&O.content_fingerprint).map(O=>O.content_fingerprint)),b=n.filter(O=>!m.has(O.contentFingerprint)),v=new Date().toISOString(),A=yt(i,l.id)+1;wt(i,l.id)||(Et(i,l,r,v,A),A+=1);for(let O of g)i.delete(E).where(eq(E.id,O.id)).run(),ka(i,O,r,v,A,{runId:e.runId,reason:ta}),A+=1;let H=0,B=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let O of b){let Fn=_t("thl");i.insert(E).values({id:Fn,thread_id:l.id,source:"auto",kind:O.kind,status:"active",text:O.text,covers_from_task_id:O.coversFromTaskId,covers_to_task_id:O.coversToTaskId,revision:0,created_at:v,updated_at:v,agent_id:B,source_task_id:O.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:O.contentFingerprint,dismissed_at:null}).run();let qn=i.select().from(E).where(eq(E.id,Fn)).get();if(!qn)throw new p("DB_ERROR","Regenerated highlight insert did not return a row");Wt(i,qn,r,v,"thread.highlight.created",A),A+=1,H+=1;}let te=i.select().from(E).where(eq(E.thread_id,l.id)).all().filter(O=>O.source==="auto"&&O.status==="active").length;Ke(i,{threadId:l.id,seq:A,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:v,payload:{runId:a.id,detectorVersion:e.detectorVersion,previousAutoCount:h,newAutoCount:te,deletedCount:g.length,createdCount:H}}),i.update(S).set({status:"completed",started_at:a.started_at??v,completed_at:v,error_code:null,previous_auto_count:h,new_auto_count:te}).where(and(eq(S.id,a.id),inArray(S.status,Gt))).run();let Pe=i.select().from(S).where(eq(S.id,a.id)).get();if(!Pe)throw new p("DB_ERROR","Highlight regeneration completion did not return a row");return {run:Pe,deletedCount:g.length,createdCount:H,previousAutoCount:h,newAutoCount:te}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:ra});}catch{}throw i instanceof p?i:new p("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;w(o.threadId,"threadId"),w(o.workspaceId,"workspaceId");let s=pa(o);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let a=i.db.select({maxSeq:sql`COALESCE(MAX(${C.seq}), 0)`}).from(C).where(eq(C.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(C).where(and(eq(C.thread_id,o.threadId),lt(C.seq,o.beforeSeq))).orderBy(desc(C.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(C).where(and(eq(C.thread_id,o.threadId),sql`${C.seq} > ${o.afterSeq}`)).orderBy(asc(C.seq)).limit(s+1).all():l=i.db.select().from(C).where(eq(C.thread_id,o.threadId)).orderBy(desc(C.seq)).limit(s+1).all().reverse();let c=l.length>s,u=o.afterSeq!==void 0?l.slice(0,s):c?l.slice(1):l,g=!1,h=u[0];return h&&(g=!!i.db.select({id:C.id}).from(C).where(and(eq(C.thread_id,o.threadId),lt(C.seq,h.seq))).limit(1).get()),{items:u,latestSeq:a,hasMoreOlder:g}}catch(a){throw a instanceof p?a:new p("DB_ERROR","Failed to list thread timeline",a)}finally{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=fa(e),r=Tt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,e.threadId,e.workspaceId);if(a||pe(`Thread ${e.threadId} not found`),n.source==="auto"){let h=i.select().from(E).where(and(eq(E.thread_id,e.threadId),eq(E.source_task_id,n.sourceTaskId),eq(E.detector_version,n.detectorVersion),eq(E.content_fingerprint,n.contentFingerprint))).orderBy(asc(E.created_at),asc(E.id)).limit(1).get();if(h)return h}let l=e.id??_t("thl"),c={id:l,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(E).values(c).run();let u=i.select().from(E).where(eq(E.id,l)).get();if(!u)throw new p("DB_ERROR","Highlight insert did not return a row");let g=yt(i,a.id)+1;return wt(i,a.id)||(Et(i,a,r,o,g),g+=1),Wt(i,u,r,o,"thread.highlight.created",g),u},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){w(e.threadId,"threadId"),w(e.workspaceId,"workspaceId"),w(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&D("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&D("highlight update requires at least one field"),e.kind!==void 0&&$n(e.kind);let n=e.text===void 0?void 0:Mn(e.text),r=Tt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let a=this.findThread(i,e.threadId,e.workspaceId);a||pe(`Thread ${e.threadId} not found`);let l=i.select().from(E).where(and(eq(E.id,e.highlightId),eq(E.thread_id,a.id))).limit(1).get();if(l||pe(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new It(a.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new It(a.id,l.id,e.expectedRevision,l.revision);let c=e.kind??l.kind,u=n??l.text,g=e.coversFromTaskId??l.covers_from_task_id,h=e.coversToTaskId??l.covers_to_task_id;(!u||g.length===0||h.length===0)&&D("highlight projection is incomplete");let m=c!==l.kind||u!==l.text||g!==l.covers_from_task_id||h!==l.covers_to_task_id,b=r.actorType==="user"&&l.source==="auto"&&m?"manual":l.source;if(!(m||b!==l.source))return l;let A=l.revision+1;i.update(E).set({source:b,kind:c,text:u,covers_from_task_id:g,covers_to_task_id:h,revision:A,updated_at:o}).where(and(eq(E.id,l.id),eq(E.revision,l.revision))).run();let H=i.select().from(E).where(eq(E.id,l.id)).get();if(!H)throw new p("DB_ERROR","Highlight update did not return a row");let B=yt(i,a.id)+1;return wt(i,a.id)||(Et(i,a,r,o,B),B+=1),Wt(i,H,r,o,"thread.highlight.updated",B,l),H},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){w(e.threadId,"threadId"),w(e.workspaceId,"workspaceId"),w(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&D("expectedRevision must be a non-negative integer");let n=Tt(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||pe(`Thread ${e.threadId} not found`);let a=s.select().from(E).where(and(eq(E.id,e.highlightId),eq(E.thread_id,i.id))).limit(1).get();if(a||pe(`Highlight ${e.highlightId} not found`),a.revision!==e.expectedRevision)throw new It(i.id,a.id,e.expectedRevision,a.revision);if(a.status==="dismissed")return a;let l=a.revision+1;s.update(E).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(and(eq(E.id,a.id),eq(E.revision,a.revision))).run();let c=s.select().from(E).where(eq(E.id,a.id)).get();if(!c)throw new p("DB_ERROR","Highlight dismissal did not return a row");let u=yt(s,i.id)+1;return wt(s,i.id)||(Et(s,i,n,r,u),u+=1),Wt(s,c,n,r,"thread.highlight.deleted",u,a),c},{behavior:"immediate"})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(w(e,"threadId"),w(n,"workspaceId"),r.taskId!==void 0&&w(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&w(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&w(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let i=o.db.select().from(E).where(and(eq(E.thread_id,e),eq(E.status,"active"))).orderBy(asc(E.created_at),asc(E.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let a=o.db.all(sql`
|
|
359
371
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
360
372
|
ORDER BY started_at ASC, id ASC
|
|
361
|
-
`),
|
|
362
|
-
`).filter(
|
|
363
|
-
`).trim()}function
|
|
364
|
-
`):
|
|
365
|
-
`)[0].slice(0,200)),
|
|
373
|
+
`),l=new Map(a.map((h,m)=>[h.id,m])),c=r.taskId===void 0?void 0:l.get(r.taskId),u=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),g=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(h=>{let m=l.get(h.covers_from_task_id),b=l.get(h.covers_to_task_id);if(m===void 0||b===void 0)return !1;let v=Math.min(m,b),A=Math.max(m,b);return !(c!==void 0&&(c<v||c>A)||u!==void 0&&A<u||g!==void 0&&v>g)})}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};var j=class extends p{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},To="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Sa(){let t=randomBytes(16),e="";for(let n of t)e+=To[n%To.length];return e.slice(0,12)}function yo(){return `c_${Sa()}`}function xa(t){return typeof t=="string"&&dn.includes(t)}function Oa(t){return typeof t=="string"&&ln.includes(t)}function vt(t){if(!xa(t))throw new j("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function wo(t){if(!Oa(t))throw new j("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function Eo(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new j("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function At(t){if(typeof t!="string"||t.trim().length===0)throw new j("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Hn(t){if(typeof t!="string"||t.trim().length===0)throw new j("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function ot(t,e){return and(eq(T.code_group,t),or(isNull(T.workspace_id),eq(T.workspace_id,e)))}var Jt=class extends ne{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 n=this.resolveDbPath();if(!e&&!existsSync(n))throw new p("NOT_FOUND","Database not found");e&&mkdirSync(dirname(n),{recursive:true});let r=L(n);if(e)try{ge(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(vt(e),At(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(T).where(and(ot(e,n),eq(T.is_archived,0))).orderBy(asc(T.sort_order),asc(T.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(vt(e),At(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(T).where(ot(e,n)).orderBy(asc(T.sort_order),asc(T.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}resolve(e,n){if(vt(e),Hn(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(T).where(and(eq(T.code_group,e),eq(T.code,n))).limit(1).get()??null}catch(o){throw new p("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){At(e.workspaceId);let n=Eo(e.name);wo(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:T.code}).from(T).where(and(ot("THREAD_STATE",e.workspaceId),eq(T.is_archived,0),eq(T.code_name,n))).limit(1).get())throw new j("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:sql`max(${T.sort_order})`}).from(T).where(ot("THREAD_STATE",e.workspaceId)).get(),a=new Date().toISOString(),l=yo();for(;o.select({code:T.code}).from(T).where(and(eq(T.code_group,"THREAD_STATE"),eq(T.code,l))).limit(1).get();)l=yo();o.insert(T).values({code_group:"THREAD_STATE",code:l,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:a,updated_at:a}).run();let c=o.select().from(T).where(and(eq(T.code_group,"THREAD_STATE"),eq(T.code,l))).limit(1).get();if(!c)throw new p("DB_ERROR","Created common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(vt(e.group),Hn(e.code),At(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 n=e.name===void 0||e.name===null?e.name:Eo(e.name);e.color!==void 0&&wo(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(T).where(and(eq(T.code_group,e.group),eq(T.code,e.code))).limit(1).get();if(!s)throw new j("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),n===null&&s.is_builtin!==1)throw new j("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let l=and(ot(e.group,e.workspaceId),eq(T.is_archived,0));if(o.select({code:T.code}).from(T).where(and(l,eq(T.code_name,n),sql`${T.code} <> ${e.code}`)).limit(1).get())throw new j("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=n??null),e.color!==void 0&&(i.color=e.color),o.update(T).set(i).where(and(eq(T.code_group,e.group),eq(T.code,e.code))).run();let a=o.select().from(T).where(and(eq(T.code_group,e.group),eq(T.code,e.code))).limit(1).get();if(!a)throw new p("DB_ERROR","Updated common code could not be read back");return a},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(vt(e),Hn(n),At(r),typeof o!="boolean")throw new j("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let a=i.select().from(T).where(and(eq(T.code_group,e),eq(T.code,n))).limit(1).get();if(!a)throw new j("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(a.is_builtin===1)throw new j("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(a,r),!o&&a.code_name!==null&&i.select({code:T.code}).from(T).where(and(ot(e,r),eq(T.is_archived,0),eq(T.code_name,a.code_name),ne$1(T.code,n))).limit(1).get())throw new j("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${a.code_name}`);i.update(T).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(and(eq(T.code_group,e),eq(T.code,n))).run();let l=i.select().from(T).where(and(eq(T.code_group,e),eq(T.code,n))).limit(1).get();if(!l)throw new p("DB_ERROR","Archived common code could not be read back");return l},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new j("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function Na(t){return t.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
374
|
+
`).filter(o=>!(o.startsWith("Loaded ")&&o.includes("layouts from")||o.includes("[dotenv@")||o.includes("[Nest]")&&o.includes("DEBUG")||o.startsWith("Registered custom layout:")||o.startsWith("Updated custom layout:"))).join(`
|
|
375
|
+
`).trim()}function Da(t){if(!t)return "";let e=t;try{let n=JSON.parse(e);Array.isArray(n)?e=n.filter(r=>r?.type==="text"&&r?.text).map(r=>r.text).join(`
|
|
376
|
+
`):n&&typeof n=="object"&&n.result!==void 0&&(e=n.result||"");}catch{e=Na(e);}return e}var Yt=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new jt({dbPath:this.dbPath})}getThreadHistoryRepo(){return new Vt({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r){let o=this.getThreadRepo(),s=o.findThreadById(e);if(s){if(s.platform!==n)throw new Error(`Thread '${e}' already exists with platform '${s.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return {created:false}}return o.ensureThread(e,n,r),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,o=this.getThreadRepo(),s=o.findThreadById(e),i=o.findTopLevelTasks(e,void 0,r),a=new Set(["queued","cancelled"]);i=i.filter(g=>(!g.status||!a.has(g.status))&&(!n?.currentTraceId||g.trace_id!==n.currentTraceId));let l=s?.platform??"cli",c=this.rowsToMessages(i),u=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,s?.workspace_id??null);return {threadId:e,platform:l,messages:c,...u?{highlights:u}:{},metadata:{title:s?.title??void 0,firstMessage:s?.first_message??void 0,lastMessage:s?.last_message??void 0,messageCount:s?.message_count??0,updatedAt:s?.updated_at?new Date(s.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new Jt({dbPath:this.dbPath}),o=(s,i)=>{try{return r.resolve(s,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:o("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:o("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,o){let{firstMessage:s}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:s}}async saveAssistantMessage(e,n,r,o){return this.getThreadRepo().saveAssistantMessage(e,n),{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,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(o=>typeof o.text=="string"&&o.text.length>0).map(o=>({id:o.id,text:o.text,kind:o.kind,source:o.source,coversFromTaskId:o.covers_from_task_id,coversToTaskId:o.covers_to_task_id,createdAt:o.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.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 o=Da(r.result),s=this.normalizeStatus(r.status);if(o||s==="running"||s==="failed"){let i={agent_id:r.agent_id,task_id:r.id};s&&(i.status=s),s==="failed"&&r.error&&(i.reason=r.error.split(`
|
|
377
|
+
`)[0].slice(0,200)),n.push({id:`${r.id}-assistant`,text:o,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:i});}}return n}};var Un=class extends Le{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Yt(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,n,r,o){}async afterAssistantMessage(e,n,r){}attach(e){this.unsubStart=e.on("task:start",async n=>{if(!n.threadId)return;let r=n.platform??"cli";try{let o=await this._provider.ensureThread(n.threadId,r,n.workspaceId),s=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,s.id,o.created||s.firstMessage,n);}catch{}}),this.unsubEnd=e.on("task:end",async n=>{if(!n.result)return;let r=n.metadata?.threadId;if(!r)return;let o=n.agentRef?.replace(/^@/,"")??"";try{let{id:s}=await this._provider.saveAssistantMessage(r,n.result,o);await this.afterAssistantMessage(r,s,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};export{Un as ConversationPlugin,Qt as FileLoggerPlugin,Sn as SqliteTracingPlugin};
|