@crewx/sdk 0.9.0-rc.91 → 0.9.0-rc.92
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +300 -118
- package/dist/esm/plugins/index.js +118 -118
- package/dist/esm/repository/index.js +29 -29
- package/dist/index.d.ts +5 -3
- package/dist/index.js +299 -117
- package/dist/migrations/0024_storage_metadata.sql +262 -0
- package/dist/migrations/meta/_journal.json +8 -1
- package/dist/plugins/index.js +118 -118
- package/dist/provider/cli/adapters/event-timestamp.util.d.ts +1 -0
- package/dist/repository/base-sqlite-repository.d.ts +1 -0
- package/dist/repository/db.d.ts +4 -1
- package/dist/repository/index.d.ts +2 -4
- package/dist/repository/index.js +29 -29
- package/dist/repository/storage-metadata.repository.d.ts +64 -0
- package/dist/repository/task.repository.d.ts +15 -0
- package/dist/schema/index.d.ts +1 -0
- package/dist/schema/storage-metadata.d.ts +181 -0
- package/dist/ui-instance/index.d.ts +2 -0
- package/dist/ui-instance/store.d.ts +14 -0
- package/package.json +1 -1
- package/dist/repository/thread-title-common-code-migration.d.ts +0 -13
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as xe from'path';import xe__default,{join,dirname,resolve}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,realpathSync,readFileSync}from'fs';import dr,{homedir}from'os';import {createHash,randomUUID,randomBytes}from'crypto';import {sql,eq,desc,and,isNull,lt,or as or$1,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 pt=(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 Jo=()=>fileURLToPath(import.meta.url),Yo=()=>xe__default.dirname(Jo()),_=Yo();var Ue=class{detach(e){}};function er(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 dn(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var ln=class extends Ue{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=er(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: ${dn(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=dn(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 ts(t){let e=xe.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 or(t){let e=ts(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 os="[crewx] Refusing to open the real CrewX database from a test process";function ir(t){if(t===":memory:")return t;let e=resolve(t),n=e,r=[];for(;!existsSync(n);){let s=dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=realpathSync(n);for(let s of r)o=join(o,s);return resolve(o)}function ss(t,e){let n=ir(t),r=ir(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Ve(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&ss(t,join(dr.homedir(),".crewx","crewx.db")))throw new Error(`${os}: ${t}. Set CREWX_DB or CREWX_TRACES_DB to an isolated temporary path or :memory:.`);return t}var ne=class{resolveDbPath(){let e=process.env.CREWX_DB||process.env.CREWX_TRACES_DB||join(dr.homedir(),".crewx","crewx.db");return Ve(e)}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 as=32*1024*1024;function L(t,e={}){let n=Ve(t),r=pt("better-sqlite3"),{drizzle:o}=pt("drizzle-orm/better-sqlite3"),s=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(s.exec("PRAGMA journal_mode = WAL"),s.exec(`PRAGMA journal_size_limit = ${as}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),runRaw:(i,d=[])=>s.prepare(i).run(...d),close:()=>s.close()}}var lr=new Set,ds={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 un(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function ls(t,e){if(e>0||!un(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(ds))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var cs={"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 us(t,e,n){if(!un(t,"__drizzle_migrations")||!un(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(xe__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=cs[i.tag];if(!d)continue;let l=xe__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)"),f=new Set(g.map(m=>m.name));for(let[m,I]of Object.entries(d))f.has(m)||(t.run(`ALTER TABLE tasks ADD COLUMN ${m} ${I}`),f.add(m));}}function ps(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(xe__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=xe__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let l=readFileSync(d,"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=[],f;for(;(f=u.exec(l))!==null;)g.push({table:f[1],column:f[2]});if(g.length===0||!l.split(/-->\s*statement-breakpoint/).map(S=>S.trim()).filter(Boolean).every(S=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(S)))continue;g.every(({table:S,column:v})=>t.all(`PRAGMA table_info("${S}")`).some(j=>j.name===v))&&t.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function gs(t){let{migrate:e}=pt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=pt("drizzle-orm"),r=[xe__default.join(_,"../migrations"),xe__default.join(_,"migrations"),xe__default.join(_,"../../../../drizzle/migrations"),xe__default.join(process.cwd(),"drizzle/migrations")],o=r.find(c=>existsSync(xe__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),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`(
|
|
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),ls(t,i),s?.cnt&&(ps(t,o,n),us(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 he(t,e){lr.has(e)||(gs(t),lr.add(e));}var et=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 a=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 me=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>a.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 Rs="json_extract(metadata, '$.threadTitle.state')",Is="json_extract(metadata, '$.threadTitle.priority')",h=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>et.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(Rs)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(Is))}));var xs=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>xs.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(()=>a.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(()=>h.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},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 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`
|
|
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 Rr=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(()=>Rr.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(()=>Rr.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 yn=["THREAD_STATE","THREAD_PRIORITY"],Tn=["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 Ir=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],vr=["user","agent","system"],Ar=["auto","manual"],xr=["decision","judgment","issue","result","pivot"];var Sr=["queued","running","completed","failed"],C=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>h.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},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(()=>h.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)})),R=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>h.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},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'`)}));sqliteTable("storage_metadata",{source_kind:text("source_kind").notNull(),source_id:text("source_id").notNull(),utc_ts:text("utc_ts"),bytes:integer("bytes").notNull()},t=>({pk:primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)}));sqliteTable("storage_metadata_state",{unit:text("unit").primaryKey().notNull(),cursor_rowid:integer("cursor_rowid").notNull().default(0),end_rowid:integer("end_rowid"),complete:integer("complete").notNull().default(0),updated_at:text("updated_at").notNull()});function br(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 Lr(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 Dr(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)=>Lr(r,o))}catch(r){throw r instanceof p?new p("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Mr(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 Pr(t){return {taskId:t.id,source:Mr(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function ii(t){if(!Number.isInteger(t)||t<0)throw new p("VALIDATION","Task log tail limit must be a non-negative integer")}var Bt=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?Ve(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let r=L(n);if(e)try{he(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.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)=>Lr(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 d=this.requireStateRowInTransaction(i,e),l=Mr(d);if(l==="blob"){let f=Dr(e,d.logs);if(i.update(a).set({logs:JSON.stringify([...f,...r]),log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new p("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let c=d.last_log_seq+1,u=d.last_log_seq+r.length;if(i.insert(me).values(r.map((f,m)=>({task_id:e,seq:c+m,timestamp:f.timestamp,level:f.level,message:f.message}))).run(),i.update(a).set({last_log_seq:u,log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new p("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:d.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?Pr(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 ii(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=Pr(s);if(i.source==="blob"){let u=Dr(e,s.logs);return {...i,entries:n===void 0?u:u.slice(Math.max(0,u.length-n))}}let d=o.select({seq:me.seq,timestamp:me.timestamp,level:me.level,message:me.message}).from(me).where(eq(me.task_id,e)).orderBy(n===void 0?asc(me.seq):desc(me.seq)),c=(n===void 0?d.all():d.limit(n).all()).map(({timestamp:u,level:g,message:f})=>({timestamp:u,level:g,message:f}));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 Rn=40,Ne="2026-05-09",pi="0.8.9-rc.13",De=10,Pe=parseInt(pi.split("rc.")[1]);function $r(){let t=sql`
|
|
18
18
|
CASE
|
|
19
|
-
WHEN ${
|
|
20
|
-
WHEN ${
|
|
21
|
-
WHEN ${
|
|
22
|
-
WHEN ${
|
|
23
|
-
WHEN ${
|
|
24
|
-
WHEN ${
|
|
25
|
-
WHEN ${
|
|
19
|
+
WHEN ${a.model} LIKE 'claude-%' OR ${a.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
20
|
+
WHEN ${a.model} LIKE 'gpt-%' OR ${a.model} LIKE 'codex-%' THEN 'codex'
|
|
21
|
+
WHEN ${a.model} LIKE 'gemini-%' THEN 'gemini'
|
|
22
|
+
WHEN ${a.model} LIKE 'grok-%' THEN 'grok'
|
|
23
|
+
WHEN ${a.model} LIKE 'zai-%' OR ${a.model} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
24
|
+
WHEN ${a.model} LIKE 'minimax/%' THEN 'minimax'
|
|
25
|
+
WHEN ${a.model} LIKE 'qwen%' THEN 'qwen'
|
|
26
26
|
ELSE 'unknown'
|
|
27
27
|
END
|
|
28
|
-
`,e=sql`json_extract(${
|
|
28
|
+
`,e=sql`json_extract(${a.metadata}, '$.provider')`,n=sql`trim(${e})`,r=sql`substr(${n}, 1, instr(${n}, '/') - 1)`,o=sql`
|
|
29
29
|
CASE
|
|
30
30
|
WHEN instr(${n}, '/') > 0
|
|
31
31
|
AND ${r} IN ('cli', 'acp', 'api', 'plugin', 'remote')
|
|
@@ -34,23 +34,23 @@ ${r.join(`
|
|
|
34
34
|
END
|
|
35
35
|
`;return sql`
|
|
36
36
|
CASE
|
|
37
|
-
WHEN ${
|
|
38
|
-
WHEN json_valid(${
|
|
39
|
-
WHEN json_type(${
|
|
40
|
-
WHEN json_type(${
|
|
41
|
-
WHEN json_type(${
|
|
37
|
+
WHEN ${a.metadata} IS NULL THEN ${t}
|
|
38
|
+
WHEN json_valid(${a.metadata}) = 0 THEN 'unknown'
|
|
39
|
+
WHEN json_type(${a.metadata}, '$') IS NOT 'object' THEN 'unknown'
|
|
40
|
+
WHEN json_type(${a.metadata}, '$.provider') IS NULL THEN ${t}
|
|
41
|
+
WHEN json_type(${a.metadata}, '$.provider') IS NOT 'text' THEN 'unknown'
|
|
42
42
|
WHEN ${n} = '' THEN 'unknown'
|
|
43
43
|
WHEN trim(${o}) = '' THEN 'unknown'
|
|
44
44
|
ELSE ${o}
|
|
45
45
|
END
|
|
46
|
-
`}var
|
|
46
|
+
`}var gi=new Set(["workflow","mcp"]),In="usageByEpoch";function xn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vn(t){if(!t)return {};try{let e=JSON.parse(t);return xn(e)?{...e}:{}}catch{return {}}}function se(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function An(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function fi(t){return {inputTokens:se(t.inputTokens??0),outputTokens:se(t.outputTokens??0),cachedInputTokens:se(t.cachedInputTokens??0),costUsd:se(t.costUsd??0)}}function hi(t){if(xn(t))return {inputTokens:se(t.inputTokens),outputTokens:se(t.outputTokens),cachedInputTokens:se(t.cachedInputTokens),costUsd:se(t.costUsd)}}function mi(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=hi(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function _i(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}var Hr=600*1e3,Gt=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 Bt({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?Ve(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let r=L(n);if(e)try{he(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(a).values(s).onConflictDoUpdate({target:a.id,set:{pid:sql`COALESCE(excluded.pid, ${a.pid})`},setWhere:eq(a.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(
|
|
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(a).where(eq(a.project_id,e)).orderBy(desc(a.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{let r=!1;n.db.transaction(o=>{let s=o.select({status:a.status,run_epoch:a.run_epoch,started_at:a.started_at,result:a.result,error:a.error,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!s)return;let i=An(s.run_epoch),d=An(e.runEpoch),l=s.status==="running"&&i===d,c=s.status==="success"&&e.status==="success"&&s.error===null&&e.error==null&&i===d&&s.result===null&&typeof e.result=="string"&&e.result.trim().length>0,u=i>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||i!==d,g={},f;if(u){f=vn(s.metadata);let m=xn(f[In])?{...f[In]}:{};m[String(d)]=fi(e),f[In]=m;let I=mi(m);g.metadata=JSON.stringify(f),g.input_tokens=I.inputTokens,g.output_tokens=I.outputTokens,g.cached_input_tokens=I.cachedInputTokens,g.cost_usd=I.costUsd;}else l&&(g.input_tokens=se(e.inputTokens??0),g.output_tokens=se(e.outputTokens??0),g.cached_input_tokens=se(e.cachedInputTokens??0),g.cost_usd=se(e.costUsd??0));l&&e.model!==void 0&&e.model!==null&&(g.model=e.model),e.partialResultRecovered===!0&&l&&(f??=vn(s.metadata),f.partialResultRecovered=!0,g.metadata=JSON.stringify(f)),l&&(g.status=e.status,g.result=e.result??null,g.error=e.error??null,g.completed_at=e.completedAt,g.duration_ms=i>0?_i(s.started_at,e.completedAt,e.durationMs):e.durationMs??null,g.exit_code=e.exitCode??null),c&&(f??=vn(s.metadata),f.lateResultFilled=!0,f.lateResultAt===void 0&&(f.lateResultAt=e.completedAt),g.metadata=JSON.stringify(f),g.result=e.result,r=!0),Object.keys(g).length>0&&o.update(a).set(g).where(eq(a.id,e.id)).run();},{behavior:"immediate"}),r&&console.warn(`[crewx] late task result filled taskId=${e.id} runEpoch=${An(e.runEpoch)}`);}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to finish task",r)}finally{n.close();}}updateTaskLifecycle(e){let n=this.openHandle(true);try{n.db.update(a).set({status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs}).where(and(eq(a.id,e.id),eq(a.workspace_id,e.workspaceId))).run();}catch(r){throw r instanceof p?r:new p("DB_ERROR","Failed to update task lifecycle",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(a).where(eq(a.status,"running")).orderBy(desc(a.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(a).orderBy(desc(a.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(a).where(eq(a.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:a.id,status:a.status,pid:a.pid}).from(a).where(eq(a.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(a).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(a.id,e),eq(a.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:a.id,pid:a.pid,platform:a.platform,run_epoch:a.run_epoch}).from(a).where(eq(a.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(a).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(a.id,i.id),eq(a.status,"running"))).run(),s++);continue}if(gi.has(i.platform??"cli"))continue;let d=`${i.id}:${i.run_epoch??0}`;o.add(d);let l=this.pidNullObservedSince.get(d);if(l===void 0){this.pidNullObservedSince.set(d,r);continue}r-l>=Hr&&(e.db.update(a).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(a.id,i.id),eq(a.status,"running"))).run(),s++,this.pidNullObservedSince.delete(d));}for(let i of Array.from(this.pidNullObservedSince.keys()))o.has(i)||this.pidNullObservedSince.delete(i);return s}finally{e.close();}}reapRunningWorkflowTasks(e=Hr){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString();return n.db.update(a).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(a.status,"running"),eq(a.platform,"workflow"),isNull(a.pid),lt(a.started_at,r),or$1(isNull(a.metadata),and(notLike(a.metadata,'%"kind":"workflow_card"%'),notLike(a.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=L(o);try{let i=n?eq(a.workspace_id,n):void 0,d=i?and(eq(a.id,e),i):eq(a.id,e),l=s.db.select().from(a).where(d).limit(1).get()??void 0;if(!l){let c=i?and(eq(a.thread_id,e),i):eq(a.thread_id,e);l=s.db.select().from(a).where(c).orderBy(desc(a.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 d=L(i);try{let l=n?and(eq(a.parent_task_id,e),eq(a.workspace_id,n)):eq(a.parent_task_id,e),c=d.db.select().from(a).where(l).orderBy(asc(a.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{d.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,
|
|
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,d=0;for(let l of r){if(!existsSync(l))continue;let c=L(l);try{let u=eq(a.thread_id,e),g=n?and(u,eq(a.workspace_id,n)):u,f=c.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(g).all();for(let m of f)o.has(m.id)||(o.add(m.id),s+=m.input_tokens??0,i+=m.output_tokens??0,d+=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:d}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],d=r?.projection==="activity-log";for(let l of o){if(!existsSync(l))continue;let c=L(l);try{let u=eq(a.thread_id,e),g=n?and(u,eq(a.workspace_id,n)):u,f=d?c.db.select({id:a.id,thread_id:a.thread_id,agent_id:a.agent_id,parent_task_id:a.parent_task_id,started_at:a.started_at,completed_at:a.completed_at}).from(a).where(g).orderBy(asc(a.started_at)).all():c.db.select().from(a).where(g).orderBy(asc(a.started_at)).all();for(let m of f)s.has(m.id)||(s.add(m.id),i.push(m));}catch(u){throw new p("DB_ERROR","Failed to find tasks by thread",u)}finally{c.close();}}return i}parseWorkflowCardMetadata(e){if(!e)return {};try{let n=JSON.parse(e);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=L(n);try{e.push(...r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(a.started_at)).all());}catch(o){throw new p("DB_ERROR","Failed to find workflow parent tasks",o)}finally{r.close();}}return e}findWorkflowParentTask(e){if(this.dbExists())for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=L(n);try{let o=r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),eq(a.workspace_id,e.workspaceId))).orderBy(desc(a.started_at),desc(a.id)).all();for(let s of o){let i=this.parseWorkflowCardMetadata(s.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return s}}catch(o){throw new p("DB_ERROR","Failed to find workflow parent task",o)}finally{r.close();}}}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let o=new Set(e),s=new Map,i=n?eq(a.workspace_id,n):void 0,d=(l,c)=>{if(!l)return;let u=s.get(l);if(u&&c.started_at<=u)return;let g=this.parseWorkflowCardMetadata(c.metadata);g.kind!=="workflow_card"&&g.kind!=="workflow_ui_instance"||(s.set(l,c.started_at),r.set(l,{taskId:c.id,workflowRunId:g.workflowRunId,raw:c.result??void 0}));};for(let l of this.resolveDbPaths()){if(!existsSync(l))continue;let c=L(l);try{let u=and(inArray(a.thread_id,e),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%'))),g=c.db.select({id:a.id,thread_id:a.thread_id,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(u,i):u).all();for(let I of g)d(I.thread_id,I);let f=and(isNull(a.thread_id),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%'))),m=c.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(f,i):f).all();for(let I of m){let S=this.extractThreadIdFromCommand(I.command);!S||!o.has(S)||d(S,I);}}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(a.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(inArray(a.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(inArray(a.status,s));let i=e.q??e.search;i&&r.push(like(a.prompt,`%${i}%`)),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt(a.started_at,e.to));let d=r.length>0?and(...r):void 0,l=n.db.select({count:sql`count(*)`}).from(a).where(d).get(),c=(e.sortDir??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at);return {rows:n.db.select().from(a).where(d).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 >= ${Ne}
|
|
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, ${
|
|
86
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${De}) AS INTEGER) < ${Pe})
|
|
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 >= ${Ne}
|
|
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, ${
|
|
109
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${De}) AS INTEGER) < ${Pe})
|
|
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 >= ${Ne}
|
|
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, ${
|
|
129
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${De}) AS INTEGER) < ${Pe})
|
|
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 >= ${Ne}
|
|
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, ${
|
|
151
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${De}) AS INTEGER) < ${Pe})
|
|
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 >= ${Ne}
|
|
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, ${
|
|
170
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${De}) AS INTEGER) < ${Pe})
|
|
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 >= ${Ne}
|
|
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, ${
|
|
197
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${De}) AS INTEGER) < ${Pe})
|
|
198
198
|
)
|
|
199
199
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
200
200
|
ELSE 0
|
|
@@ -209,117 +209,117 @@ ${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(
|
|
213
|
-
COALESCE(${
|
|
212
|
+
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new p("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(a).where(and(eq(a.id,e),eq(a.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:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(and(eq(a.agent_id,e.agentId),eq(a.workspace_id,e.workspaceId),sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(a.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(a.id,e),eq(a.status,"running"),eq(a.workspace_id,r)):and(eq(a.id,e),eq(a.status,"running"));o.db.update(a).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 d=L(i);try{let l=n?and(like(a.prompt,`%${e}%`),eq(a.workspace_id,n)):like(a.prompt,`%${e}%`),c=d.db.select().from(a).where(l).orderBy(asc(a.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{d.close();}}return s}getProviderUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=$r(),i=sql`
|
|
213
|
+
COALESCE(${a.input_tokens}, 0)
|
|
214
214
|
+ CASE
|
|
215
|
-
WHEN ${
|
|
215
|
+
WHEN ${a.started_at} >= ${Ne}
|
|
216
216
|
AND (
|
|
217
|
-
${
|
|
218
|
-
OR (${
|
|
219
|
-
OR (${
|
|
217
|
+
${a.crewx_version} IS NULL
|
|
218
|
+
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
219
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${De}) AS INTEGER) < ${Pe})
|
|
220
220
|
)
|
|
221
|
-
THEN COALESCE(${
|
|
221
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
222
222
|
ELSE 0
|
|
223
223
|
END
|
|
224
|
-
`,
|
|
224
|
+
`,d=r?sql`WHERE ${a.status} IN ('completed', 'success') AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${a.status} IN ('completed', 'success') AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return o.db.all(sql`
|
|
225
225
|
SELECT
|
|
226
226
|
${s} AS provider,
|
|
227
227
|
COUNT(*) AS total_tasks,
|
|
228
228
|
COALESCE(SUM(${i}), 0) AS input_tokens,
|
|
229
|
-
COALESCE(SUM(${
|
|
230
|
-
COALESCE(SUM(${
|
|
231
|
-
COALESCE(SUM(${
|
|
232
|
-
COALESCE(SUM(${
|
|
233
|
-
MAX(${
|
|
234
|
-
FROM ${
|
|
235
|
-
${
|
|
229
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
230
|
+
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
231
|
+
COALESCE(SUM(${a.cost_usd}), 0) AS cost_usd,
|
|
232
|
+
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
233
|
+
MAX(${a.completed_at}) AS last_active_at
|
|
234
|
+
FROM ${a}
|
|
235
|
+
${d}
|
|
236
236
|
GROUP BY ${s}
|
|
237
|
-
ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${
|
|
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
|
|
239
|
-
COALESCE(${
|
|
237
|
+
ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${a.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=$r(),i=sql`
|
|
239
|
+
COALESCE(${a.input_tokens}, 0)
|
|
240
240
|
+ CASE
|
|
241
|
-
WHEN ${
|
|
241
|
+
WHEN ${a.started_at} >= ${Ne}
|
|
242
242
|
AND (
|
|
243
|
-
${
|
|
244
|
-
OR (${
|
|
245
|
-
OR (${
|
|
243
|
+
${a.crewx_version} IS NULL
|
|
244
|
+
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
245
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${De}) AS INTEGER) < ${Pe})
|
|
246
246
|
)
|
|
247
|
-
THEN COALESCE(${
|
|
247
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
248
248
|
ELSE 0
|
|
249
249
|
END
|
|
250
|
-
`,
|
|
250
|
+
`,d=r?sql`WHERE ${a.status} IN ('completed', 'success') AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${a.status} IN ('completed', 'success') AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,l=o.db.all(sql`
|
|
251
251
|
SELECT
|
|
252
|
-
${
|
|
252
|
+
${a.model} AS model,
|
|
253
253
|
${s} AS provider,
|
|
254
254
|
COUNT(*) AS total_tasks,
|
|
255
255
|
COALESCE(SUM(${i}), 0) AS input_tokens,
|
|
256
|
-
COALESCE(SUM(${
|
|
257
|
-
COALESCE(SUM(${
|
|
258
|
-
COALESCE(SUM(${
|
|
259
|
-
COALESCE(SUM(${
|
|
260
|
-
MAX(${
|
|
261
|
-
FROM ${
|
|
262
|
-
${
|
|
263
|
-
GROUP BY ${
|
|
264
|
-
`),c=new Map;for(let u of l){let g=
|
|
256
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
257
|
+
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
258
|
+
COALESCE(SUM(${a.cost_usd}), 0) AS cost_usd,
|
|
259
|
+
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
260
|
+
MAX(${a.completed_at}) AS last_active_at
|
|
261
|
+
FROM ${a}
|
|
262
|
+
${d}
|
|
263
|
+
GROUP BY ${a.model}, ${s}
|
|
264
|
+
`),c=new Map;for(let u of l){let g=br(u.model??""),f=JSON.stringify([u.provider,g]),m=c.get(f);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(f,{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 ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return o.db.all(sql`
|
|
265
265
|
SELECT
|
|
266
|
-
${
|
|
267
|
-
${
|
|
268
|
-
${
|
|
269
|
-
${
|
|
270
|
-
${
|
|
271
|
-
${
|
|
272
|
-
FROM ${
|
|
266
|
+
${a.thread_id} AS thread_id,
|
|
267
|
+
${a.agent_id} AS agent_id,
|
|
268
|
+
${a.started_at} AS started_at,
|
|
269
|
+
${a.status} AS status,
|
|
270
|
+
${a.error} AS error,
|
|
271
|
+
${a.exit_code} AS exit_code
|
|
272
|
+
FROM ${a}
|
|
273
273
|
${s}
|
|
274
|
-
ORDER BY ${
|
|
275
|
-
`).map(
|
|
276
|
-
COALESCE(${
|
|
274
|
+
ORDER BY ${a.started_at} ASC
|
|
275
|
+
`).map(d=>({threadId:d.thread_id,agentId:d.agent_id,startedAt:d.started_at,status:d.status,error:d.error,exitCode:d.exit_code}))}catch(s){throw new p("DB_ERROR","Failed to get tasks for report",s)}finally{o.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let o=this.openHandle(false);try{let s=sql`
|
|
276
|
+
COALESCE(${a.input_tokens}, 0)
|
|
277
277
|
+ CASE
|
|
278
|
-
WHEN ${
|
|
278
|
+
WHEN ${a.started_at} >= ${Ne}
|
|
279
279
|
AND (
|
|
280
|
-
${
|
|
281
|
-
OR (${
|
|
282
|
-
OR (${
|
|
280
|
+
${a.crewx_version} IS NULL
|
|
281
|
+
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
282
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${De}) AS INTEGER) < ${Pe})
|
|
283
283
|
)
|
|
284
|
-
THEN COALESCE(${
|
|
284
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
285
285
|
ELSE 0
|
|
286
286
|
END
|
|
287
|
-
`,i=r?sql`WHERE ${
|
|
287
|
+
`,i=r?sql`WHERE ${a.status} IN ('completed', 'success') AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${a.status} IN ('completed', 'success') AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,d=o.db.all(sql`
|
|
288
288
|
SELECT
|
|
289
|
-
${
|
|
290
|
-
${
|
|
289
|
+
${a.caller_agent_id} AS caller_agent_id,
|
|
290
|
+
${a.agent_id} AS agent_id,
|
|
291
291
|
COUNT(*) AS task_count,
|
|
292
292
|
COALESCE(SUM(${s}), 0) AS input_tokens,
|
|
293
|
-
COALESCE(SUM(${
|
|
294
|
-
FROM ${
|
|
293
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens
|
|
294
|
+
FROM ${a}
|
|
295
295
|
${i}
|
|
296
|
-
GROUP BY ${
|
|
297
|
-
ORDER BY task_count DESC, ${
|
|
298
|
-
LIMIT ${
|
|
299
|
-
`),l=
|
|
296
|
+
GROUP BY ${a.caller_agent_id}, ${a.agent_id}
|
|
297
|
+
ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
|
|
298
|
+
LIMIT ${Rn+1}
|
|
299
|
+
`),l=d.length>Rn;return {edges:d.slice(0,Rn).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(a.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(inArray(a.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(inArray(a.status,e.statuses)),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt(a.started_at,e.to));let o=r.length>0?and(...r):void 0,s=(e.order??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at),i={id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id};return e.limit?n.db.select(i).from(a).where(o).orderBy(s).limit(e.limit).all():n.db.select(i).from(a).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(a.thread_id),isNull(a.parent_task_id),isNull(a.caller_agent_id),or$1(isNull(a.platform),ne$1(a.platform,"workflow")),or$1(isNull(a.metadata),and(notLike(a.metadata,'%"kind":"workflow_card"%'),notLike(a.metadata,'%"kind":"workflow_ui_instance"%'))),or$1(isNull(a.metadata),notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(a.workspace_id,e.workspaceId)),e.from&&s.push(gte(a.started_at,e.from)),e.to&&s.push(lt(a.started_at,e.to));let i=n.db.select({id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id}).from(a).where(and(...s)).orderBy(asc(a.started_at),asc(a.id)).all(),d=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=d.get(c.thread_id);g?g.push(u):d.set(c.thread_id,[u]);}let l=[];for(let[c,u]of d){let g=u.filter(f=>f.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,f=u.turns[u.turns.length-1].startedAt;return g<f?1:g>f?-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 Le=class extends z{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};function Re(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function Ie(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 Ur="[[crewx:delegation-result ",ki="[[crewx:delegation-result";var yi=new Set(["schema","taskId","agentId","isError"]);function Ti(t){let e=wi(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>Ri(s.value)),r=Ei(e);return {result:n.length===1&&n[0].index===r?Ii(n[0].line.value):null,resultPreview:xi(e,n),hasReservedLine:n.length>0}}function Me(t,e){let n=Ti(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function wi(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 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:["minimal","low","medium","high","xhigh","max","ultra"],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-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{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-6-astra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["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
|
|
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{}if(n.length>0)return n[n.length-1];if(r)return r}var
|
|
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,
|
|
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 Ei(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Ri(t){return t.trimStart().startsWith(ki)}function Ii(t){let e=t.trim();if(!e.startsWith(Ur)||!e.endsWith("]]"))return null;let n=e.slice(Ur.length,-2);if(!n)return null;try{return vi(JSON.parse(n))}catch{return null}}function vi(t){return Ai(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Ai(t){if(!Si(t)||Object.keys(t).some(r=>!yi.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?Fr(t.taskId)&&Fr(t.agentId):t.isError===true}function xi(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 Fr(t){return typeof t=="string"&&t.trim().length>0}function Si(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ve(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 qr=["none","minimal","low","medium","high","xhigh","max","ultra"],Wt={claude:["low","medium","high","xhigh","max"],codex:["minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]};var Sn={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-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{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-6-astra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["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(Sn).map(([t,e])=>[t,e.models]));var Oi=[{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]"}],bi={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};function On(t){return bi[t]??t}var Ci=new Map(Oi.map(({baseModelId:t,catalogModelId:e})=>[t,e]));function Ni(t){return Ci.get(t)??t}var Di=[{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"}],Pi=new Map(Di.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));function bn(t){if(!t)return {};let e=Pi.get(t);return e?{...e}:{model:t}}function Cn(t,e){return t==="antigravity"||t==="cli/antigravity"?bn(e):e===void 0?{}:{model:Ni(e)}}var Li={};function Mi(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Ge(t){return zt(t).models}function zt(t){return Li[t]??Sn[t]??Mi()}function yt(t,e){let n=zt(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Cn(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Br(t){return zt(t).modelOverrides}function jr(){return Ge("claude")}function Gr(){return Ge("codex")}function Wr(){return Ge("copilot")}function zr(){return Ge("antigravity")}var $i={auto:"default"};function Vr(t){return $i[t]??t}var Hi=new Set(qr);function Vt(t,e){return (Wt[t]??[]).includes(e)}function We(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Hi.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Kr(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 Jr(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 Yr(t){return !t||!Vt("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Xr(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Vr(t);return e.has(n)?["--permission-mode",n]:[]}function Qr(t){return t?Vt("claude",t)?["--effort",t]:[]:[]}var Ui=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);function Zr(t){return t==="default"?[]:t&&Ui.has(t)?["--permission-mode",t]:[]}function eo(t){return t===true?["--always-approve"]:[]}function to(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 no(t){return t?Vt("grok",t)?["--effort",t]:[]:[]}function ro(t){if(!t)return [];switch(On(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function oo(t){return t?Vt("antigravity",t)?["--effort",t]:[]:[]}function Fi(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 qi(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,d="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,l=i!==void 0?i:d??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:l}}function Bi(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 so(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 d=i.message,l=d?.id,c=d?.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 f=d?.model;typeof f=="string"&&f&&(n=f);}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 nt(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=Bi(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=Fi(o)??qi(o);i&&(e=i);}catch{}return n||(e??void 0)}function pe(t,e){if(typeof t!="object"||t===null||Array.isArray(t))return e;let n=t.timestamp;return typeof n!="string"||!Number.isFinite(Date.parse(n))?e:new Date(n).toISOString()}var ji=new Set(["tool_progress"]);function io(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 Nn={command:"claude",meta:{displayName:"Claude",models:jr(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=We(e.model),s=e.effort??o,i=Xr(e.mode),d=Qr(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,...d,...l,...g],stdinMessage:t}:{args:["--output-format","stream-json","--verbose",...c,...i,...d,...l,...g],stdinMessage:t}}return {args:["-p","--output-format","stream-json","--verbose",...c,...i,...d,...l],stdinMessage:t}},extractText(t){return io(t)??t.trim()},extractPartialText(t){return io(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 Le(`Claude rate limit: ${n.rateLimitType??"unknown"} (status: ${n.status})`)}if(e.error==="rate_limit"){let n=Gi(e);return new Le(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(Wi(n))return new Le(`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,d=o.modelUsage,l=d?Object.keys(d)[0]??null:null;return {usage:i,model:l}}}catch{}let n=so(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=pe(n,e??new Date().toISOString()),d=[];for(let l of s){let c=zi(i,l);c&&d.push(c);}return d},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?ji.has(r):!1}catch{return false}}};function Gi(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{}if(n.length>0)return n[n.length-1];if(r)return r}var
|
|
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(
|
|
313
|
-
`).flatMap(
|
|
314
|
-
`),o=r.length>
|
|
315
|
-
`).flatMap(
|
|
316
|
-
`).flatMap(
|
|
317
|
-
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>
|
|
318
|
-
`)??"";if(!c.trim())return;let u=
|
|
308
|
+
`):""}function Wi(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function zi(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=ve(s);return r==="Bash"&&Re(i)?Ie(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(d=>d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
|
|
309
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...Me(i,r)}}return null}var Vi=new Set(["interactive","plan","autopilot"]);function ao(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 Dn={command:"copilot",meta:{displayName:"Copilot",models:Wr()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&Vi.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Wt.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){return ao(t)??t.trim()},extractPartialText(t){return ao(t)},parseResultMeta(t){let e=nt(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=pe(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let d=String(o.toolName||""),l=o.arguments,c=ve(l);return (d==="bash"||d==="Bash")&&Re(c)?[Ie(s,c,i)]:[{timestamp:s,type:"tool_use",toolName:d,toolInput:c,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let d=o.error;if(d)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Me(String(d.message||""),true)}];let l=o.result,c=String(l?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Me(c,false)}]}if(r==="assistant.message"){let d=String(o.content||"");return d?[{timestamp:s,type:"text",content:d}]:[]}return []}};var Ki=new Set(["turn.started","turn.completed","item.updated"]);function Ji(t){let e=[],n=0,r=false,o=false,s=0;for(let d=0;d<t.length;d++){let l=t[d];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,d+1).trim();c&&e.push(c),s=d+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function Yi(t){return t[0]==="exec"?t.slice(1):t}function lo(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 Pn={command:"codex",meta:{displayName:"Codex",models:Gr(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=We(e.model),s=e.effort??o,i=e.resumeSessionId?Jr(e.mode):Kr(e.mode),d=Yr(s),l=r?["-m",r]:[],c=Yi(e.additionalArgs??[]),g=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...g,...i,...d,...l,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...g,...i,...d,...l,...c],stdinMessage:t}},extractText(t){return lo(t)??t.trim()},extractPartialText(t){return lo(t)},parseResultMeta(t){let e=nt(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=Ji(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 d=i.type;if(!d||!d.startsWith("item.")&&!d.startsWith("turn.")&&!d.startsWith("thread."))continue;let l=pe(i,n),c=i.item;if(c){if(d==="item.started"){r.push(...Xi(l,c));continue}if(d==="item.completed"){let u=Qi(l,c);u&&r.push(u);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?Ki.has(r):!1}catch{return false}}};function Xi(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return Re(r)?[Ie(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function Qi(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=Zi(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",...Me(r,o)}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=ve(o);return r==="Bash"&&Re(s)?Ie(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",...Me(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 Zi(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=ve(o);return r==="Bash"&&Re(s)?Ie(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var ea=new Set(["step_start","step_finish"]),rt="cli/opencode",po="OpenCode provider error",go=240,ta={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};function na(t){return t?ta[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Kt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function fo(t){let e=[],n=0,r=false,o=false,s=0;for(let d=0;d<t.length;d++){let l=t[d];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,d+1).trim();c&&e.push(c),s=d+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function ot(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ra(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);ot(i)?e.push(i):n=!0;continue}catch{}let s=fo(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 d=JSON.parse(i);ot(d)?e.push(d):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Xe(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,go).trim()}function ho(t){let e=ot(t.error)?t.error:void 0,n=e&&ot(e.data)?e.data:void 0,r=Xe(e?.name),o=Xe(n?.message)??Xe(e?.message)??Xe(t.message)??Xe(t.errorMessage)??Xe(t.error),s=Xe(t.ref),i=r&&o&&r!==o?`${r}: ${o}`:r??o??po;return (s?`${i} (ref: ${s})`:i).slice(0,go)}function co(t){let e=ra(t),n=[],r=null,o=0,s=[],i,d=false;for(let l of e.events){let c=typeof l.type=="string"?l.type:void 0;if(c){if(c==="text"){let u=ot(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(ho(l));continue}if(c==="step_finish"){d=true;let u=ot(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:d}}function mo(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Jt(){return new z("OpenCode returned no assistant output.",rt,{code:"EMPTY_OUTPUT",kind:"transient"})}function oa(){return new z("OpenCode emitted malformed JSON output.",rt,{code:"PROVIDER_CRASHED",kind:"transient"})}function uo(t,e){switch(mo(t)){case "length":return new z("OpenCode stopped because the context window was exceeded.",rt,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new z("OpenCode stopped because the content filter blocked the response.",rt,{code:"UNKNOWN",kind:"permanent"});case "error":return new z(e?`OpenCode error: ${e}`:`${po} while generating a response.`,rt,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var Ln={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Kt(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=na(e.mode);Kt(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!Kt(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!Kt(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let d;return !n&&!i&&!e.env?.OPENCODE_PERMISSION&&(d={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:d}},extractText(t){let e=co(t),n=e.errorMessages[0];if(n){let i=uo("error",n);if(i)throw i}let r=uo(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 Jt();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Jt();return e.resultText}if(e.malformed)throw oa();if(!e.hasTerminal)throw Jt();let s=mo(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Jt()},interpretExit(t,e,n=""){if(t===0)return null;let o=co(n).errorMessages[0];return o?new z(`OpenCode error: ${o}`,rt,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=nt(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=fo(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 d=pe(i,n),l=i.type;if(l){if(l==="text"){let u=i.part?.text;u&&r.push({timestamp:d,type:"text",content:u});continue}if(l==="tool_use"){let c=i.part;if(!c)continue;let u=String(c.tool||""),g=String(c.callID||""),f=c.state,m=String(f?.status||""),I=f?.input,S=ve(I);if(r.push({timestamp:d,type:"tool_use",toolName:u,toolUseId:g,toolInput:S}),m==="completed"&&f?.output!==void 0){let v=f.output,$=typeof v=="string"?v:JSON.stringify(v);r.push({timestamp:d,type:"tool_result",toolUseId:g,resultPreview:$,isError:false});}else m==="error"&&r.push({timestamp:d,type:"tool_result",toolUseId:g,resultPreview:String(f?.error||"tool error"),isError:true});continue}if(l==="error"){let c=ho(i);r.push({timestamp:d,type:"error",content:c,errorMessage: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?ea.has(r):!1}catch{return false}}};var Mn="antigravity";function Tt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function sa(t,e){if(!(t?Ge(Mn).some(s=>s.id===t):false)||!t)return e;let r=yt(Mn,t),o=Br(Mn)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var $n={command:"agy",meta:{displayName:"Antigravity",models:zr(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=We(e.model),s=bn(r),i=s.model,d=e.effort??o??s.effort,l=sa(i,d),c=e.additionalArgs??[],u=i&&!Tt(c,"--model")?["--model",i]:[],g=Tt(c,"--effort")?[]:oo(l),f=Tt(c,"--mode")||Tt(c,"--dangerously-skip-permissions")?[]:ro(e.mode),m=Tt(c,"--print")?[]:["--print",t];return {args:[...u,...g,...f,...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 Yt="cli/grok",aa=new Set(["available_commands","usage","end"]),da=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,la=/\u001b\[[0-?]*[ -/]*[@-~]/g,_o=20,ko=4e3,yo="\u2026";function st(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xt(t){return st(t)?t:void 0}function Y(t){return typeof t=="string"?t:void 0}function Qe(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function ca(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let d=t[i];if(n===-1){(d==="{"||d==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(d==="\\"&&o){s=true;continue}if(d==='"'){o=!o;continue}o||(d==="{"||d==="["?r+=1:(d==="}"||d==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function wt(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return st(n)?[n]:[]}catch{return ca(e).flatMap(n=>{try{let r=JSON.parse(n);return st(r)?[r]:[]}catch{return []}})}}function Et(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Rt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Rt).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
312
|
+
`):void 0}if(st(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=Rt(t[e]);if(n!==void 0)return n}}}function ua(t){if(t.rawOutput!==null&&t.rawOutput!==void 0)return Rt(t.rawOutput)??Et(t.rawOutput);if(t.content!==null&&t.content!==void 0)return Rt(t.content)??Et(t.content);if(t.result!==null&&t.result!==void 0)return Rt(t.result)??Et(t.result)}function wo(t){let e=Xt(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?Eo(n):"Grok CLI reported an error."}function Eo(t){return (t.replace(la,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function To(t){return da.test(t)}function pa(t){let e=Xt(t.modelUsage);return e?Object.keys(e)[0]??null:null}function ga(t){let e=Xt(t.usage);if(!e)return null;let n=Qe(e.cache_read_input_tokens);return {inputTokens:Qe(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Qe(e.output_tokens),costUsd:Qe(t.total_cost_usd)}}function fa(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
313
|
+
`).flatMap(wt)){if(i.type!=="usage")continue;let d=Xt(i.usage);if(!d)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=Qe(d.cache_read_input_tokens);e+=Qe(d.input_tokens)+c,n+=c,r+=Qe(d.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function ha(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,_o)){if(!st(s))continue;let i=Y(s.content)?.trim();if(!i)continue;let d=Y(s.status)?.trim(),l=Y(s.priority)?.trim(),c=[d?`status=${d}`: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>_o&&n.push(yo);let r=n.join(`
|
|
314
|
+
`),o=r.length>ko?`${r.slice(0,ko-1)}${yo}`:r;return [{timestamp:t,type:"info",content:o}]}function ma(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 ha(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:Et(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:ua(e),isError:r!=="completed"||e.isError===true}]}if(n==="error"){let r=wo(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var Hn={command:"grok",createSessionId:()=>randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=We(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],d=n?Ge("grok").some(de=>de.id===n):false,l=n&&d?yt("grok",n):[],c=!o||l.length===0||l.includes(o)?o:void 0,u=no(c),g=e.additionalArgs??[],f=de=>g.some(te=>te===de||te.startsWith(`${de}=`)),m=e.providerOptions,I=m?.alwaysApprove,S=m?.sandbox,v=f("--permission-mode")?[]:Zr(e.mode),$=f("--always-approve")?[]:eo(I),j=f("--sandbox")?[]:to(S);return {args:["--no-auto-update",...s,"--single",t,"--output-format","streaming-json","--no-alt-screen",...i,...u,...v,...$,...j,...g]}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
315
|
+
`).flatMap(wt))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 wt(t))if(e.type==="error"){let n=wo(e);return To(Et(e))?new Le(n,Yt):new z(n,Yt)}return null},interpretExit(t,e){if(t===0)return null;let n=Eo(e)||`Grok CLI exited with code ${t}.`;return To(e)?new Le(n,Yt):new z(n,Yt)},parseResultMeta(t){let n=t.split(`
|
|
316
|
+
`).flatMap(wt).find(r=>r.type==="end");return n?{usage:ga(n),model:pa(n)}:{usage:fa(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return wt(t).flatMap(r=>ma(pe(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return st(n)&&typeof n.type=="string"?aa.has(n.type):!1}catch{return false}}};var Ro={codex:Pn,claude:Nn,opencode:Ln,antigravity:$n,copilot:Dn,grok:Hn};function Io(t){if(t.startsWith("cli/"))return Ro[t.slice(4)]}function _a(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?va[e]:void 0;return s?s(r,o):Object.values(Ao).some(i=>i(r,o))}function Qt(t,e){let n=t.split(`
|
|
317
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>_a(r,e))}function ie(t){return typeof t=="object"&&t!==null}function vo(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 ka(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:vo(t,e)}function ya(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 Ta(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 wa(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||ie(t.part)||e==="result"&&typeof t.result=="string")}function Ea(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?ie(t.data):e==="result"?typeof t.result=="string":false}function Ra(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 Ia(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 Ao={claude:vo,codex:ya,opencode:Ta,copilot:Ea,gemini:Ra},va={...Ao,claude:ka,opencode:wa,grok:Ia,antigravity:()=>false};var xa=200,Sa=200;function Oa(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 ba(t){let e=t instanceof p?t.code:void 0,n=t instanceof p?t.cause:t,r=Oa(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function So(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Ca(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Na(t){if(!t)return {};try{let e=JSON.parse(t);return Ca(e)?e:{}}catch{return {}}}function Oo(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Fn=class extends Ue{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 Gt({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),s=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))?or(r):null,i=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let l=d.callerAgentId??null,c=d.parentTaskId??null,u=d.rootTraceId??d.traceId,g=d.metadata?JSON.stringify(d.metadata):JSON.stringify({provider:d.provider??"cli/claude"});n.startTask({id:d.traceId,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:d.pid??null,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:i,codingAgentCommand:d.codingAgentCommand??null,workspaceId:d.workspaceId??s,projectId:d.projectId??null,callerAgentId:l,parentTaskId:c,traceId:u,metadata:g,threadId:d.threadId??null});}catch{}}),e.on("task:output",d=>{try{this.enqueueLog(d.traceId,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(l){let c={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(l,[c],So(c));}}),e.on("task:end",d=>{try{this.flushTaskLogs(d.traceId);let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null,c=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{}}):null,u=d.result??null,g=!1;if(d.error&&(!u||u.trim()==="")){let f=this.recoverPartialResult(d.traceId,d,l);f&&(u=f,g=!0);}n.finishTask({id:d.traceId,status:d.error?"failed":"success",result:u,error:c,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch: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+=So(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>=xa){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));},Sa);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo?.getTask(e);if(!o||o.status!=="running"||Oo(o.run_epoch)!==Oo(r))return;let s=Na(o.metadata),i=typeof s.provider=="string"?s.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!i)return;let d=Io(i);if(!d?.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=d.extractPartialText(c);return !u||!u.trim()||Qt(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=ba(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 it=class extends p{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function It(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function $a(t){let n=It(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 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?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new p("NOT_FOUND","Database not found");let r=L(n);if(e)try{he(r.db,n);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,n){return e.db.select({id:et.id}).from(et).where(eq(et.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
319
319
|
SELECT 1 FROM tasks parent
|
|
320
320
|
WHERE parent.id = ${e}.parent_task_id
|
|
321
321
|
AND parent.thread_id = ${e}.thread_id
|
|
322
|
-
)`)}findAllThreads(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!existsSync(s))continue;let i=
|
|
322
|
+
)`)}findAllThreads(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!existsSync(s))continue;let i=L(s);try{let d=e?eq(h.workspace_id,e):void 0,l=i.db.select().from(h).where(d).orderBy(desc(h.updated_at)).all();for(let c of l)r.has(c.id)||(r.add(c.id),o.push(c));}catch(d){throw new p("DB_ERROR","Failed to find all threads",d)}finally{i.close();}}return o}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let d=L(i);try{let l=or$1(inArray(h.id,e),inArray(h.title,e)),c=n?and(l,eq(h.workspace_id,n)):l,u=d.db.select().from(h).where(c).orderBy(desc(h.updated_at)).all();for(let g of u)o.has(g.id)||(o.add(g.id),s.push(g));}catch(l){throw new p("DB_ERROR","Failed to find threads by ids or titles",l)}finally{d.close();}}return s}findThreadById(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=L(o);try{let i=eq(h.id,e),d=n?and(i,eq(h.workspace_id,n)):i,l=s.db.select().from(h).where(d).limit(1).get()??void 0;if(l)return l}catch(i){throw new p("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=L(o);try{let i=eq(h.id,e),d=n?and(i,eq(h.workspace_id,n)):i;if(s.db.select({id:h.id}).from(h).where(d).limit(1).get())return !0}catch(i){throw new p("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),o=0,s=0,i=0,d=0,l=0,c=new Set;for(let u of r){if(!existsSync(u))continue;let g=L(u);try{let f=g.db.get(sql`
|
|
323
323
|
SELECT
|
|
324
324
|
count(*) AS cnt,
|
|
325
325
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -330,13 +330,13 @@ ${r.join(`
|
|
|
330
330
|
WHERE child.thread_id = ${e}
|
|
331
331
|
AND ${this.topLevelTaskPredicateSql()}
|
|
332
332
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
333
|
-
`);
|
|
333
|
+
`);f&&(o+=f.cnt,s+=f.total_input,i+=f.total_output,d+=f.total_cached,l+=f.total_cost);let m=g.db.all(sql`
|
|
334
334
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
335
335
|
WHERE child.thread_id = ${e}
|
|
336
336
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
337
337
|
AND ${this.topLevelTaskPredicateSql()}
|
|
338
338
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
339
|
-
`);for(let
|
|
339
|
+
`);for(let I of m)c.add(I.agent_id);}catch(f){throw new p("DB_ERROR","Failed to aggregate task stats",f)}finally{g.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:d,costUsd:l,agentIds:Array.from(c)}}findTopLevelTasks(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[];for(let d of o){if(!existsSync(d))continue;let l=L(d);try{let c;r!==void 0?c=l.db.all(sql`
|
|
340
340
|
SELECT * FROM (
|
|
341
341
|
SELECT child.*,
|
|
342
342
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -353,7 +353,7 @@ ${r.join(`
|
|
|
353
353
|
AND ${this.topLevelTaskPredicateSql()}
|
|
354
354
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
355
355
|
ORDER BY child.started_at ASC
|
|
356
|
-
`);for(let u of c)s.has(u.id)||(s.add(u.id),i.push(u));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}if(r!==void 0&&o.length>1){let
|
|
356
|
+
`);for(let u of c)s.has(u.id)||(s.add(u.id),i.push(u));}catch(c){throw new p("DB_ERROR","Failed to find top-level tasks",c)}finally{l.close();}}if(r!==void 0&&o.length>1){let d=new Map;for(let l of i){let c=l.agent_id??"";d.has(c)||d.set(c,[]),d.get(c).push(l);}i=[];for(let l of d.values())l.sort((c,u)=>(u.started_at??"").localeCompare(c.started_at??"")),i.push(...l.slice(0,r));i.sort((l,c)=>(l.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let d=L(i);try{let l=eq(a.thread_id,e),c=n?and(l,eq(a.workspace_id,n)):l,u=d.db.select().from(a).where(c).orderBy(asc(a.started_at)).all();for(let g of u)o.has(g.id)||(o.add(g.id),s.push(g));}catch(l){throw new p("DB_ERROR","Failed to find all tasks for thread",l)}finally{d.close();}}return s}findTaskById(e,n,r){let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=L(s);try{let d=and(eq(a.id,n),eq(a.thread_id,e)),l=r?and(d,eq(a.workspace_id,r)):d,c=i.db.select().from(a).where(l).limit(1).get();if(!c)continue;let u=i.db.select().from(a).where(eq(a.parent_task_id,c.id)).orderBy(asc(a.started_at)).all();return {task:c,children:u}}catch(d){throw new p("DB_ERROR","Failed to find task by id",d)}finally{i.close();}}}batchFetchTasksQuery(e,n){return sql`
|
|
357
357
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
358
358
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
359
359
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -363,7 +363,7 @@ ${r.join(`
|
|
|
363
363
|
AND ${this.topLevelTaskPredicateSql()}
|
|
364
364
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
365
365
|
ORDER BY child.started_at ASC
|
|
366
|
-
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=
|
|
366
|
+
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=L(s);try{let d=i.db.all(this.batchFetchTasksQuery(e,n));for(let l of d){let c=l.thread_id;r.has(c)||r.set(c,[]),r.get(c).push(l);}}catch(d){throw new p("DB_ERROR","Failed to batch fetch tasks",d)}finally{i.close();}}return r}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=L(o);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(d=>d.detail)}finally{s.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=eq(h.id,e),i=r?and(s,eq(h.workspace_id,r)):s;if(!o.db.select({id:h.id}).from(h).where(i).limit(1).get())return;o.db.update(h).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(h.id,e)).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,n){let r=this.openHandle(true);try{let o=n.workspaceId?this.validateWorkspaceId(r,n.workspaceId):null,s=new Date().toISOString();if(r.db.select({id:h.id,message_count:h.message_count}).from(h).where(eq(h.id,e)).limit(1).get()){let d={updated_at:s};n.title!==void 0&&(d.title=n.title),n.titleLocked!==void 0&&(d.title_locked=n.titleLocked?1:0),r.db.update(h).set(d).where(eq(h.id,e)).run();}else r.db.insert(h).values({id:e,platform:n.platform,workspace_id:o,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to upsert thread",o)}finally{r.close();}}ensureThread(e,n,r){let o=this.openHandle(true);try{let s=r?this.validateWorkspaceId(o,r):null,i=o.db.select({id:h.id,platform:h.platform,workspace_id:h.workspace_id}).from(h).where(eq(h.id,e)).limit(1).get();if(i){s&&!i.workspace_id&&o.db.update(h).set({workspace_id:s}).where(eq(h.id,e)).run();return}let d=new Date().toISOString();o.db.insert(h).values({id:e,platform:n,workspace_id:s,message_count:0,created_at:d,updated_at:d}).run();}catch(s){throw s instanceof p?s:new p("DB_ERROR","Failed to ensure thread",s)}finally{o.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(d=>{let c=d.select({message_count:h.message_count}).from(h).where(eq(h.id,e)).limit(1).get()?.message_count===0;return d.run(sql`
|
|
367
367
|
UPDATE threads
|
|
368
368
|
SET first_message = COALESCE(first_message, ${n}),
|
|
369
369
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
@@ -371,11 +371,11 @@ ${r.join(`
|
|
|
371
371
|
message_count = message_count + 1,
|
|
372
372
|
updated_at = ${s}
|
|
373
373
|
WHERE id = ${e}
|
|
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
|
+
`),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(h).set({last_message:n,updated_at:s}).where(eq(h.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(h).set(o).where(eq(h.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 it("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new it("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 it("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 it("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let l=r?and(eq(h.id,e),eq(h.workspace_id,r)):eq(h.id,e);return d.db.transaction(c=>{let u=c.select({metadata:h.metadata}).from(h).where(l).get();if(!u)return null;let g=It(u.metadata),f=g.threadTitle,m=f&&typeof f=="object"&&!Array.isArray(f)?{...f}:{};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 I=Object.keys(g).length>0?JSON.stringify(g):null,S=new Date().toISOString();c.update(h).set({metadata:I,updated_at:S}).where(l).run();let v=c.select({metadata:h.metadata}).from(h).where(l).get();if(!v)throw new p("DB_ERROR","Thread-title metadata update could not be read back");let $=$a(v.metadata);return {threadId:e,priority:$.priority,state:$.state}},{behavior:"immediate"})}catch(l){throw l instanceof p?l:new p("DB_ERROR","Failed to patch thread-title metadata",l)}finally{d.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?and(eq(h.id,e),eq(h.workspace_id,n)):eq(h.id,e);return r.db.transaction(s=>{let i=s.select({pinned:h.pinned,metadata:h.metadata}).from(h).where(o).get();if(!i)return null;let d=i.pinned?0:1,l=It(i.metadata);if(d){let c=n?and(eq(h.pinned,1),eq(h.workspace_id,n)):eq(h.pinned,1),u=s.select({metadata:h.metadata}).from(h).where(c).all(),g=null;for(let f of u){let m=It(f.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(h).set({pinned:d,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(o).run(),{pinned:!!d}},{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(h.id,e[s]),eq(h.workspace_id,n)):eq(h.id,e[s]),d=o.select({metadata:h.metadata}).from(h).where(i).get();if(!d)continue;let l=It(d.metadata);l.pinOrder=s+1,o.update(h).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(h.id,e),eq(h.workspace_id,n)):eq(h.id,e),s=r.db.select({starred:h.starred}).from(h).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(h).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 d=n?and(eq(h.id,e),eq(h.workspace_id,n)):eq(h.id,e);return i.db.transaction(c=>{let u=c.select({metadata:h.metadata}).from(h).where(d).get();if(!u)return null;let g=u.metadata?JSON.parse(u.metadata):{},f=g.overdrive??{},m=o?.defaultTurns??f.defaultTurns??3,I=o?.updatedBy??"ui",S=new Date().toISOString(),v,$,j,de;switch(r){case "enable-count":{let te=o?.turns??m,He=o?.consumeCurrent?Math.max(te-1,0):te;v=He>0?"count":"off",$=He,j=!0,de="count";break}case "enable-latch":{v="latch",$=0,j=!0,de="latch";break}case "disable":{v="off",$=0,j=!1;break}default:{let te=f.state??"off",He=typeof f.remaining=="number"?f.remaining:0;if(te==="count"&&He>0){let b=He-1;b<=0?(v="off",$=0):(v="count",$=b),j=!0,de="count";}else te==="latch"?(v="latch",$=0,j=!0,de="latch"):(v="off",$=0,j=!1);break}}return g.overdrive={state:v,remaining:$,defaultTurns:m,updatedAt:S,updatedBy:I},c.update(h).set({metadata:JSON.stringify(g),updated_at:S}).where(d).run(),{applied:j,appliedMode:de,state:v,remaining:$}},{behavior:"immediate"})}catch(d){throw d instanceof p?d:new p("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};var qn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Ha(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+=qn[o%62]);}for(;n.length<t;)n+=qn[randomBytes(1)[0]%62];return n}function vt(t){return `${t}_${Ha(8)}`}function Po(t,e){let{createHash:n}=pt("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+=qn[i%62];return `${t}_${s}`}var Ua=["urgent","high","medium","low"],Fa=["investigating","in-progress","in-review","on-hold","done"],Lo="custom:";var qa=new Set(Ua),Ba=new Set(Fa);function Bn(t){return typeof t=="string"&&qa.has(t)}function jn(t){if(typeof t!="string")return false;if(Ba.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Lo))return false;let e=t.slice(Lo.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 Gn(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 Bn(r.priority)&&(o.priority=r.priority),jn(r.state)&&(o.state=r.state),o}function $o(t,e){let n=Mo(t)??{},r={...Gn(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 Va="regeneration_replaced";var Ka="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Ja="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Vn=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;}},Nt=class extends Vn{},Kn=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;}},Ya=new Set(vr),Xa=new Set(Ir),Qa=new Set(Ar),Za=new Set(xr),ed=50,Uo=100,Fo=280,qo=40,td=new Set(Sr),en=["queued","running"],nd=["success","completed","done","failed","error"];function zn(t){return td.has(t)}function D(t){throw new p("VALIDATION",t)}function fe(t){throw new p("NOT_FOUND",t)}function E(t,e){(typeof t!="string"||t.trim().length===0)&&D(`${e} is required`);}function xt(t={}){let e=t.actor??t,n=e.actorType??"system";return Ya.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 rd(t){E(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&E(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&&!Bn(t.priority)&&D(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!jn(t.state)&&D(`invalid state: ${String(t.state)}`);}function od(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??ed;return (!Number.isInteger(e)||e<1||e>Uo)&&D(`limit must be between 1 and ${Uo}`),e}function Jn(t){typeof t!="string"&&D("text is required");let e=t.trim();return e.length===0&&D("text must not be empty"),e.length>Fo&&D(`text must be at most ${Fo} characters`),e}function $e(t,e){return E(t??"",e),t}function Yn(t){Za.has(t)||D(`invalid highlight kind: ${String(t)}`);}function sd(t){Qa.has(t)||D(`invalid highlight source: ${String(t)}`);}function id(t){E(t.threadId,"threadId"),E(t.workspaceId,"workspaceId");let e=t.source??"manual";sd(e),Yn(t.kind);let n=Jn(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=$e(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=$e(r,"coversFromTaskId"),i=$e(o,"coversToTaskId"),d=t.sourceTaskId??s,l=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return $e(d??void 0,"sourceTaskId"),$e(l??void 0,"detectorVersion"),$e(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:d,detectorVersion:l,contentFingerprint:c}}function ad(t,e){(!t||typeof t!="object")&&D(`candidates[${e}] is required`),Yn(t.kind);let n=Jn(t.text),r=$e(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=$e(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=$e(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Po("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return E(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function dd(t){Array.isArray(t)||D("candidates must be an array"),t.length>qo&&D(`candidates must contain at most ${qo} items`);let e=new Map;for(let[n,r]of t.entries()){let o=ad(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function Ct(t){let e=Gn(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 ld(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 St(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${C.seq}), 0)`}).from(C).where(eq(C.thread_id,e)).get()?.maxSeq??0}function Ot(t,e){return !!t.select({id:C.id}).from(C).where(eq(C.thread_id,e)).limit(1).get()}function Ze(t,e){Xa.has(e.type)||D(`invalid thread event type: ${String(e.type)}`);let n=vt("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:ld(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 bt(t,e,n,r,o){let s=Ct(e);Ze(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 nn(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 tn(t,e,n,r,o,s,i){let d=o==="thread.highlight.created"?nn(e):{before:i?nn({...e,...i,id:e.id}):void 0,after:nn(e)};return Ze(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:d})}function cd(t,e,n,r,o,s){return Ze(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:nn(e),...s??{}}})}var rn=class extends ne{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!existsSync(n))throw new p("NOT_FOUND","Database not found");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=L(n);if(e)try{he(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=eq(h.id,n),s=r===void 0?o:r===null?and(o,isNull(h.workspace_id)):and(o,eq(h.workspace_id,r));return e.select().from(h).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(E(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:h.workspace_id}).from(h).where(eq(h.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(E(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?Ct(o):null}catch(o){throw o instanceof p?o:new p("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){rd(e);let n=xt(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||fe(`Thread ${e.threadId} not found`);let d=Ct(i),l=e.title!==void 0,c=l&&e.title!==d.title,u=l&&i.title_locked!==1,g=e.priority!==void 0&&e.priority!==d.priority,f=e.state!==void 0&&e.state!==d.state,m=c||g||f;if(!m&&!u)return d;let I=i.metadata;(g||f)&&(I=$o(i.metadata,{priority:e.priority,state:e.state}));let S={};if(m&&(S.metadata=I,S.updated_at=r),c&&(S.title=e.title),l&&(S.title_locked=1),s.update(h).set(S).where(e.workspaceId===void 0?eq(h.id,e.threadId):e.workspaceId===null?and(eq(h.id,e.threadId),isNull(h.workspace_id)):and(eq(h.id,e.threadId),eq(h.workspace_id,e.workspaceId))).run(),!m){let j={...i,title_locked:1};return Ct(j)}let v=St(s,i.id)+1;Ot(s,i.id)||(bt(s,i,n,r,v),v+=1),c&&(Ze(s,{threadId:i.id,seq:v,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),v+=1),g&&(Ze(s,{threadId:i.id,seq:v,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),v+=1),f&&Ze(s,{threadId:i.id,seq:v,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let $={...i,title:c?e.title:i.title,metadata:I,title_locked:l?1:i.title_locked,updated_at:r};return Ct($)},{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(E(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(E(e,"threadId"),E(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(and(eq(a.thread_id,e),eq(a.workspace_id,n),inArray(a.status,nd),or$1(isNull(a.parent_task_id),eq(a.parent_task_id,"")),sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(asc(a.started_at),asc(a.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){E(e.threadId,"threadId"),E(e.workspaceId,"workspaceId"),E(e.requestId,"requestId"),E(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&E(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||fe(`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 d=o.select().from(x).where(and(eq(x.thread_id,s.id),inArray(x.status,en))).orderBy(asc(x.requested_at),asc(x.id)).limit(1).get();if(d)throw new Kn(d);let l=e.runId??vt("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(E(e,"runId"),n!==void 0&&E(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(E(e,"threadId"),E(n,"workspaceId"),E(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){E(e,"runId"),n!==void 0&&E(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||fe(`Highlight regeneration run ${e} not found`),zn(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 d=s.select().from(x).where(eq(x.id,i.id)).get();if(!d)throw new p("DB_ERROR","Highlight regeneration run start did not return a row");return d},{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){E(e.runId,"runId"),E(e.errorCode,"errorCode"),e.workspaceId!==void 0&&E(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||fe(`Highlight regeneration run ${e.runId} not found`),zn(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,en))).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=Ka){E(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,en)).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){E(e.runId,"runId"),E(e.threadId,"threadId"),E(e.workspaceId,"workspaceId"),E(e.detectorVersion,"detectorVersion");let n=dd(e.candidates),r=xt(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let d=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!d||d.thread_id!==e.threadId)&&fe(`Highlight regeneration run ${e.runId} not found`),zn(d.status)||D(`invalid highlight regeneration status: ${d.status}`),d.status==="failed")throw new p("CONFLICT","Highlight regeneration run has already failed");if(d.status==="completed")return {run:d,deletedCount:0,createdCount:0,previousAutoCount:d.previous_auto_count??0,newAutoCount:d.new_auto_count??0};s=!0;let l=this.findThread(i,e.threadId,e.workspaceId);l||fe(`Thread ${e.threadId} not found`),d.detector_version!==e.detectorVersion&&D("detectorVersion does not match the regeneration run");let c=i.select().from(R).where(eq(R.thread_id,l.id)).orderBy(asc(R.created_at),asc(R.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??"")),f=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)),I=n.filter(b=>!m.has(b.contentFingerprint)),S=new Date().toISOString(),v=St(i,l.id)+1;Ot(i,l.id)||(bt(i,l,r,S,v),v+=1);for(let b of g)i.delete(R).where(eq(R.id,b.id)).run(),cd(i,b,r,S,v,{runId:e.runId,reason:Va}),v+=1;let $=0,j=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let b of I){let Qn=vt("thl");i.insert(R).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:S,updated_at:S,agent_id:j,source_task_id:b.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:b.contentFingerprint,dismissed_at:null}).run();let Zn=i.select().from(R).where(eq(R.id,Qn)).get();if(!Zn)throw new p("DB_ERROR","Regenerated highlight insert did not return a row");tn(i,Zn,r,S,"thread.highlight.created",v),v+=1,$+=1;}let te=i.select().from(R).where(eq(R.thread_id,l.id)).all().filter(b=>b.source==="auto"&&b.status==="active").length;Ze(i,{threadId:l.id,seq:v,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:S,payload:{runId:d.id,detectorVersion:e.detectorVersion,previousAutoCount:f,newAutoCount:te,deletedCount:g.length,createdCount:$}}),i.update(x).set({status:"completed",started_at:d.started_at??S,completed_at:S,error_code:null,previous_auto_count:f,new_auto_count:te}).where(and(eq(x.id,d.id),inArray(x.status,en))).run();let He=i.select().from(x).where(eq(x.id,d.id)).get();if(!He)throw new p("DB_ERROR","Highlight regeneration completion did not return a row");return {run:He,deletedCount:g.length,createdCount:$,previousAutoCount:f,newAutoCount:te}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Ja});}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;E(o.threadId,"threadId"),E(o.workspaceId,"workspaceId");let s=od(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 d=i.db.select({maxSeq:sql`COALESCE(MAX(${C.seq}), 0)`}).from(C).where(eq(C.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(C).where(and(eq(C.thread_id,o.threadId),lt(C.seq,o.beforeSeq))).orderBy(desc(C.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(C).where(and(eq(C.thread_id,o.threadId),sql`${C.seq} > ${o.afterSeq}`)).orderBy(asc(C.seq)).limit(s+1).all():l=i.db.select().from(C).where(eq(C.thread_id,o.threadId)).orderBy(desc(C.seq)).limit(s+1).all().reverse();let c=l.length>s,u=o.afterSeq!==void 0?l.slice(0,s):c?l.slice(1):l,g=!1,f=u[0];return f&&(g=!!i.db.select({id:C.id}).from(C).where(and(eq(C.thread_id,o.threadId),lt(C.seq,f.seq))).limit(1).get()),{items:u,latestSeq:d,hasMoreOlder:g}}catch(d){throw d instanceof p?d:new p("DB_ERROR","Failed to list thread timeline",d)}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=id(e),r=xt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);if(d||fe(`Thread ${e.threadId} not found`),n.source==="auto"){let f=i.select().from(R).where(and(eq(R.thread_id,e.threadId),eq(R.source_task_id,n.sourceTaskId),eq(R.detector_version,n.detectorVersion),eq(R.content_fingerprint,n.contentFingerprint))).orderBy(asc(R.created_at),asc(R.id)).limit(1).get();if(f)return f}let l=e.id??vt("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(R).values(c).run();let u=i.select().from(R).where(eq(R.id,l)).get();if(!u)throw new p("DB_ERROR","Highlight insert did not return a row");let g=St(i,d.id)+1;return Ot(i,d.id)||(bt(i,d,r,o,g),g+=1),tn(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){E(e.threadId,"threadId"),E(e.workspaceId,"workspaceId"),E(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&&Yn(e.kind);let n=e.text===void 0?void 0:Jn(e.text),r=xt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);d||fe(`Thread ${e.threadId} not found`);let l=i.select().from(R).where(and(eq(R.id,e.highlightId),eq(R.thread_id,d.id))).limit(1).get();if(l||fe(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new Nt(d.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new Nt(d.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,f=e.coversToTaskId??l.covers_to_task_id;(!u||g.length===0||f.length===0)&&D("highlight projection is incomplete");let m=c!==l.kind||u!==l.text||g!==l.covers_from_task_id||f!==l.covers_to_task_id,I=r.actorType==="user"&&l.source==="auto"&&m?"manual":l.source;if(!(m||I!==l.source))return l;let v=l.revision+1;i.update(R).set({source:I,kind:c,text:u,covers_from_task_id:g,covers_to_task_id:f,revision:v,updated_at:o}).where(and(eq(R.id,l.id),eq(R.revision,l.revision))).run();let $=i.select().from(R).where(eq(R.id,l.id)).get();if(!$)throw new p("DB_ERROR","Highlight update did not return a row");let j=St(i,d.id)+1;return Ot(i,d.id)||(bt(i,d,r,o,j),j+=1),tn(i,$,r,o,"thread.highlight.updated",j,l),$},{behavior:"immediate"})}catch(i){throw i instanceof p?i:new p("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){E(e.threadId,"threadId"),E(e.workspaceId,"workspaceId"),E(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&D("expectedRevision must be a non-negative integer");let n=xt(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||fe(`Thread ${e.threadId} not found`);let d=s.select().from(R).where(and(eq(R.id,e.highlightId),eq(R.thread_id,i.id))).limit(1).get();if(d||fe(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new Nt(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let l=d.revision+1;s.update(R).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(and(eq(R.id,d.id),eq(R.revision,d.revision))).run();let c=s.select().from(R).where(eq(R.id,d.id)).get();if(!c)throw new p("DB_ERROR","Highlight dismissal did not return a row");let u=St(s,i.id)+1;return Ot(s,i.id)||(bt(s,i,n,r,u),u+=1),tn(s,c,n,r,"thread.highlight.deleted",u,d),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(E(e,"threadId"),E(n,"workspaceId"),r.taskId!==void 0&&E(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&E(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&E(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(R).where(and(eq(R.thread_id,e),eq(R.status,"active"))).orderBy(asc(R.created_at),asc(R.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(sql`
|
|
375
375
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
376
376
|
ORDER BY started_at ASC, id ASC
|
|
377
|
-
`),l=new Map(
|
|
377
|
+
`),l=new Map(d.map((f,m)=>[f.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(f=>{let m=l.get(f.covers_from_task_id),I=l.get(f.covers_to_task_id);if(m===void 0||I===void 0)return !1;let S=Math.min(m,I),v=Math.max(m,I);return !(c!==void 0&&(c<S||c>v)||u!==void 0&&v<u||g!==void 0&&S>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;}},jo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function yd(){let t=randomBytes(16),e="";for(let n of t)e+=jo[n%jo.length];return e.slice(0,12)}function Go(){return `c_${yd()}`}function Td(t){return typeof t=="string"&&yn.includes(t)}function wd(t){return typeof t=="string"&&Tn.includes(t)}function ct(t){if(!Td(t))throw new F("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Wo(t){if(!wd(t))throw new F("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function zo(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 ut(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 on(t){if(typeof t!="string"||t.trim().length===0)throw new F("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function ze(t,e){return and(eq(k.code_group,t),or$1(isNull(k.workspace_id),eq(k.workspace_id,e)))}var sn=class extends ne{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!existsSync(n))throw new p("NOT_FOUND","Database not found");e&&mkdirSync(dirname(n),{recursive:true});let r=L(n);if(e)try{he(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(ct(e),ut(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(k).where(and(ze(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(ct(e),ut(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(k).where(ze(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(ct(n),ut(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)on(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(ze(n,e.workspaceId)).all(),i=s.filter(m=>m.is_archived===0),d=new Set(s.map(m=>m.code)),l=new Set(i.map(m=>m.code)),c=e.codes.find(m=>!d.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 I=u.get(m);if(!I)throw new F("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${m}`);return I}),f;for(let[m,I]of g.entries())I.sort_order!==m&&(f??=new Date().toISOString(),o.update(k).set({sort_order:m,updated_at:f}).where(and(eq(k.code_group,n),eq(k.code,I.code))).run());return o.select().from(k).where(ze(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(ct(e),on(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){ut(e.workspaceId);let n=zo(e.name);Wo(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:k.code}).from(k).where(and(ze("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(ze("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),l=Go();for(;o.select({code:k.code}).from(k).where(and(eq(k.code_group,"THREAD_STATE"),eq(k.code,l))).limit(1).get();)l=Go();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:d,updated_at:d}).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(ct(e.group),on(e.code),ut(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:zo(e.name);e.color!==void 0&&Wo(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(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(ze(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 d=o.select().from(k).where(and(eq(k.code_group,e.group),eq(k.code,e.code))).limit(1).get();if(!d)throw new p("DB_ERROR","Updated common code could not be read back");return d},{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(ct(e),on(n),ut(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 d=i.select().from(k).where(and(eq(k.code_group,e),eq(k.code,n))).limit(1).get();if(!d)throw new F("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(d.is_builtin===1)throw new F("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(d,r),!o&&d.code_name!==null&&i.select({code:k.code}).from(k).where(and(ze(e,r),eq(k.is_archived,0),eq(k.code_name,d.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: ${d.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 Id(t){return t.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
378
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(`
|
|
379
|
-
`).trim()}function
|
|
380
|
-
`):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=
|
|
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:
|
|
379
|
+
`).trim()}function vd(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 Ad(t,e,n){if(!t||e==="failed"&&Qt(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=Id(r);}return r}var an=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Zt({dbPath:this.dbPath})}getThreadHistoryRepo(){return new rn({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),d=new Set(["queued","cancelled"]);i=i.filter(g=>(!g.status||!d.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 sn({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=vd(r.metadata),i=Ad(r.result,o??r.status??null,s);if(i||o==="running"||o==="failed"){let d={agent_id:r.agent_id,task_id:r.id};o&&(d.status=o),o==="failed"&&r.error&&(d.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:d});}}return n}};var Xn=class extends Ue{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new an(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{Xn as ConversationPlugin,ln as FileLoggerPlugin,Fn as SqliteTracingPlugin};
|