@crewx/sdk 0.9.0-rc.86 → 0.9.0-rc.88
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/config/models.generated.d.ts +4 -0
- package/dist/esm/index.js +112 -105
- package/dist/esm/plugins/index.js +54 -53
- package/dist/esm/testing/index.js +1 -1
- package/dist/index.browser.d.ts +2 -0
- package/dist/index.browser.js +3 -3
- package/dist/index.d.ts +5 -2
- package/dist/index.js +113 -106
- package/dist/plugins/index.js +57 -56
- package/dist/provider/cli/adapter.types.d.ts +1 -0
- package/dist/provider/cli/protocol-envelope.d.ts +2 -0
- package/dist/testing/index.js +1 -1
- package/dist/utils/crewx-executable.d.ts +19 -1
- package/package.json +1 -1
- package/templates/agents/default.yaml +5 -5
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as Ie from'path';import Ie__default,{join,dirname}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,readFileSync}from'fs';import Jo,{homedir}from'os';import {createHash,randomUUID,randomBytes}from'crypto';import {sql,eq,desc,and,isNull,lt as lt$1,or,notLike,asc,like,inArray,gte,isNotNull,ne as ne$1}from'drizzle-orm';import {sqliteTable,integer,text,real,index,check,uniqueIndex,unique,primaryKey}from'drizzle-orm/sqlite-core';var ct=(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 Uo=()=>fileURLToPath(import.meta.url),Fo=()=>Ie__default.dirname(Uo()),_=Fo();var $e=class{detach(e){}};function Vn(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 rn(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var on=class extends $e{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=Vn(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
3
|
Mode: ${n.mode}
|
|
4
4
|
Agent: ${n.agentRef}
|
|
5
|
-
Started: ${
|
|
5
|
+
Started: ${rn(n.timestamp)}
|
|
6
6
|
Message: ${n.message}
|
|
7
7
|
|
|
8
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=
|
|
9
|
+
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=rn(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
|
|
10
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
|
|
11
|
+
`;appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};function Wo(t){let e=Ie.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 Xn(t){let e=Wo(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(Jo.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 Yo=32*1024*1024;function M(t){let e=ct("better-sqlite3"),{drizzle:n}=ct("drizzle-orm/better-sqlite3"),r=new e(t);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Yo}`),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 Qn=new Set,Xo={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 sn(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Qo(t,e){if(e>0||!sn(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(Xo))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var Zo={"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 es(t,e,n){if(!sn(t,"__drizzle_migrations")||!sn(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(Ie__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=Zo[i.tag];if(!a)continue;let l=Ie__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,S]of Object.entries(a))h.has(m)||(t.run(`ALTER TABLE tasks ADD COLUMN ${m} ${S}`),h.add(m));}}function ts(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(Ie__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=Ie__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(j=>j.name===A))&&t.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function ns(t){let{migrate:e}=ct("drizzle-orm/better-sqlite3/migrator"),{sql:n}=ct("drizzle-orm"),r=[Ie__default.join(_,"../migrations"),Ie__default.join(_,"migrations"),Ie__default.join(_,"../../../../drizzle/migrations"),Ie__default.join(process.cwd(),"drizzle/migrations")],o=r.find(c=>existsSync(Ie__default.join(c,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
12
12
|
${r.join(`
|
|
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),Bo(t,i),s?.cnt&&(Wo(t,o,n),Go(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){Kn.has(e)||(zo(t),Kn.add(e));}var Xe=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(),starred:integer("starred").notNull().default(0)});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),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));var ns="json_extract(metadata, '$.threadTitle.state')",rs="json_extract(metadata, '$.threadTitle.priority')",f=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Xe.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(ns)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(rs))}));var is=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(()=>is.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`(
|
|
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),Qo(t,i),s?.cnt&&(ts(t,o,n),es(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 fe(t,e){Qn.has(e)||(ns(t),Qn.add(e));}var Qe=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(),starred:integer("starred").notNull().default(0)});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 he=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),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));var ps="json_extract(metadata, '$.threadTitle.state')",gs="json_extract(metadata, '$.threadTitle.priority')",f=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Qe.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(ps)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(gs))}));var ms=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(()=>ms.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
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
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 dr=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(()=>dr.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(()=>dr.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 cn=["THREAD_STATE","THREAD_PRIORITY"],un=["gray","blue","violet","green","amber","orange","red","pink"],k=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 lr=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],cr=["user","agent","system"],ur=["auto","manual"],pr=["decision","judgment","issue","result","pivot"];var gr=["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 fr(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 Tr(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 _r(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)=>Tr(r,o))}catch(r){throw r instanceof p?new p("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function yr(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 kr(t){return {taskId:t.id,source:yr(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function $s(t){if(!Number.isInteger(t)||t<0)throw new p("VALIDATION","Task log tail limit must be a non-negative integer")}var $t=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=M(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)=>Tr(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=yr(a);if(l==="blob"){let h=_r(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?kr(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 $s(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=kr(s);if(i.source==="blob"){let u=_r(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 fn=40,Oe="2026-05-09",js="0.8.9-rc.13",be=10,Ce=parseInt(js.split("rc.")[1]);function wr(){let t=sql`
|
|
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 pr=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(()=>pr.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(()=>pr.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 fn=["THREAD_STATE","THREAD_PRIORITY"],hn=["gray","blue","violet","green","amber","orange","red","pink"],k=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 gr=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],fr=["user","agent","system"],hr=["auto","manual"],mr=["decision","judgment","issue","result","pivot"];var _r=["queued","running","completed","failed"],b=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)})),x=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 kr(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 Rr(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 wr(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)=>Rr(r,o))}catch(r){throw r instanceof p?new p("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Ir(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 Er(t){return {taskId:t.id,source:Ir(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Vs(t){if(!Number.isInteger(t)||t<0)throw new p("VALIDATION","Task log tail limit must be a non-negative integer")}var Ht=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=M(n);if(e)try{fe(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)=>Rr(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=Ir(a);if(l==="blob"){let h=wr(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(he).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?Er(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 Vs(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=Er(s);if(i.source==="blob"){let u=wr(e,s.logs);return {...i,entries:n===void 0?u:u.slice(Math.max(0,u.length-n))}}let a=o.select({seq:he.seq,timestamp:he.timestamp,level:he.level,message:he.message}).from(he).where(eq(he.task_id,e)).orderBy(n===void 0?asc(he.seq):desc(he.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 kn=40,Ce="2026-05-09",Zs="0.8.9-rc.13",be=10,Ne=parseInt(Zs.split("rc.")[1]);function vr(){let t=sql`
|
|
18
18
|
CASE
|
|
19
19
|
WHEN ${d.model} LIKE 'claude-%' OR ${d.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
20
20
|
WHEN ${d.model} LIKE 'gpt-%' OR ${d.model} LIKE 'codex-%' THEN 'codex'
|
|
@@ -43,14 +43,14 @@ ${r.join(`
|
|
|
43
43
|
WHEN trim(${o}) = '' THEN 'unknown'
|
|
44
44
|
ELSE ${o}
|
|
45
45
|
END
|
|
46
|
-
`}var
|
|
46
|
+
`}var ei=new Set(["workflow","mcp"]),Tn="usageByEpoch";function yn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ar(t){if(!t)return {};try{let e=JSON.parse(t);return yn(e)?{...e}:{}}catch{return {}}}function se(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function xr(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function ti(t){return {inputTokens:se(t.inputTokens??0),outputTokens:se(t.outputTokens??0),cachedInputTokens:se(t.cachedInputTokens??0),costUsd:se(t.costUsd??0)}}function ni(t){if(yn(t))return {inputTokens:se(t.inputTokens),outputTokens:se(t.outputTokens),cachedInputTokens:se(t.cachedInputTokens),costUsd:se(t.costUsd)}}function ri(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=ni(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function oi(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}var Sr=600*1e3,Ft=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 Ht({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=M(n);if(e)try{fe(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 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=
|
|
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=xr(o.run_epoch),i=xr(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=Ar(o.metadata);let g=yn(u[Tn])?{...u[Tn]}:{};g[String(i)]=ti(e),u[Tn]=g;let h=ri(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??=Ar(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?oi(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(ei.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>=Sr&&(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=Sr){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$1(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=M(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=M(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`
|
|
54
54
|
SELECT
|
|
55
55
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
56
56
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -71,7 +71,7 @@ ${r.join(`
|
|
|
71
71
|
FROM tasks
|
|
72
72
|
GROUP BY workspace_id
|
|
73
73
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
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=M(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=M(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=M(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=M(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
|
|
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=M(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=M(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=M(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=M(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 S of g)a(S.thread_id,S);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 S of m){let v=this.extractThreadIdFromCommand(S.command);!v||!o.has(v)||a(v,S);}}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$1(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`
|
|
75
75
|
SELECT
|
|
76
76
|
t.agent_id,
|
|
77
77
|
t.workspace_id,
|
|
@@ -79,11 +79,11 @@ ${r.join(`
|
|
|
79
79
|
COALESCE(SUM(
|
|
80
80
|
COALESCE(t.input_tokens, 0)
|
|
81
81
|
+ CASE
|
|
82
|
-
WHEN t.started_at >= ${
|
|
82
|
+
WHEN t.started_at >= ${Ce}
|
|
83
83
|
AND (
|
|
84
84
|
t.crewx_version IS NULL
|
|
85
85
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
86
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${
|
|
86
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ne})
|
|
87
87
|
)
|
|
88
88
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
89
89
|
ELSE 0
|
|
@@ -102,11 +102,11 @@ ${r.join(`
|
|
|
102
102
|
COALESCE(SUM(
|
|
103
103
|
COALESCE(t.input_tokens, 0)
|
|
104
104
|
+ CASE
|
|
105
|
-
WHEN t.started_at >= ${
|
|
105
|
+
WHEN t.started_at >= ${Ce}
|
|
106
106
|
AND (
|
|
107
107
|
t.crewx_version IS NULL
|
|
108
108
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
109
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${
|
|
109
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ne})
|
|
110
110
|
)
|
|
111
111
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
112
112
|
ELSE 0
|
|
@@ -122,11 +122,11 @@ ${r.join(`
|
|
|
122
122
|
COALESCE(SUM(
|
|
123
123
|
COALESCE(t.input_tokens, 0)
|
|
124
124
|
+ CASE
|
|
125
|
-
WHEN t.started_at >= ${
|
|
125
|
+
WHEN t.started_at >= ${Ce}
|
|
126
126
|
AND (
|
|
127
127
|
t.crewx_version IS NULL
|
|
128
128
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
129
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${
|
|
129
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ne})
|
|
130
130
|
)
|
|
131
131
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
132
132
|
ELSE 0
|
|
@@ -144,11 +144,11 @@ ${r.join(`
|
|
|
144
144
|
COALESCE(SUM(
|
|
145
145
|
COALESCE(t.input_tokens, 0)
|
|
146
146
|
+ CASE
|
|
147
|
-
WHEN t.started_at >= ${
|
|
147
|
+
WHEN t.started_at >= ${Ce}
|
|
148
148
|
AND (
|
|
149
149
|
t.crewx_version IS NULL
|
|
150
150
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
151
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${
|
|
151
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ne})
|
|
152
152
|
)
|
|
153
153
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
154
154
|
ELSE 0
|
|
@@ -163,11 +163,11 @@ ${r.join(`
|
|
|
163
163
|
COALESCE(SUM(
|
|
164
164
|
COALESCE(t.input_tokens, 0)
|
|
165
165
|
+ CASE
|
|
166
|
-
WHEN t.started_at >= ${
|
|
166
|
+
WHEN t.started_at >= ${Ce}
|
|
167
167
|
AND (
|
|
168
168
|
t.crewx_version IS NULL
|
|
169
169
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
170
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${
|
|
170
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ne})
|
|
171
171
|
)
|
|
172
172
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
173
173
|
ELSE 0
|
|
@@ -190,11 +190,11 @@ ${r.join(`
|
|
|
190
190
|
COALESCE(SUM(
|
|
191
191
|
COALESCE(t.input_tokens, 0)
|
|
192
192
|
+ CASE
|
|
193
|
-
WHEN t.started_at >= ${
|
|
193
|
+
WHEN t.started_at >= ${Ce}
|
|
194
194
|
AND (
|
|
195
195
|
t.crewx_version IS NULL
|
|
196
196
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
197
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${
|
|
197
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${be}) AS INTEGER) < ${Ne})
|
|
198
198
|
)
|
|
199
199
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
200
200
|
ELSE 0
|
|
@@ -209,14 +209,14 @@ ${r.join(`
|
|
|
209
209
|
AND t.started_at < ${n}
|
|
210
210
|
GROUP BY date(t.started_at), t.agent_id
|
|
211
211
|
ORDER BY date(t.started_at) ASC
|
|
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=M(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=
|
|
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=M(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=vr(),i=sql`
|
|
213
213
|
COALESCE(${d.input_tokens}, 0)
|
|
214
214
|
+ CASE
|
|
215
|
-
WHEN ${d.started_at} >= ${
|
|
215
|
+
WHEN ${d.started_at} >= ${Ce}
|
|
216
216
|
AND (
|
|
217
217
|
${d.crewx_version} IS NULL
|
|
218
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) < ${
|
|
219
|
+
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${be}) AS INTEGER) < ${Ne})
|
|
220
220
|
)
|
|
221
221
|
THEN COALESCE(${d.cached_input_tokens}, 0)
|
|
222
222
|
ELSE 0
|
|
@@ -235,14 +235,14 @@ ${r.join(`
|
|
|
235
235
|
${a}
|
|
236
236
|
GROUP BY ${s}
|
|
237
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=
|
|
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=vr(),i=sql`
|
|
239
239
|
COALESCE(${d.input_tokens}, 0)
|
|
240
240
|
+ CASE
|
|
241
|
-
WHEN ${d.started_at} >= ${
|
|
241
|
+
WHEN ${d.started_at} >= ${Ce}
|
|
242
242
|
AND (
|
|
243
243
|
${d.crewx_version} IS NULL
|
|
244
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) < ${
|
|
245
|
+
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${be}) AS INTEGER) < ${Ne})
|
|
246
246
|
)
|
|
247
247
|
THEN COALESCE(${d.cached_input_tokens}, 0)
|
|
248
248
|
ELSE 0
|
|
@@ -261,7 +261,7 @@ ${r.join(`
|
|
|
261
261
|
FROM ${d}
|
|
262
262
|
${a}
|
|
263
263
|
GROUP BY ${d.model}, ${s}
|
|
264
|
-
`),c=new Map;for(let u of l){let g=
|
|
264
|
+
`),c=new Map;for(let u of l){let g=kr(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`
|
|
265
265
|
SELECT
|
|
266
266
|
${d.thread_id} AS thread_id,
|
|
267
267
|
${d.agent_id} AS agent_id,
|
|
@@ -275,11 +275,11 @@ ${r.join(`
|
|
|
275
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
276
|
COALESCE(${d.input_tokens}, 0)
|
|
277
277
|
+ CASE
|
|
278
|
-
WHEN ${d.started_at} >= ${
|
|
278
|
+
WHEN ${d.started_at} >= ${Ce}
|
|
279
279
|
AND (
|
|
280
280
|
${d.crewx_version} IS NULL
|
|
281
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) < ${
|
|
282
|
+
OR (${d.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${d.crewx_version}, ${be}) AS INTEGER) < ${Ne})
|
|
283
283
|
)
|
|
284
284
|
THEN COALESCE(${d.cached_input_tokens}, 0)
|
|
285
285
|
ELSE 0
|
|
@@ -295,26 +295,27 @@ ${r.join(`
|
|
|
295
295
|
${i}
|
|
296
296
|
GROUP BY ${d.caller_agent_id}, ${d.agent_id}
|
|
297
297
|
ORDER BY task_count DESC, ${d.caller_agent_id} ASC, ${d.agent_id} ASC
|
|
298
|
-
LIMIT ${
|
|
299
|
-
`),l=a.length>
|
|
298
|
+
LIMIT ${kn+1}
|
|
299
|
+
`),l=a.length>kn;return {edges:a.slice(0,kn).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$1(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$1(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 De=class extends z{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};function ye(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function we(t,e,n){let r=e.match(/@(\S+)/);return {timestamp:t,type:"agent_call",targetAgent:r?.[1]?.replace(/["']/g,""),toolInput:e,...typeof n=="string"&&n.length>0?{toolUseId:n}:{}}}var Or="[[crewx:delegation-result ",si="[[crewx:delegation-result";var ii=new Set(["schema","taskId","agentId","isError"]);function ai(t){let e=di(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>ci(s.value)),r=li(e);return {result:n.length===1&&n[0].index===r?ui(n[0].line.value):null,resultPreview:fi(e,n),hasReservedLine:n.length>0}}function Pe(t,e){let n=ai(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function di(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
300
300
|
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
301
301
|
`?`\r
|
|
302
|
-
`:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Zs(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function ei(t){return t.trimStart().startsWith(Js)}function ti(t){let e=t.trim();if(!e.startsWith(Ar)||!e.endsWith("]]"))return null;let n=e.slice(Ar.length,-2);if(!n)return null;try{return ni(JSON.parse(n))}catch{return null}}function ni(t){return ri(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function ri(t){if(!si(t)||Object.keys(t).some(r=>!Ys.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?vr(t.taskId)&&vr(t.agentId):t.isError===true}function oi(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function vr(t){return typeof t=="string"&&t.trim().length>0}function si(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}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 _n={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{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-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"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(_n).map(([t,e])=>[t,e.models]));var ii=[{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]"}],ai={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};function kn(t){return ai[t]??t}var di=new Map(ii.map(({baseModelId:t,catalogModelId:e})=>[t,e]));function li(t){return di.get(t)??t}var ci=[{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"}],ui=new Map(ci.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));function Tn(t){if(!t)return {};let e=ui.get(t);return e?{...e}:{model:t}}function yn(t,e){return t==="antigravity"||t==="cli/antigravity"?Tn(e):e===void 0?{}:{model:li(e)}}var pi={};function gi(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Be(t){return Ft(t).models}function Ft(t){return pi[t]??_n[t]??gi()}function ht(t,e){let n=Ft(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=yn(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Sr(t){return Ft(t).modelOverrides}function xr(){return Be("claude")}function Or(){return Be("codex")}function br(){return Be("copilot")}function Cr(){return Be("antigravity")}var fi={auto:"default"};function Nr(t){return fi[t]??t}var hi=new Set(["minimal","low","medium","high","xhigh","max"]);function je(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return hi.has(n)?{model:e[1],effort:e[2]}:{model:t}}return {model:t}}function Dr(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 Lr(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 Pr(t){return t?["-c",`model_reasoning_effort=${t}`]:[]}function Mr(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Nr(t);return e.has(n)?["--permission-mode",n]:[]}function $r(t){return t?new Set(["low","medium","high","xhigh","max"]).has(t)?["--effort",t]:[]:[]}var mi=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);function Hr(t){return t==="default"?[]:t&&mi.has(t)?["--permission-mode",t]:[]}function Ur(t){return t===true?["--always-approve"]:[]}function Fr(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 qr(t){return t?new Set(["low","medium","high","xhigh"]).has(t)?["--effort",t]:[]:[]}function Br(t){if(!t)return [];switch(kn(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function jr(t){return t?new Set(["low","medium","high"]).has(t)?["--effort",t]:[]:[]}function _i(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 ki(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 Ti(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 Gr(t){let e=new Map,n;for(let s of t.split(`
|
|
303
|
-
`))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
|
|
304
|
-
`))if(r.trim())try{let o=JSON.parse(r),s=
|
|
305
|
-
`).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{}
|
|
306
|
-
`);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=
|
|
302
|
+
`:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function li(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function ci(t){return t.trimStart().startsWith(si)}function ui(t){let e=t.trim();if(!e.startsWith(Or)||!e.endsWith("]]"))return null;let n=e.slice(Or.length,-2);if(!n)return null;try{return pi(JSON.parse(n))}catch{return null}}function pi(t){return gi(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function gi(t){if(!hi(t)||Object.keys(t).some(r=>!ii.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?Cr(t.taskId)&&Cr(t.agentId):t.isError===true}function fi(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function Cr(t){return typeof t=="string"&&t.trim().length>0}function hi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ee(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 br=["none","minimal","low","medium","high","xhigh","max","ultra"],qt={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]};var wn={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{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-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"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(wn).map(([t,e])=>[t,e.models]));var mi=[{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]"}],_i={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};function En(t){return _i[t]??t}var ki=new Map(mi.map(({baseModelId:t,catalogModelId:e})=>[t,e]));function Ti(t){return ki.get(t)??t}var yi=[{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"}],wi=new Map(yi.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));function Rn(t){if(!t)return {};let e=wi.get(t);return e?{...e}:{model:t}}function In(t,e){return t==="antigravity"||t==="cli/antigravity"?Rn(e):e===void 0?{}:{model:Ti(e)}}var Ei={};function Ri(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function je(t){return Bt(t).models}function Bt(t){return Ei[t]??wn[t]??Ri()}function mt(t,e){let n=Bt(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=In(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Nr(t){return Bt(t).modelOverrides}function Dr(){return je("claude")}function Pr(){return je("codex")}function Lr(){return je("copilot")}function Mr(){return je("antigravity")}var Ii={auto:"default"};function $r(t){return Ii[t]??t}var vi=new Set(br);function jt(t,e){return (qt[t]??[]).includes(e)}function Ge(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return vi.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Hr(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 Ur(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 Fr(t){return !t||!jt("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function qr(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=$r(t);return e.has(n)?["--permission-mode",n]:[]}function Br(t){return t?jt("claude",t)?["--effort",t]:[]:[]}var Ai=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);function jr(t){return t==="default"?[]:t&&Ai.has(t)?["--permission-mode",t]:[]}function Gr(t){return t===true?["--always-approve"]:[]}function Wr(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 zr(t){return t?jt("grok",t)?["--effort",t]:[]:[]}function Vr(t){if(!t)return [];switch(En(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Jr(t){return t?jt("antigravity",t)?["--effort",t]:[]:[]}function xi(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 Si(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 Kr(t){let e=new Map,n;for(let s of t.split(`
|
|
303
|
+
`))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 et(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
304
|
+
`))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=xi(o)??Si(o);i&&(e=i);}catch{}return n||(e??void 0)}var Ci=new Set(["tool_progress"]);function Yr(t){let e=t.split(`
|
|
305
|
+
`).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{}if(n.length>0)return n[n.length-1];if(r)return r}var vn={command:"claude",meta:{displayName:"Claude",models:Dr(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Ge(e.model),s=e.effort??o,i=qr(e.mode),a=Br(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){return Yr(t)??t.trim()},extractPartialText(t){return Yr(t)},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 De(`Claude rate limit: ${n.rateLimitType??"unknown"} (status: ${n.status})`)}if(e.error==="rate_limit"){let n=bi(e);return new De(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(Ni(n))return new De(`Claude rate limit: ${n}`)}}catch{}return null},parseResultMeta(t){let e=t.split(`
|
|
306
|
+
`);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=Kr(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?Ci.has(r):!1}catch{return false}}};function bi(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
307
307
|
|
|
308
|
-
`):""}function
|
|
309
|
-
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...
|
|
310
|
-
`).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{}
|
|
311
|
-
`).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=Ze(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=Si(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(...Oi(n,l));continue}if(a==="item.completed"){let c=bi(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?vi.has(r):!1}catch{return false}}};function Oi(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 bi(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=Ci(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",...De(r,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",...De(o,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 Ci(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 Ni=new Set(["step_start","step_finish"]),et="cli/opencode",Vr="OpenCode provider error",Kr=240,Di={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};function Li(t){return t?Di[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function qt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Jr(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 tt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pi(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);tt(i)?e.push(i):n=!0;continue}catch{}let s=Jr(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);tt(a)?e.push(a):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Ke(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,Kr).trim()}function Yr(t){let e=tt(t.error)?t.error:void 0,n=e&&tt(e.data)?e.data:void 0,r=Ke(e?.name),o=Ke(n?.message)??Ke(e?.message)??Ke(t.message)??Ke(t.errorMessage)??Ke(t.error),s=Ke(t.ref),i=r&&o&&r!==o?`${r}: ${o}`:r??o??Vr;return (s?`${i} (ref: ${s})`:i).slice(0,Kr)}function Wr(t){let e=Pi(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=tt(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(Yr(l));continue}if(c==="step_finish"){a=true;let u=tt(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 Xr(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Bt(){return new z("OpenCode returned no assistant output.",et,{code:"EMPTY_OUTPUT",kind:"transient"})}function Mi(){return new z("OpenCode emitted malformed JSON output.",et,{code:"PROVIDER_CRASHED",kind:"transient"})}function zr(t,e){switch(Xr(t)){case "length":return new z("OpenCode stopped because the context window was exceeded.",et,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new z("OpenCode stopped because the content filter blocked the response.",et,{code:"UNKNOWN",kind:"permanent"});case "error":return new z(e?`OpenCode error: ${e}`:`${Vr} while generating a response.`,et,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var In={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];qt(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=Li(e.mode);qt(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!qt(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!qt(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=Wr(t),n=e.errorMessages[0];if(n){let i=zr("error",n);if(i)throw i}let r=zr(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 Bt();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Bt();return e.resultText}if(e.malformed)throw Mi();if(!e.hasTerminal)throw Bt();let s=Xr(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Bt()},interpretExit(t,e,n=""){if(t===0)return null;let o=Wr(n).errorMessages[0];return o?new z(`OpenCode error: ${o}`,et,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=Ze(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=Jr(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,x=we(m);if(r.push({timestamp:n,type:"tool_use",toolName:c,toolUseId:u,toolInput:x}),h==="completed"&&g?.output!==void 0){let A=g.output,v=typeof A=="string"?A:JSON.stringify(A);r.push({timestamp:n,type:"tool_result",toolUseId:u,resultPreview:v,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=Yr(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?Ni.has(r):!1}catch{return false}}};var An="antigravity";function mt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function $i(t,e){if(!(t?Be(An).some(s=>s.id===t):false)||!t)return e;let r=ht(An,t),o=Sr(An)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var vn={command:"agy",meta:{displayName:"Antigravity",models:Cr(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=je(e.model),s=Tn(r),i=s.model,a=e.effort??o??s.effort,l=$i(i,a),c=e.additionalArgs??[],u=i&&!mt(c,"--model")?["--model",i]:[],g=mt(c,"--effort")?[]:jr(l),h=mt(c,"--mode")||mt(c,"--dangerously-skip-permissions")?[]:Br(e.mode),m=mt(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 jt="cli/grok",Ui=new Set(["available_commands","usage","end"]),Fi=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,qi=/\u001b\[[0-?]*[ -/]*[@-~]/g,Qr=20,Zr=4e3,eo="\u2026";function nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Gt(t){return nt(t)?t:void 0}function Y(t){return typeof t=="string"?t:void 0}function Je(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Bi(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 _t(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return nt(n)?[n]:[]}catch{return Bi(e).flatMap(n=>{try{let r=JSON.parse(n);return nt(r)?[r]:[]}catch{return []}})}}function kt(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Tt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Tt).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
312
|
-
`):void 0}if(
|
|
313
|
-
`).flatMap(
|
|
314
|
-
`),o=r.length>
|
|
315
|
-
`).flatMap(
|
|
316
|
-
`).flatMap(
|
|
317
|
-
`)
|
|
308
|
+
`):""}function Ni(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=Ee(s);return r==="Bash"&&ye(i)?we(t,i,o):{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(`
|
|
309
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...Pe(i,r)}}return null}var Pi=new Set(["interactive","plan","autopilot"]);function Xr(t){let e=t.split(`
|
|
310
|
+
`).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{}if(n.length>0)return n[n.length-1];if(r)return r}var An={command:"copilot",meta:{displayName:"Copilot",models:Lr()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&Pi.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(qt.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){return Xr(t)??t.trim()},extractPartialText(t){return Xr(t)},parseResultMeta(t){let e=et(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=Ee(l);return (a==="bash"||a==="Bash")&&ye(c)?[we(s,c,i)]:[{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",...i&&{toolUseId:i},...Pe(String(a.message||""),true)}];let l=o.result,c=String(l?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Pe(c,false)}]}if(r==="assistant.message"){let a=String(o.content||"");return a?[{timestamp:s,type:"text",content:a}]:[]}return []}};var Li=new Set(["turn.started","turn.completed","item.updated"]);function Mi(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 $i(t){return t[0]==="exec"?t.slice(1):t}function Qr(t){let e=t.split(`
|
|
311
|
+
`).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{}if(n.length>0)return n[n.length-1];if(r)return r}var xn={command:"codex",meta:{displayName:"Codex",models:Pr(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=Ge(e.model),s=e.effort??o,i=e.resumeSessionId?Ur(e.mode):Hr(e.mode),a=Fr(s),l=r?["-m",r]:[],c=$i(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){return Qr(t)??t.trim()},extractPartialText(t){return Qr(t)},parseResultMeta(t){let e=et(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=Mi(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(...Hi(n,l));continue}if(a==="item.completed"){let c=Ui(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?Li.has(r):!1}catch{return false}}};function Hi(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return ye(r)?[we(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function Ui(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=Fi(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",...Pe(r,o)}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=Ee(o);return r==="Bash"&&ye(s)?we(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",...Pe(o,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 Fi(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=Ee(o);return r==="Bash"&&ye(s)?we(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var qi=new Set(["step_start","step_finish"]),tt="cli/opencode",to="OpenCode provider error",no=240,Bi={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};function ji(t){return t?Bi[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Gt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function ro(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 nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Gi(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);nt(i)?e.push(i):n=!0;continue}catch{}let s=ro(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);nt(a)?e.push(a):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Ke(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,no).trim()}function oo(t){let e=nt(t.error)?t.error:void 0,n=e&&nt(e.data)?e.data:void 0,r=Ke(e?.name),o=Ke(n?.message)??Ke(e?.message)??Ke(t.message)??Ke(t.errorMessage)??Ke(t.error),s=Ke(t.ref),i=r&&o&&r!==o?`${r}: ${o}`:r??o??to;return (s?`${i} (ref: ${s})`:i).slice(0,no)}function Zr(t){let e=Gi(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=nt(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(oo(l));continue}if(c==="step_finish"){a=true;let u=nt(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 so(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Wt(){return new z("OpenCode returned no assistant output.",tt,{code:"EMPTY_OUTPUT",kind:"transient"})}function Wi(){return new z("OpenCode emitted malformed JSON output.",tt,{code:"PROVIDER_CRASHED",kind:"transient"})}function eo(t,e){switch(so(t)){case "length":return new z("OpenCode stopped because the context window was exceeded.",tt,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new z("OpenCode stopped because the content filter blocked the response.",tt,{code:"UNKNOWN",kind:"permanent"});case "error":return new z(e?`OpenCode error: ${e}`:`${to} while generating a response.`,tt,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var Sn={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Gt(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=ji(e.mode);Gt(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!Gt(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!Gt(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=Zr(t),n=e.errorMessages[0];if(n){let i=eo("error",n);if(i)throw i}let r=eo(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 Wt();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Wt();return e.resultText}if(e.malformed)throw Wi();if(!e.hasTerminal)throw Wt();let s=so(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Wt()},interpretExit(t,e,n=""){if(t===0)return null;let o=Zr(n).errorMessages[0];return o?new z(`OpenCode error: ${o}`,tt,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=et(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=ro(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,S=Ee(m);if(r.push({timestamp:n,type:"tool_use",toolName:c,toolUseId:u,toolInput:S}),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=oo(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?qi.has(r):!1}catch{return false}}};var On="antigravity";function _t(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function zi(t,e){if(!(t?je(On).some(s=>s.id===t):false)||!t)return e;let r=mt(On,t),o=Nr(On)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var Cn={command:"agy",meta:{displayName:"Antigravity",models:Mr(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=Ge(e.model),s=Rn(r),i=s.model,a=e.effort??o??s.effort,l=zi(i,a),c=e.additionalArgs??[],u=i&&!_t(c,"--model")?["--model",i]:[],g=_t(c,"--effort")?[]:Jr(l),h=_t(c,"--mode")||_t(c,"--dangerously-skip-permissions")?[]:Vr(e.mode),m=_t(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 zt="cli/grok",Ji=new Set(["available_commands","usage","end"]),Ki=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,Yi=/\u001b\[[0-?]*[ -/]*[@-~]/g,io=20,ao=4e3,lo="\u2026";function rt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Vt(t){return rt(t)?t:void 0}function Y(t){return typeof t=="string"?t:void 0}function Ye(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Xi(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 kt(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return rt(n)?[n]:[]}catch{return Xi(e).flatMap(n=>{try{let r=JSON.parse(n);return rt(r)?[r]:[]}catch{return []}})}}function Tt(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function yt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(yt).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
312
|
+
`):void 0}if(rt(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=yt(t[e]);if(n!==void 0)return n}}}function Qi(t){if(t.rawOutput!==null&&t.rawOutput!==void 0)return yt(t.rawOutput)??Tt(t.rawOutput);if(t.content!==null&&t.content!==void 0)return yt(t.content)??Tt(t.content);if(t.result!==null&&t.result!==void 0)return yt(t.result)??Tt(t.result)}function uo(t){let e=Vt(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?po(n):"Grok CLI reported an error."}function po(t){return (t.replace(Yi,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function co(t){return Ki.test(t)}function Zi(t){let e=Vt(t.modelUsage);return e?Object.keys(e)[0]??null:null}function ea(t){let e=Vt(t.usage);if(!e)return null;let n=Ye(e.cache_read_input_tokens);return {inputTokens:Ye(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Ye(e.output_tokens),costUsd:Ye(t.total_cost_usd)}}function ta(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
313
|
+
`).flatMap(kt)){if(i.type!=="usage")continue;let a=Vt(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=Ye(a.cache_read_input_tokens);e+=Ye(a.input_tokens)+c,n+=c,r+=Ye(a.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function na(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,io)){if(!rt(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>io&&n.push(lo);let r=n.join(`
|
|
314
|
+
`),o=r.length>ao?`${r.slice(0,ao-1)}${lo}`:r;return [{timestamp:t,type:"info",content:o}]}function ra(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 na(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:Tt(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:Qi(e),isError:r!=="completed"||e.isError===true}]}if(n==="error"){let r=uo(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var bn={command:"grok",createSessionId:()=>randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=Ge(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],a=n?je("grok").some(de=>de.id===n):false,l=n&&a?mt("grok",n):[],c=!o||l.length===0||l.includes(o)?o:void 0,u=zr(c),g=e.additionalArgs??[],h=de=>g.some(te=>te===de||te.startsWith(`${de}=`)),m=e.providerOptions,S=m?.alwaysApprove,v=m?.sandbox,A=h("--permission-mode")?[]:jr(e.mode),H=h("--always-approve")?[]:Gr(S),j=h("--sandbox")?[]:Wr(v);return {args:["--no-auto-update",...s,"--single",t,"--output-format","streaming-json","--no-alt-screen",...i,...u,...A,...H,...j,...g]}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
315
|
+
`).flatMap(kt))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 kt(t))if(e.type==="error"){let n=uo(e);return co(Tt(e))?new De(n,zt):new z(n,zt)}return null},interpretExit(t,e){if(t===0)return null;let n=po(e)||`Grok CLI exited with code ${t}.`;return co(e)?new De(n,zt):new z(n,zt)},parseResultMeta(t){let n=t.split(`
|
|
316
|
+
`).flatMap(kt).find(r=>r.type==="end");return n?{usage:ea(n),model:Zi(n)}:{usage:ta(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return kt(t).flatMap(r=>ra(n,r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return rt(n)&&typeof n.type=="string"?Ji.has(n.type):!1}catch{return false}}};var go={codex:xn,claude:vn,opencode:Sn,antigravity:Cn,copilot:An,grok:bn};function fo(t){if(t.startsWith("cli/"))return go[t.slice(4)]}function oa(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=r.type;if(typeof o!="string")return false;let s=e?pa[e]:void 0;return s?s(r,o):Object.values(mo).some(i=>i(r,o))}function Jt(t,e){let n=t.split(`
|
|
317
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>oa(r,e))}function ie(t){return typeof t=="object"&&t!==null}function ho(t,e){if(e==="assistant"||e==="user"){let n=t.message;return ie(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||ie(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?ie(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function sa(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:ho(t,e)}function ia(t,e){if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return ie(n)&&typeof n.type=="string"}return false}function aa(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||ie(t.part):e==="text"||e==="tool_use"?ie(t.part):e==="result"?typeof t.result=="string":false}function da(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||ie(t.part)||e==="result"&&typeof t.result=="string")}function la(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?ie(t.data):e==="result"?typeof t.result=="string":false}function ca(t,e){return e==="message"?typeof t.role=="string":e==="tool_use"?typeof t.tool_name=="string"||typeof t.tool_id=="string":e==="tool_result"?typeof t.tool_id=="string"||typeof t.status=="string":false}function ua(t,e){return e==="available_commands"?ie(t.tools)||ie(t.commands):e==="usage"?ie(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||ie(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var mo={claude:ho,codex:ia,opencode:aa,copilot:la,gemini:ca},pa={...mo,claude:sa,opencode:da,grok:ua,antigravity:()=>false};var fa=200,ha=200;function ma(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 _a(t){let e=t instanceof p?t.code:void 0,n=t instanceof p?t.cause:t,r=ma(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function ko(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function ka(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ta(t){if(!t)return {};try{let e=JSON.parse(t);return ka(e)?e:{}}catch{return {}}}function To(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Dn=class extends $e{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 Ft({dbPath:this.dbPath});this.taskRepo=n;let r=process.cwd(),s=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))?Xn(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],ko(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+=ko(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>=fa){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));},ha);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo?.getTask(e);if(!o||o.status!=="running"||To(o.run_epoch)!==To(r))return;let s=Ta(o.metadata),i=typeof s.provider=="string"?s.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!i)return;let a=fo(i);if(!a?.extractPartialText)return;let c=this.taskRepo?.readLogs(e)?.entries.filter(g=>g.level==="stdout").map(g=>g.message).join(`
|
|
318
|
+
`)??"";if(!c.trim())return;let u=a.extractPartialText(c);return !u||!u.trim()||Jt(u,i)?void 0:u}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=_a(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 ot=class extends p{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function wt(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Ia(t){let n=wt(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 Kt=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=M(n);if(e)try{fe(r.db,n);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,n){return e.db.select({id:Qe.id}).from(Qe).where(eq(Qe.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
318
319
|
SELECT 1 FROM tasks parent
|
|
319
320
|
WHERE parent.id = ${e}.parent_task_id
|
|
320
321
|
AND parent.thread_id = ${e}.thread_id
|
|
@@ -335,7 +336,7 @@ ${r.join(`
|
|
|
335
336
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
336
337
|
AND ${this.topLevelTaskPredicateSql()}
|
|
337
338
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
338
|
-
`);for(let
|
|
339
|
+
`);for(let S of m)c.add(S.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=M(a);try{let c;r!==void 0?c=l.db.all(sql`
|
|
339
340
|
SELECT * FROM (
|
|
340
341
|
SELECT child.*,
|
|
341
342
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -370,11 +371,11 @@ ${r.join(`
|
|
|
370
371
|
message_count = message_count + 1,
|
|
371
372
|
updated_at = ${s}
|
|
372
373
|
WHERE id = ${e}
|
|
373
|
-
`),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 rt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new rt("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 rt("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 rt("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=yt(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 x=Object.keys(g).length>0?JSON.stringify(g):null,A=new Date().toISOString();c.update(f).set({metadata:x,updated_at:A}).where(l).run();let v=c.select({metadata:f.metadata}).from(f).where(l).get();if(!v)throw new p("DB_ERROR","Thread-title metadata update could not be read back");let H=ia(v.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=yt(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=yt(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=yt(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,x=o?.updatedBy??"ui",A=new Date().toISOString(),v,H,j,ae;switch(r){case "enable-count":{let te=o?.turns??m,Pe=o?.consumeCurrent?Math.max(te-1,0):te;v=Pe>0?"count":"off",H=Pe,j=!0,ae="count";break}case "enable-latch":{v="latch",H=0,j=!0,ae="latch";break}case "disable":{v="off",H=0,j=!1;break}default:{let te=h.state??"off",Pe=typeof h.remaining=="number"?h.remaining:0;if(te==="count"&&Pe>0){let b=Pe-1;b<=0?(v="off",H=0):(v="count",H=b),j=!0,ae="count";}else te==="latch"?(v="latch",H=0,j=!0,ae="latch"):(v="off",H=0,j=!1);break}}return g.overdrive={state:v,remaining:H,defaultTurns:m,updatedAt:A,updatedBy:x},c.update(f).set({metadata:JSON.stringify(g),updated_at:A}).where(a).run(),{applied:j,appliedMode:ae,state:v,remaining:H}},{behavior:"immediate"})}catch(a){throw a instanceof p?a:new p("DB_ERROR","Failed to resolve overdrive",a)}finally{i.close();}}};var bn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function aa(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+=bn[o%62]);}for(;n.length<t;)n+=bn[randomBytes(1)[0]%62];return n}function wt(t){return `${t}_${aa(8)}`}function fo(t,e){let{createHash:n}=lt("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+=bn[i%62];return `${t}_${s}`}var da=["urgent","high","medium","low"],la=["investigating","in-progress","in-review","on-hold","done"],ho="custom:";var ca=new Set(da),ua=new Set(la);function Cn(t){return typeof t=="string"&&ca.has(t)}function Nn(t){if(typeof t!="string")return false;if(ua.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(ho))return false;let e=t.slice(ho.length);return e.length>=1&&e.length<=20}function mo(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 Dn(t){let e=mo(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return Cn(r.priority)&&(o.priority=r.priority),Nn(r.state)&&(o.state=r.state),o}function _o(t,e){let n=mo(t)??{},r={...Dn(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 ma="regeneration_replaced";var _a="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var ka="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Mn=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;}},xt=class extends Mn{},$n=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;}},Ta=new Set(cr),ya=new Set(lr),wa=new Set(ur),Ea=new Set(pr),Ra=50,To=100,yo=280,wo=40,Ia=new Set(gr),zt=["queued","running"],Aa=["success","completed","done","failed","error"];function Pn(t){return Ia.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 Rt(t={}){let e=t.actor??t,n=e.actorType??"system";return Ta.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 va(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&&!Cn(t.priority)&&D(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Nn(t.state)&&D(`invalid state: ${String(t.state)}`);}function Sa(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??Ra;return (!Number.isInteger(e)||e<1||e>To)&&D(`limit must be between 1 and ${To}`),e}function Hn(t){typeof t!="string"&&D("text is required");let e=t.trim();return e.length===0&&D("text must not be empty"),e.length>yo&&D(`text must be at most ${yo} characters`),e}function Le(t,e){return w(t??"",e),t}function Un(t){Ea.has(t)||D(`invalid highlight kind: ${String(t)}`);}function xa(t){wa.has(t)||D(`invalid highlight source: ${String(t)}`);}function Oa(t){w(t.threadId,"threadId"),w(t.workspaceId,"workspaceId");let e=t.source??"manual";xa(e),Un(t.kind);let n=Hn(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=Le(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=Le(r,"coversFromTaskId"),i=Le(o,"coversToTaskId"),a=t.sourceTaskId??s,l=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Le(a??void 0,"sourceTaskId"),Le(l??void 0,"detectorVersion"),Le(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 ba(t,e){(!t||typeof t!="object")&&D(`candidates[${e}] is required`),Un(t.kind);let n=Hn(t.text),r=Le(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Le(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Le(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||fo("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 Ca(t){Array.isArray(t)||D("candidates must be an array"),t.length>wo&&D(`candidates must contain at most ${wo} items`);let e=new Map;for(let[n,r]of t.entries()){let o=ba(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function St(t){let e=Dn(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 Na(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 It(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${C.seq}), 0)`}).from(C).where(eq(C.thread_id,e)).get()?.maxSeq??0}function At(t,e){return !!t.select({id:C.id}).from(C).where(eq(C.thread_id,e)).limit(1).get()}function Ye(t,e){ya.has(e.type)||D(`invalid thread event type: ${String(e.type)}`);let n=wt("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:Na(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 vt(t,e,n,r,o){let s=St(e);Ye(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 Kt(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 Vt(t,e,n,r,o,s,i){let a=o==="thread.highlight.created"?Kt(e):{before:i?Kt({...e,...i,id:e.id}):void 0,after:Kt(e)};return Ye(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 Da(t,e,n,r,o,s){return Ye(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:Kt(e),...s??{}}})}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");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=M(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?St(o):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){va(e);let n=Rt(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=St(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 x=i.metadata;(g||h)&&(x=_o(i.metadata,{priority:e.priority,state:e.state}));let A={};if(m&&(A.metadata=x,A.updated_at=r),c&&(A.title=e.title),l&&(A.title_locked=1),s.update(f).set(A).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 j={...i,title_locked:1};return St(j)}let v=It(s,i.id)+1;At(s,i.id)||(vt(s,i,n,r,v),v+=1),c&&(Ye(s,{threadId:i.id,seq:v,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.title,after:e.title}}),v+=1),g&&(Ye(s,{threadId:i.id,seq:v,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:a.priority,after:e.priority}}),v+=1),h&&Ye(s,{threadId:i.id,seq:v,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:x,title_locked:l?1:i.title_locked,updated_at:r};return St(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,Aa),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,zt))).orderBy(asc(S.requested_at),asc(S.id)).limit(1).get();if(a)throw new $n(a);let l=e.runId??wt("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`),Pn(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`),Pn(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,zt))).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=_a){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,zt)).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=Ca(e.candidates),r=Rt(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`),Pn(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(b=>b.contentFingerprint)),g=c.filter(b=>b.source==="auto"&&b.status==="active"&&b.revision===0&&!u.has(b.content_fingerprint??"")),h=c.filter(b=>b.source==="auto"&&b.status==="active").length,m=new Set(c.filter(b=>!g.includes(b)&&b.content_fingerprint).map(b=>b.content_fingerprint)),x=n.filter(b=>!m.has(b.contentFingerprint)),A=new Date().toISOString(),v=It(i,l.id)+1;At(i,l.id)||(vt(i,l,r,A,v),v+=1);for(let b of g)i.delete(E).where(eq(E.id,b.id)).run(),Da(i,b,r,A,v,{runId:e.runId,reason:ma}),v+=1;let H=0,j=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let b of x){let qn=wt("thl");i.insert(E).values({id:qn,thread_id:l.id,source:"auto",kind:b.kind,status:"active",text:b.text,covers_from_task_id:b.coversFromTaskId,covers_to_task_id:b.coversToTaskId,revision:0,created_at:A,updated_at:A,agent_id:j,source_task_id:b.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:b.contentFingerprint,dismissed_at:null}).run();let Bn=i.select().from(E).where(eq(E.id,qn)).get();if(!Bn)throw new p("DB_ERROR","Regenerated highlight insert did not return a row");Vt(i,Bn,r,A,"thread.highlight.created",v),v+=1,H+=1;}let te=i.select().from(E).where(eq(E.thread_id,l.id)).all().filter(b=>b.source==="auto"&&b.status==="active").length;Ye(i,{threadId:l.id,seq:v,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:A,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??A,completed_at:A,error_code:null,previous_auto_count:h,new_auto_count:te}).where(and(eq(S.id,a.id),inArray(S.status,zt))).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:ka});}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=Sa(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$1(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$1(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=Oa(e),r=Rt(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??wt("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=It(i,a.id)+1;return At(i,a.id)||(vt(i,a,r,o,g),g+=1),Vt(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&&Un(e.kind);let n=e.text===void 0?void 0:Hn(e.text),r=Rt(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 xt(a.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new xt(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,x=r.actorType==="user"&&l.source==="auto"&&m?"manual":l.source;if(!(m||x!==l.source))return l;let v=l.revision+1;i.update(E).set({source:x,kind:c,text:u,covers_from_task_id:g,covers_to_task_id:h,revision:v,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 j=It(i,a.id)+1;return At(i,a.id)||(vt(i,a,r,o,j),j+=1),Vt(i,H,r,o,"thread.highlight.updated",j,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=Rt(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 xt(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=It(s,i.id)+1;return At(s,i.id)||(vt(s,i,n,r,u),u+=1),Vt(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`
|
|
374
|
+
`),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 ot("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new ot("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 ot("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 ot("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=wt(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 S=Object.keys(g).length>0?JSON.stringify(g):null,v=new Date().toISOString();c.update(f).set({metadata:S,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=Ia(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=wt(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=wt(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=wt(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,S=o?.updatedBy??"ui",v=new Date().toISOString(),A,H,j,de;switch(r){case "enable-count":{let te=o?.turns??m,Me=o?.consumeCurrent?Math.max(te-1,0):te;A=Me>0?"count":"off",H=Me,j=!0,de="count";break}case "enable-latch":{A="latch",H=0,j=!0,de="latch";break}case "disable":{A="off",H=0,j=!1;break}default:{let te=h.state??"off",Me=typeof h.remaining=="number"?h.remaining:0;if(te==="count"&&Me>0){let C=Me-1;C<=0?(A="off",H=0):(A="count",H=C),j=!0,de="count";}else te==="latch"?(A="latch",H=0,j=!0,de="latch"):(A="off",H=0,j=!1);break}}return g.overdrive={state:A,remaining:H,defaultTurns:m,updatedAt:v,updatedBy:S},c.update(f).set({metadata:JSON.stringify(g),updated_at:v}).where(a).run(),{applied:j,appliedMode:de,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 Pn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function va(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+=Pn[o%62]);}for(;n.length<t;)n+=Pn[randomBytes(1)[0]%62];return n}function Et(t){return `${t}_${va(8)}`}function Io(t,e){let{createHash:n}=ct("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+=Pn[i%62];return `${t}_${s}`}var Aa=["urgent","high","medium","low"],xa=["investigating","in-progress","in-review","on-hold","done"],vo="custom:";var Sa=new Set(Aa),Oa=new Set(xa);function Ln(t){return typeof t=="string"&&Sa.has(t)}function Mn(t){if(typeof t!="string")return false;if(Oa.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(vo))return false;let e=t.slice(vo.length);return e.length>=1&&e.length<=20}function Ao(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 $n(t){let e=Ao(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return Ln(r.priority)&&(o.priority=r.priority),Mn(r.state)&&(o.state=r.state),o}function xo(t,e){let n=Ao(t)??{},r={...$n(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 Pa="regeneration_replaced";var La="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Ma="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Fn=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;}},Ot=class extends Fn{},qn=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;}},$a=new Set(fr),Ha=new Set(gr),Ua=new Set(hr),Fa=new Set(mr),qa=50,Oo=100,Co=280,bo=40,Ba=new Set(_r),Yt=["queued","running"],ja=["success","completed","done","failed","error"];function Un(t){return Ba.has(t)}function D(t){throw new p("VALIDATION",t)}function ge(t){throw new p("NOT_FOUND",t)}function w(t,e){(typeof t!="string"||t.trim().length===0)&&D(`${e} is required`);}function It(t={}){let e=t.actor??t,n=e.actorType??"system";return $a.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 Ga(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&&!Ln(t.priority)&&D(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Mn(t.state)&&D(`invalid state: ${String(t.state)}`);}function Wa(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??qa;return (!Number.isInteger(e)||e<1||e>Oo)&&D(`limit must be between 1 and ${Oo}`),e}function Bn(t){typeof t!="string"&&D("text is required");let e=t.trim();return e.length===0&&D("text must not be empty"),e.length>Co&&D(`text must be at most ${Co} characters`),e}function Le(t,e){return w(t??"",e),t}function jn(t){Fa.has(t)||D(`invalid highlight kind: ${String(t)}`);}function za(t){Ua.has(t)||D(`invalid highlight source: ${String(t)}`);}function Va(t){w(t.threadId,"threadId"),w(t.workspaceId,"workspaceId");let e=t.source??"manual";za(e),jn(t.kind);let n=Bn(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=Le(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=Le(r,"coversFromTaskId"),i=Le(o,"coversToTaskId"),a=t.sourceTaskId??s,l=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Le(a??void 0,"sourceTaskId"),Le(l??void 0,"detectorVersion"),Le(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 Ja(t,e){(!t||typeof t!="object")&&D(`candidates[${e}] is required`),jn(t.kind);let n=Bn(t.text),r=Le(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Le(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Le(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Io("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 Ka(t){Array.isArray(t)||D("candidates must be an array"),t.length>bo&&D(`candidates must contain at most ${bo} items`);let e=new Map;for(let[n,r]of t.entries()){let o=Ja(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function St(t){let e=$n(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 Ya(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 vt(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${b.seq}), 0)`}).from(b).where(eq(b.thread_id,e)).get()?.maxSeq??0}function At(t,e){return !!t.select({id:b.id}).from(b).where(eq(b.thread_id,e)).limit(1).get()}function Xe(t,e){Ha.has(e.type)||D(`invalid thread event type: ${String(e.type)}`);let n=Et("the");t.insert(b).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:Ya(e.payload),created_at:e.createdAt}).run();let r=t.select().from(b).where(eq(b.id,n)).get();if(!r)throw new p("DB_ERROR","Thread event insert did not return a row");return r}function xt(t,e,n,r,o){let s=St(e);Xe(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 Qt(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 Xt(t,e,n,r,o,s,i){let a=o==="thread.highlight.created"?Qt(e):{before:i?Qt({...e,...i,id:e.id}):void 0,after:Qt(e)};return Xe(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 Xa(t,e,n,r,o,s){return Xe(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:Qt(e),...s??{}}})}var Zt=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=M(n);if(e)try{fe(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(x).where(eq(x.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?St(o):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Ga(e);let n=It(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||ge(`Thread ${e.threadId} not found`);let a=St(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 S=i.metadata;(g||h)&&(S=xo(i.metadata,{priority:e.priority,state:e.state}));let v={};if(m&&(v.metadata=S,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 j={...i,title_locked:1};return St(j)}let A=vt(s,i.id)+1;At(s,i.id)||(xt(s,i,n,r,A),A+=1),c&&(Xe(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&&(Xe(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&&Xe(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:S,title_locked:l?1:i.title_locked,updated_at:r};return St(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(${b.seq}), 0)`}).from(b).where(eq(b.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,ja),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||ge(`Thread ${e.threadId} not found`);let i=o.select().from(x).where(and(eq(x.thread_id,s.id),eq(x.request_id,e.requestId))).orderBy(desc(x.requested_at),desc(x.id)).limit(1).get();if(i)return {run:i,created:!1};let a=o.select().from(x).where(and(eq(x.thread_id,s.id),inArray(x.status,Yt))).orderBy(asc(x.requested_at),asc(x.id)).limit(1).get();if(a)throw new qn(a);let l=e.runId??Et("thr");o.insert(x).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(x).where(eq(x.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(x).where(and(eq(x.thread_id,e),eq(x.request_id,r))).orderBy(desc(x.requested_at),desc(x.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||ge(`Highlight regeneration run ${e} not found`),Un(i.status)||D(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(x).set({status:"running",started_at:r}).where(and(eq(x.id,i.id),eq(x.status,"queued"))).run();let a=s.select().from(x).where(eq(x.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||ge(`Highlight regeneration run ${e.runId} not found`),Un(s.status)||D(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(x).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(x.id,s.id),inArray(x.status,Yt))).run();let i=o.select().from(x).where(eq(x.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=La){w(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(x).set({status:"failed",completed_at:n,error_code:e}).where(inArray(x.status,Yt)).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=Ka(e.candidates),r=It(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)&&ge(`Highlight regeneration run ${e.runId} not found`),Un(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||ge(`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(C=>C.contentFingerprint)),g=c.filter(C=>C.source==="auto"&&C.status==="active"&&C.revision===0&&!u.has(C.content_fingerprint??"")),h=c.filter(C=>C.source==="auto"&&C.status==="active").length,m=new Set(c.filter(C=>!g.includes(C)&&C.content_fingerprint).map(C=>C.content_fingerprint)),S=n.filter(C=>!m.has(C.contentFingerprint)),v=new Date().toISOString(),A=vt(i,l.id)+1;At(i,l.id)||(xt(i,l,r,v,A),A+=1);for(let C of g)i.delete(E).where(eq(E.id,C.id)).run(),Xa(i,C,r,v,A,{runId:e.runId,reason:Pa}),A+=1;let H=0,j=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let C of S){let Wn=Et("thl");i.insert(E).values({id:Wn,thread_id:l.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:v,updated_at:v,agent_id:j,source_task_id:C.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:C.contentFingerprint,dismissed_at:null}).run();let zn=i.select().from(E).where(eq(E.id,Wn)).get();if(!zn)throw new p("DB_ERROR","Regenerated highlight insert did not return a row");Xt(i,zn,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(C=>C.source==="auto"&&C.status==="active").length;Xe(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(x).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(x.id,a.id),inArray(x.status,Yt))).run();let Me=i.select().from(x).where(eq(x.id,a.id)).get();if(!Me)throw new p("DB_ERROR","Highlight regeneration completion did not return a row");return {run:Me,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:Ma});}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=Wa(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(${b.seq}), 0)`}).from(b).where(eq(b.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(b).where(and(eq(b.thread_id,o.threadId),lt$1(b.seq,o.beforeSeq))).orderBy(desc(b.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(b).where(and(eq(b.thread_id,o.threadId),sql`${b.seq} > ${o.afterSeq}`)).orderBy(asc(b.seq)).limit(s+1).all():l=i.db.select().from(b).where(eq(b.thread_id,o.threadId)).orderBy(desc(b.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:b.id}).from(b).where(and(eq(b.thread_id,o.threadId),lt$1(b.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=Va(e),r=It(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||ge(`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??Et("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=vt(i,a.id)+1;return At(i,a.id)||(xt(i,a,r,o,g),g+=1),Xt(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&&jn(e.kind);let n=e.text===void 0?void 0:Bn(e.text),r=It(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||ge(`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||ge(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new Ot(a.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new Ot(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,S=r.actorType==="user"&&l.source==="auto"&&m?"manual":l.source;if(!(m||S!==l.source))return l;let A=l.revision+1;i.update(E).set({source:S,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 j=vt(i,a.id)+1;return At(i,a.id)||(xt(i,a,r,o,j),j+=1),Xt(i,H,r,o,"thread.highlight.updated",j,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=It(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||ge(`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||ge(`Highlight ${e.highlightId} not found`),a.revision!==e.expectedRevision)throw new Ot(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=vt(s,i.id)+1;return At(s,i.id)||(xt(s,i,n,r,u),u+=1),Xt(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`
|
|
374
375
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
375
376
|
ORDER BY started_at ASC, id ASC
|
|
376
|
-
`),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),
|
|
377
|
+
`),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),S=l.get(h.covers_to_task_id);if(m===void 0||S===void 0)return !1;let v=Math.min(m,S),A=Math.max(m,S);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 F=class extends p{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Do="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function id(){let t=randomBytes(16),e="";for(let n of t)e+=Do[n%Do.length];return e.slice(0,12)}function Po(){return `c_${id()}`}function ad(t){return typeof t=="string"&&fn.includes(t)}function dd(t){return typeof t=="string"&&hn.includes(t)}function dt(t){if(!ad(t))throw new F("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Lo(t){if(!dd(t))throw new F("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function Mo(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new F("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function lt(t){if(typeof t!="string"||t.trim().length===0)throw new F("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function en(t){if(typeof t!="string"||t.trim().length===0)throw new F("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function We(t,e){return and(eq(k.code_group,t),or(isNull(k.workspace_id),eq(k.workspace_id,e)))}var tn=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=M(n);if(e)try{fe(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(dt(e),lt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(k).where(and(We(e,n),eq(k.is_archived,0))).orderBy(asc(k.sort_order),asc(k.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(dt(e),lt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(k).where(We(e,n)).orderBy(asc(k.sort_order),asc(k.code)).all()}catch(o){throw new p("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(dt(n),lt(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new F("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)en(o);if(new Set(e.codes).size!==e.codes.length)throw new F("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new F("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(k).where(We(n,e.workspaceId)).all(),i=s.filter(m=>m.is_archived===0),a=new Set(s.map(m=>m.code)),l=new Set(i.map(m=>m.code)),c=e.codes.find(m=>!a.has(m));if(c)throw new F("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(m=>!l.has(m)))throw new F("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let u=new Map(i.map(m=>[m.code,m])),g=e.codes.map(m=>{let S=u.get(m);if(!S)throw new F("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${m}`);return S}),h;for(let[m,S]of g.entries())S.sort_order!==m&&(h??=new Date().toISOString(),o.update(k).set({sort_order:m,updated_at:h}).where(and(eq(k.code_group,n),eq(k.code,S.code))).run());return o.select().from(k).where(We(n,e.workspaceId)).orderBy(asc(k.sort_order),asc(k.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(dt(e),en(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(k).where(and(eq(k.code_group,e),eq(k.code,n))).limit(1).get()??null}catch(o){throw new p("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){lt(e.workspaceId);let n=Mo(e.name);Lo(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:k.code}).from(k).where(and(We("THREAD_STATE",e.workspaceId),eq(k.is_archived,0),eq(k.code_name,n))).limit(1).get())throw new F("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=o.select({maxSortOrder:sql`max(${k.sort_order})`}).from(k).where(We("THREAD_STATE",e.workspaceId)).get(),a=new Date().toISOString(),l=Po();for(;o.select({code:k.code}).from(k).where(and(eq(k.code_group,"THREAD_STATE"),eq(k.code,l))).limit(1).get();)l=Po();o.insert(k).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(k).where(and(eq(k.code_group,"THREAD_STATE"),eq(k.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(dt(e.group),en(e.code),lt(e.workspaceId),e.name===void 0&&e.color===void 0)throw new F("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:Mo(e.name);e.color!==void 0&&Lo(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(k).where(and(eq(k.code_group,e.group),eq(k.code,e.code))).limit(1).get();if(!s)throw new F("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 F("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let l=and(We(e.group,e.workspaceId),eq(k.is_archived,0));if(o.select({code:k.code}).from(k).where(and(l,eq(k.code_name,n),sql`${k.code} <> ${e.code}`)).limit(1).get())throw new F("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(k).set(i).where(and(eq(k.code_group,e.group),eq(k.code,e.code))).run();let a=o.select().from(k).where(and(eq(k.code_group,e.group),eq(k.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(dt(e),en(n),lt(r),typeof o!="boolean")throw new F("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(k).where(and(eq(k.code_group,e),eq(k.code,n))).limit(1).get();if(!a)throw new F("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(a.is_builtin===1)throw new F("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:k.code}).from(k).where(and(We(e,r),eq(k.is_archived,0),eq(k.code_name,a.code_name),ne$1(k.code,n))).limit(1).get())throw new F("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${a.code_name}`);i.update(k).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(and(eq(k.code_group,e),eq(k.code,n))).run();let l=i.select().from(k).where(and(eq(k.code_group,e),eq(k.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 F("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function ud(t){return t.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
377
378
|
`).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(`
|
|
378
|
-
`).trim()}function
|
|
379
|
-
`):
|
|
380
|
-
`)[0].slice(0,200)),n.push({id:`${r.id}-assistant`,text:
|
|
379
|
+
`).trim()}function pd(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.provider;return typeof n=="string"?n:void 0}catch{return}}function gd(t,e,n){if(!t||e==="failed"&&Jt(t,n))return "";let r=t;try{let o=JSON.parse(r);Array.isArray(o)?r=o.filter(s=>s?.type==="text"&&s?.text).map(s=>s.text).join(`
|
|
380
|
+
`):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=ud(r);}return r}var nn=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Kt({dbPath:this.dbPath})}getThreadHistoryRepo(){return new Zt({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 tn({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=this.normalizeStatus(r.status),s=pd(r.metadata),i=gd(r.result,o??r.status??null,s);if(i||o==="running"||o==="failed"){let a={agent_id:r.agent_id,task_id:r.id};o&&(a.status=o),o==="failed"&&r.error&&(a.reason=r.error.split(`
|
|
381
|
+
`)[0].slice(0,200)),n.push({id:`${r.id}-assistant`,text:i,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:a});}}return n}};var Gn=class extends $e{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new nn(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{Gn as ConversationPlugin,on as FileLoggerPlugin,Dn as SqliteTracingPlugin};
|