@crewx/sdk 0.9.0-rc.104 → 0.9.0-rc.105
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 +191 -181
- package/dist/esm/plugins/index.js +81 -78
- package/dist/esm/repository/index.js +69 -66
- package/dist/events/types.d.ts +1 -0
- package/dist/index.d.ts +8 -6
- package/dist/index.js +192 -182
- package/dist/lifecycle/task-stop.d.ts +4 -1
- package/dist/mcp-app/discovery.d.ts +105 -0
- package/dist/mcp-app/index.d.ts +9 -3
- package/dist/mcp-app/node-app-discovery-fs.d.ts +20 -0
- package/dist/mcp-app/registry.d.ts +9 -1
- package/dist/mcp-app/state-set.d.ts +9 -0
- package/dist/mcp-app/types.d.ts +134 -1
- package/dist/mcp-app/workspace-snapshot.d.ts +53 -0
- package/dist/migrations/0027_task_stop_scope_cleanup.sql +5 -0
- package/dist/migrations/0027_ui_instance_active_unique.sql +2 -0
- package/dist/migrations/0029_nice_rhino.sql +1 -0
- package/dist/migrations/meta/0029_snapshot.json +3206 -0
- package/dist/migrations/meta/_journal.json +21 -0
- package/dist/plugins/index.js +82 -79
- package/dist/plugins/sqlite-tracing.d.ts +2 -0
- package/dist/repository/index.d.ts +1 -1
- package/dist/repository/index.js +69 -66
- package/dist/repository/task.repository.d.ts +12 -1
- package/dist/schema/tasks.d.ts +19 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/ui-instance/runtime.d.ts +7 -2
- package/dist/ui-instance/store.d.ts +1 -0
- package/dist/ui-instance/types.d.ts +1 -0
- package/dist/ui-plugin/index.d.ts +3 -2
- package/dist/ui-plugin/limits.d.ts +27 -0
- package/dist/ui-plugin/types.d.ts +97 -2
- package/dist/ui-plugin/validator.d.ts +9 -3
- package/dist/utils/workspace.d.ts +1 -0
- package/package.json +1 -1
|
@@ -1,28 +1,33 @@
|
|
|
1
|
-
import*as
|
|
1
|
+
import*as le from'path';import le__default,{join,dirname,resolve}from'path';import {fileURLToPath}from'url';import {existsSync,mkdirSync,writeFileSync,appendFileSync,lstatSync,readFileSync,statSync,realpathSync}from'fs';import zo,{homedir}from'os';import {createHash,randomBytes,randomUUID}from'crypto';import {sqliteTable,text,integer,index,check,primaryKey,real,uniqueIndex,unique}from'drizzle-orm/sqlite-core';import {sql,or as or$1,eq,isNull,and,ne as ne$1,desc,inArray,lt as lt$1,notLike,asc,like,gte,isNotNull}from'drizzle-orm';import {spawn}from'child_process';var ba=Object.defineProperty;var kt=(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 v=(t,e)=>()=>(t&&(e=t(t=0)),e);var xa=(t,e)=>{for(var n in e)ba(t,n,{get:e[n],enumerable:true});};var Pa,Da,R,h=v(()=>{Pa=()=>fileURLToPath(import.meta.url),Da=()=>le__default.dirname(Pa()),R=Da();});var f,it=v(()=>{h();f=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);}};});function Wo(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 Wa(t,e){let n=Wo(t),r=Wo(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function at(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&Wa(t,join(zo.homedir(),".crewx","crewx.db")))throw new Error(`${ja}: ${t}. Set CREWX_DB or CREWX_TRACES_DB to an isolated temporary path or :memory:.`);return t}var ja,ke,dt=v(()=>{h();ja="[crewx] Refusing to open the real CrewX database from a test process";ke=class{resolveDbPath(){let e=process.env.CREWX_DB||process.env.CREWX_TRACES_DB||join(zo.homedir(),".crewx","crewx.db");return at(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())}};});function W(t,e={}){let n=at(t),r=kt("better-sqlite3"),{drizzle:o}=kt("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 = ${za}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),runRaw:(a,u=[])=>s.prepare(a).run(...u),close:()=>s.close()}}var za,wt=v(()=>{h();dt();za=32*1024*1024;});function vn(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Ka(t,e){if(e>0||!vn(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(Va))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function Xa(t,e,n){if(!vn(t,"__drizzle_migrations")||!vn(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(a=>a.hash)),s=JSON.parse(readFileSync(le__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let u=Ja[a.tag];if(!u)continue;let d=le__default.join(e,`${a.tag}.sql`);if(!existsSync(d))continue;let c=readFileSync(d,"utf-8"),l=createHash("sha256").update(c).digest("hex");if(o.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),g=new Set(p.map(m=>m.name));for(let[m,T]of Object.entries(u))g.has(m)||(t.run(`ALTER TABLE tasks ADD COLUMN ${m} ${T}`),g.add(m));}}function Ya(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(a=>a.hash)),s=JSON.parse(readFileSync(le__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let u=le__default.join(e,`${a.tag}.sql`);if(!existsSync(u))continue;let d=readFileSync(u,"utf-8"),c=createHash("sha256").update(d).digest("hex");if(o.has(c))continue;let l=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,p=[],g;for(;(g=l.exec(d))!==null;)p.push({table:g[1],column:g[2]});if(p.length===0||!d.split(/-->\s*statement-breakpoint/).map(E=>E.trim()).filter(Boolean).every(E=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(E)))continue;p.every(({table:E,column:w})=>t.all(`PRAGMA table_info("${E}")`).some(M=>M.name===w))&&t.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${a.when})`);}}function Qa(t,e){let{sql:n}=kt("drizzle-orm"),r=JSON.parse(readFileSync(le__default.join(e,"meta/_journal.json"),"utf-8")),s=["0025_task_heartbeat","0025_thread_app_instance_ledger","0026_mcp_action_source","0027_ui_instance_active_unique"].map(a=>{let u=r.entries.find(c=>c.tag===a);if(!u)throw new Error(`Missing release/App compatibility migration: ${a}`);let d=readFileSync(le__default.join(e,`${a}.sql`),"utf-8");return {entry:u,content:d,hash:createHash("sha256").update(d).digest("hex")}});t.transaction(a=>{let u=new Set(a.all(n`SELECT hash FROM __drizzle_migrations`).map(d=>d.hash));if(u.has(s[0].hash)){for(let d of s.slice(1))if(!u.has(d.hash)){for(let c of d.content.split(/-->\s*statement-breakpoint/).filter(l=>l.trim()))a.run(n.raw(c));a.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${d.hash}, ${d.entry.when})`);}}},{behavior:"immediate"});}function ed(t,e,n,r){let s=JSON.parse(readFileSync(le__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===Za);if(!s)return;let a=le__default.join(e,`${s.tag}.sql`);if(!existsSync(a))return;let u=createHash("sha256").update(readFileSync(a,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.hash===u))return;if(!vn(t,"tasks"))return {hash:u,affectedRows:0};let d=t.all("PRAGMA table_info(tasks)"),c=new Set(d.map(p=>p.name));if(!c.has("stop_requested_at")||!c.has("stop_requested_epoch"))return {hash:u,affectedRows:0};let l=t.get(n`
|
|
2
|
+
SELECT count(*) AS count
|
|
3
|
+
FROM tasks
|
|
4
|
+
WHERE status IN ('success', 'failed')
|
|
5
|
+
AND (stop_requested_at IS NOT NULL OR stop_requested_epoch IS NOT NULL)
|
|
6
|
+
`);return {hash:u,affectedRows:l?.count??0}}function td(t){let{migrate:e}=kt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=kt("drizzle-orm"),r=[le__default.join(R,"../migrations"),le__default.join(R,"migrations"),le__default.join(R,"../../../../drizzle/migrations"),le__default.join(process.cwd(),"drizzle/migrations")],o=r.find(l=>existsSync(le__default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
2
7
|
${r.join(`
|
|
3
|
-
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;s?.cnt&&(a=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),$a(t,a),s?.cnt&&(Ba(t,o),qa(t,o,n),Fa(t,o,n)),e(t,{migrationsFolder:o});let u=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(u>0){let c=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${c} (${u} migration${u>1?"s":""} applied).`);}}function Ce(t,e){Fo.has(e)||(ja(t),Fo.add(e));}var Fo,Ha,Ua,Tt=v(()=>{h();Fo=new Set,Ha={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"};Ua={"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"},"0024_storage_metadata":{prompt:"TEXT",rendered_prompt:"TEXT",result:"TEXT",input_tokens:"INTEGER DEFAULT 0",output_tokens:"INTEGER DEFAULT 0",cost_usd:"REAL DEFAULT 0"}};});var wt,_r=v(()=>{h();wt=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 i,qt=v(()=>{h();i=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"),heartbeat_at:text("heartbeat_at"),stop_requested_at:text("stop_requested_at"),stop_requested_epoch:integer("stop_requested_epoch"),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_status_heartbeat:index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),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 Pe,jo=v(()=>{h();qt();Pe=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>i.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 Za,ed,_,An=v(()=>{h();_r();Za="json_extract(metadata, '$.threadTitle.state')",ed="json_extract(metadata, '$.threadTitle.priority')",_=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>wt.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(Za)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(ed))}));});var rd,zo=v(()=>{h();qt();rd=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>rd.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)}));});var Vo=v(()=>{h();qt();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.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)}));});var Jo=v(()=>{h();An();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},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)}));});var Yo=v(()=>{h();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)}));});var es=v(()=>{h();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)}));});var ts=v(()=>{h();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)}));});var rs=v(()=>{h();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]})}));});var ss=v(()=>{h();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)}));});var is=v(()=>{h();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(),app_id:text("app_id"),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`),appIdCheck:check("ui_instances_app_id_ck",sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),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),workspaceThreadAppUnique:uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id)}));});var ds=v(()=>{h();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', 'mcp')`),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`(
|
|
8
|
+
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;s?.cnt&&(a=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ka(t,a),s?.cnt&&(Qa(t,o),Ya(t,o,n),Xa(t,o,n));let u=ed(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let c=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(c>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}u&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(p=>p.hash===u.hash)&&console.error(`[crewx] Task stop-marker cleanup (${u.affectedRows} success/failed row(s) affected).`);}function Ne(t,e){Vo.has(e)||(td(t),Vo.add(e));}var Vo,Va,Ja,Za,yt=v(()=>{h();Vo=new Set,Va={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"};Ja={"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"},"0024_storage_metadata":{prompt:"TEXT",rendered_prompt:"TEXT",result:"TEXT",input_tokens:"INTEGER DEFAULT 0",output_tokens:"INTEGER DEFAULT 0",cost_usd:"REAL DEFAULT 0"}};Za="0027_task_stop_scope_cleanup";});var Et,yr=v(()=>{h();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 i,Wt=v(()=>{h();i=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"),heartbeat_at:text("heartbeat_at"),stop_requested_at:text("stop_requested_at"),stop_requested_epoch:integer("stop_requested_epoch"),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"),cwd:text("cwd"),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_status_heartbeat:index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),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 De,Xo=v(()=>{h();Wt();De=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>i.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 ld,pd,_,Nn=v(()=>{h();yr();ld="json_extract(metadata, '$.threadTitle.state')",pd="json_extract(metadata, '$.threadTitle.priority')",_=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(ld)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(pd))}));});var hd,Zo=v(()=>{h();Wt();hd=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>hd.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)}));});var es=v(()=>{h();Wt();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.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)}));});var ns=v(()=>{h();Nn();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},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)}));});var os=v(()=>{h();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)}));});var as=v(()=>{h();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)}));});var ds=v(()=>{h();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)}));});var cs=v(()=>{h();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]})}));});var ps=v(()=>{h();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)}));});var fs=v(()=>{h();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(),app_id:text("app_id"),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`),appIdCheck:check("ui_instances_app_id_ck",sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),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),workspaceThreadAppUnique:uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(sql`${t.status} = 'active'`)}));});var hs=v(()=>{h();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', 'mcp')`),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`(
|
|
4
9
|
(${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
|
|
5
10
|
OR
|
|
6
11
|
(${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
|
|
7
|
-
)`),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 cs,ls=v(()=>{h();cs=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(()=>cs.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(()=>cs.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 Sr,Ir,I,Ar=v(()=>{h();Sr=["THREAD_STATE","THREAD_PRIORITY"],Ir=["gray","blue","violet","green","amber","orange","red","pink"],I=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 ps,fs,gs,hs,ms,F,H,D,_s=v(()=>{h();An();ps=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],fs=["user","agent","system"],gs=["auto","manual"],hs=["decision","judgment","issue","result","pivot"],ms=["queued","running","completed","failed"],F=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},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)})),H=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),request_id:text("request_id").notNull(),status:text("status").notNull(),detector_version:text("detector_version").notNull(),requested_at:text("requested_at").notNull(),started_at:text("started_at"),completed_at:text("completed_at"),error_code:text("error_code"),previous_auto_count:integer("previous_auto_count"),new_auto_count:integer("new_auto_count")},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)})),D=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},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'`)}));});var Ts=v(()=>{h();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()});});var Et=v(()=>{h();_r();qt();jo();An();zo();Vo();Jo();Yo();es();ts();rs();ss();is();ds();ls();Ar();_s();Ts();});var Rt,Or,ws,br=v(()=>{h();Rt={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-5.6-sol":{input:5,cachedInput:.5,output:30},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},Or=new Set(["gpt-5.3-codex-spark"]),ws=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7[1m]","claude-opus-4-8[1m]","claude-opus-5","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","gemini-3.1-pro","gemini-3.5-flash","gemini-3.6-flash","gemini-3.7-flash","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-oss-120b","grok-4.5","grok-4.6"]);});function xr(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 Cd(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Gt;let e=xr(t),n=xd[e];if(n)return Pn[n]??Rt[n]??Gt;if(Pn[e])return Pn[e];if(Rt[e])return Rt[e];if(Or.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Gt;if(ws.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Gt;let r={...Rt,...Pn};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Gt}function Nd(t,e,n,r=0,o){let s=Cd(n),a=Math.min(r,t),u=(t-a)*s.input/1e6,c=a*s.cachedInput/1e6,l=e*s.output/1e6;return u+c+l}function ys(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:Nd(e??0,n??0,o,r??0)}var xd,Gt,Pn,Dn=v(()=>{h();br();br();xd={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},Gt={input:0,cachedInput:0,output:0},Pn={};});function Is(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Rs(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function As(t){return Number.isSafeInteger(t)&&t>0}function Hd(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:Is(c)});return}let o="",s="",a=false,d,u=setTimeout(()=>{try{r.kill();}catch{}d({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${Es}ms`)});},Es);d=c=>{a||(a=true,clearTimeout(u),n(c));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",c=>{o+=String(c);}),r.stderr?.on("data",c=>{s+=String(c);}),r.once("error",c=>{d({status:null,stdout:o,stderr:s,error:c});}),r.once("close",c=>{d({status:c,stdout:o,stderr:s});});})}async function vs(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Hd(t,e)}function $d(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Ud(){return new Promise(t=>{setImmediate(t);})}function ut(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Rs(n)==="ESRCH"?"not_found":Rs(n)==="EPERM"?"alive":"unknown"}}function Fd(t,e){let n=ut(-t,e),r=ut(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Os(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??Ld),a=Date.now()+o,d,u=o===0,c=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(l=>{d=setTimeout(l,o);});c.then(()=>{u=true;});try{for(await Ud();;){let l=Fd(t,e);if(l==="not_found")return l;let p=a-Date.now();if(u||p<=0)return l;await Promise.race([c,$d(Math.min(s,p))]);}}finally{d!==void 0&&clearTimeout(d);}}async function Ss(t,e,n,r,o){let s=await Os(t,e,o.hardConfirmMs??Md,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function Ln(t,e,n={}){if(!As(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],a;try{a=await vs(o,s,n);}catch{return "unknown"}if(a.error||a.status!==0)return "unknown";let d=a.stdout.trim();if(!d)return "not_found";let u=r==="win32"?d.toLowerCase():d;return e.filter(l=>l.trim().length>0).some(l=>{let p=r==="win32"?l.toLowerCase():l;return u.includes(p)})?"owned":"not_owned"}async function It(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=g=>({status:"failed",pid:t,method:r,error:g});if(!As(t))return o("Invalid process ID");let s=e.kill??process.kill,a=ut(t,s);if(a==="not_found")return {status:"not_found",pid:t,method:r};if(a!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let g;try{g=await vs("taskkill",["/PID",String(t),"/T","/F"],e);}catch(S){g={status:null,stdout:"",stderr:"",error:Is(S)};}let m=ut(t,s);return m==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(m==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let d,u=e.signal??"SIGKILL";try{s(-t,u);}catch(g){d=g;}if(u==="SIGKILL")return Ss(t,s,d,r,e);if(await Os(t,s,e.graceMs??Dd,e)==="not_found")return d?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{s(-t,"SIGKILL");}catch(g){l=g;}let p=await Ss(t,s,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?d?p:{status:"terminated",pid:t,method:r}:o(p.error??"Process termination failed")}var Es,St,Dd,Ld,Md,Mn=v(()=>{h();Es=3e3,St="SIGINT",Dd=2e3,Ld=25,Md=100;});function Ps(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Cs(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>Ps(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Ds(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Ns(t){return {taskId:t.id,source:Ds(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function zd(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var Hn,Ls=v(()=>{h();it();_t();Tt();ot();Et();Hn=class extends he{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?st(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 f("NOT_FOUND","Database not found");let r=W(n);if(e)try{Ce(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(eq(i.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(eq(i.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,a)=>Ps(s,a));if(r.length===0){let s=this.getLogState(e);if(!s)throw new f("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(a=>{let d=this.requireStateRowInTransaction(a,e),u=Ds(d);if(u==="blob"){let g=Cs(e,d.logs);if(a.update(i).set({logs:JSON.stringify([...g,...r]),log_revision:sql`${i.log_revision} + 1`}).where(eq(i.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:u,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let c=d.last_log_seq+1,l=d.last_log_seq+r.length;if(a.insert(Pe).values(r.map((g,m)=>({task_id:e,seq:c+m,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(i).set({last_log_seq:l,log_revision:sql`${i.log_revision} + 1`}).where(eq(i.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:u,revision:d.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("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?Ns(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return zd(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 a=Ns(s);if(a.source==="blob"){let l=Cs(e,s.logs);return {...a,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let d=o.select({seq:Pe.seq,timestamp:Pe.timestamp,level:Pe.level,message:Pe.message}).from(Pe).where(eq(Pe.task_id,e)).orderBy(n===void 0?asc(Pe.seq):desc(Pe.seq)),c=(n===void 0?d.all():d.limit(n).all()).map(({timestamp:l,level:p,message:g})=>({timestamp:l,level:p,message:g}));return n!==void 0&&c.reverse(),{...a,entries:c}},{behavior:"deferred"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var Ms=v(()=>{h();});var te,Vt=v(()=>{h();te=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 We,Cr=v(()=>{h();Vt();We=class extends te{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function He(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function $e(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 At=v(()=>{h();});function Jd(t){let e=Xd(t),n=e.map((s,a)=>({line:s,index:a})).filter(({line:s})=>Qd(s.value)),r=Yd(e);return {result:n.length===1&&n[0].index===r?Zd(n[0].line.value):null,resultPreview:nu(e,n),hasReservedLine:n.length>0}}function Ge(t,e){let n=Jd(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function Xd(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
12
|
+
)`),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 _s,ks=v(()=>{h();_s=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(()=>_s.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(()=>_s.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 Or,br,I,xr=v(()=>{h();Or=["THREAD_STATE","THREAD_PRIORITY"],br=["gray","blue","violet","green","amber","orange","red","pink"],I=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 Ts,ws,ys,Es,Rs,U,H,P,Ss=v(()=>{h();Nn();Ts=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],ws=["user","agent","system"],ys=["auto","manual"],Es=["decision","judgment","issue","result","pivot"],Rs=["queued","running","completed","failed"],U=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},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)})),H=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),request_id:text("request_id").notNull(),status:text("status").notNull(),detector_version:text("detector_version").notNull(),requested_at:text("requested_at").notNull(),started_at:text("started_at"),completed_at:text("completed_at"),error_code:text("error_code"),previous_auto_count:integer("previous_auto_count"),new_auto_count:integer("new_auto_count")},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)})),P=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},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'`)}));});var As=v(()=>{h();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()});});var St=v(()=>{h();yr();Wt();Xo();Nn();Zo();es();ns();os();as();ds();cs();ps();fs();hs();ks();xr();Ss();As();});var It,Nr,vs,Pr=v(()=>{h();It={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-5.6-sol":{input:5,cachedInput:.5,output:30},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},Nr=new Set(["gpt-5.3-codex-spark"]),vs=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7[1m]","claude-opus-4-8[1m]","claude-opus-5","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","gemini-3.1-pro","gemini-3.5-flash","gemini-3.6-flash","gemini-3.7-flash","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-oss-120b","grok-4.5","grok-4.6"]);});function Dr(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 jd(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Kt;let e=Dr(t),n=Bd[e];if(n)return Un[n]??It[n]??Kt;if(Un[e])return Un[e];if(It[e])return It[e];if(Nr.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Kt;if(vs.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Kt;let r={...It,...Un};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Kt}function Wd(t,e,n,r=0,o){let s=jd(n),a=Math.min(r,t),d=(t-a)*s.input/1e6,c=a*s.cachedInput/1e6,l=e*s.output/1e6;return d+c+l}function Os(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:Wd(e??0,n??0,o,r??0)}var Bd,Kt,Un,qn=v(()=>{h();Pr();Pr();Bd={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},Kt={input:0,cachedInput:0,output:0},Un={};});function Ns(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function xs(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Ps(t){return Number.isSafeInteger(t)&&t>0}function Jd(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:Ns(c)});return}let o="",s="",a=false,u,d=setTimeout(()=>{try{r.kill();}catch{}u({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${bs}ms`)});},bs);u=c=>{a||(a=true,clearTimeout(d),n(c));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",c=>{o+=String(c);}),r.stderr?.on("data",c=>{s+=String(c);}),r.once("error",c=>{u({status:null,stdout:o,stderr:s,error:c});}),r.once("close",c=>{u({status:c,stdout:o,stderr:s});});})}async function Ds(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Jd(t,e)}function Xd(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Yd(){return new Promise(t=>{setImmediate(t);})}function lt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return xs(n)==="ESRCH"?"not_found":xs(n)==="EPERM"?"alive":"unknown"}}function Qd(t,e){let n=lt(-t,e),r=lt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Ls(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??Vd),a=Date.now()+o,u,d=o===0,c=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(l=>{u=setTimeout(l,o);});c.then(()=>{d=true;});try{for(await Yd();;){let l=Qd(t,e);if(l==="not_found")return l;let p=a-Date.now();if(d||p<=0)return l;await Promise.race([c,Xd(Math.min(s,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function Cs(t,e,n,r,o){let s=await Ls(t,e,o.hardConfirmMs??Kd,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function Fn(t,e,n={}){if(!Ps(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],a;try{a=await Ds(o,s,n);}catch{return "unknown"}if(a.error||a.status!==0)return "unknown";let u=a.stdout.trim();if(!u)return "not_found";let d=r==="win32"?u.toLowerCase():u;return e.filter(l=>l.trim().length>0).some(l=>{let p=r==="win32"?l.toLowerCase():l;return d.includes(p)})?"owned":"not_owned"}async function vt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=g=>({status:"failed",pid:t,method:r,error:g});if(!Ps(t))return o("Invalid process ID");let s=e.kill??process.kill,a=lt(t,s);if(a==="not_found")return {status:"not_found",pid:t,method:r};if(a!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let g;try{g=await Ds("taskkill",["/PID",String(t),"/T","/F"],e);}catch(T){g={status:null,stdout:"",stderr:"",error:Ns(T)};}let m=lt(t,s);return m==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(m==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let u,d=e.signal??"SIGKILL";try{s(-t,d);}catch(g){u=g;}if(d==="SIGKILL")return Cs(t,s,u,r,e);if(await Ls(t,s,e.graceMs??zd,e)==="not_found")return u?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{s(-t,"SIGKILL");}catch(g){l=g;}let p=await Cs(t,s,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?u?p:{status:"terminated",pid:t,method:r}:o(p.error??"Process termination failed")}var bs,At,zd,Vd,Kd,Bn=v(()=>{h();bs=3e3,At="SIGINT",zd=2e3,Vd=25,Kd=100;});function qs(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function $s(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>qs(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Fs(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Us(t){return {taskId:t.id,source:Fs(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function ou(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var jn,Bs=v(()=>{h();dt();wt();yt();it();St();jn=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?at(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 f("NOT_FOUND","Database not found");let r=W(n);if(e)try{Ne(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(eq(i.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(eq(i.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,a)=>qs(s,a));if(r.length===0){let s=this.getLogState(e);if(!s)throw new f("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(a=>{let u=this.requireStateRowInTransaction(a,e),d=Fs(u);if(d==="blob"){let g=$s(e,u.logs);if(a.update(i).set({logs:JSON.stringify([...g,...r]),log_revision:sql`${i.log_revision} + 1`}).where(eq(i.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:u.last_log_seq}}let c=u.last_log_seq+1,l=u.last_log_seq+r.length;if(a.insert(De).values(r.map((g,m)=>({task_id:e,seq:c+m,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(i).set({last_log_seq:l,log_revision:sql`${i.log_revision} + 1`}).where(eq(i.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("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?Us(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return ou(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 a=Us(s);if(a.source==="blob"){let l=$s(e,s.logs);return {...a,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=o.select({seq:De.seq,timestamp:De.timestamp,level:De.level,message:De.message}).from(De).where(eq(De.task_id,e)).orderBy(n===void 0?asc(De.seq):desc(De.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({timestamp:l,level:p,message:g})=>({timestamp:l,level:p,message:g}));return n!==void 0&&c.reverse(),{...a,entries:c}},{behavior:"deferred"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var js=v(()=>{h();});var ne,Xt=v(()=>{h();ne=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 Ge,Lr=v(()=>{h();Xt();Ge=class extends ne{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function $e(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function Ue(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 Ot=v(()=>{h();});function au(t){let e=du(t),n=e.map((s,a)=>({line:s,index:a})).filter(({line:s})=>cu(s.value)),r=uu(e);return {result:n.length===1&&n[0].index===r?lu(n[0].line.value):null,resultPreview:gu(e,n),hasReservedLine:n.length>0}}function ze(t,e){let n=au(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function du(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
8
13
|
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
9
14
|
`?`\r
|
|
10
|
-
`: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 Yd(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Qd(t){return t.trimStart().startsWith(Vd)}function Zd(t){let e=t.trim();if(!e.startsWith(Hs)||!e.endsWith("]]"))return null;let n=e.slice(Hs.length,-2);if(!n)return null;try{return eu(JSON.parse(n))}catch{return null}}function eu(t){return tu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function tu(t){if(!ru(t)||Object.keys(t).some(r=>!Kd.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?$s(t.taskId)&&$s(t.agentId):t.isError===true}function nu(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 $s(t){return typeof t=="string"&&t.trim().length>0}function ru(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Hs,Vd,Kd,Kt=v(()=>{h();Hs="[[crewx:delegation-result ",Vd="[[crewx:delegation-result",Kd=new Set(["schema","taskId","agentId","isError"]);});function Ue(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 vt=v(()=>{h();});var Us,$n,Nr,Un=v(()=>{h();Us=["none","minimal","low","medium","high","xhigh","max","ultra"],$n={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"]},Nr={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(Nr).map(([t,e])=>[t,e.models]));});function Pr(t){return su[t]??t}function au(t){return iu.get(t)??t}function Dr(t){if(!t)return {};let e=uu.get(t);return e?{...e}:{model:t}}function Lr(t,e){return t==="antigravity"||t==="cli/antigravity"?Dr(e):e===void 0?{}:{model:au(e)}}var ou,su,iu,du,uu,Jt=v(()=>{h();ou=[{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]"}],su={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};iu=new Map(ou.map(({baseModelId:t,catalogModelId:e})=>[t,e]));du=[{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"}],uu=new Map(du.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function lu(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function et(t){return Fn(t).models}function Fn(t){return cu[t]??Nr[t]??lu()}function Xt(t,e){let n=Fn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Lr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Fs(t){return Fn(t).modelOverrides}function qs(){return et("claude")}function Bs(){return et("codex")}function js(){return et("copilot")}function Ws(){return et("antigravity")}var cu,ct=v(()=>{h();Un();Dn();Jt();cu={};});function Gs(t){return pu[t]??t}var pu,zs=v(()=>{h();ct();Jt();pu={auto:"default"};});function qn(t,e){return ($n[t]??[]).includes(e)}function tt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return fu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Vs(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 Ks(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 Js(t){return !t||!qn("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Xs(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Gs(t);return e.has(n)?["--permission-mode",n]:[]}function Ys(t){return t?qn("claude",t)?["--effort",t]:[]:[]}function Qs(t){return t==="default"?[]:t&&gu.has(t)?["--permission-mode",t]:[]}function Zs(t){return t===true?["--always-approve"]:[]}function ei(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 ti(t){return t?qn("grok",t)?["--effort",t]:[]:[]}function ni(t){if(!t)return [];switch(Pr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function ri(t){return t?qn("antigravity",t)?["--effort",t]:[]:[]}var fu,gu,Yt=v(()=>{h();zs();Jt();Un();fu=new Set(Us);gu=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function hu(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,a=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:a}}function mu(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),a="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,u=a!==void 0?a:d??0;return {inputTokens:a!==void 0?r+a:r,outputTokens:o,cachedInputTokens:u}}function _u(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,a=s?Number(s.read??0):0;return {inputTokens:r+a,outputTokens:o,cachedInputTokens:a}}function oi(t){let e=new Map,n;for(let s of t.split(`
|
|
11
|
-
`))if(s.trim())try{let a=JSON.parse(s);if(a.type!=="assistant")continue;let
|
|
12
|
-
`))if(r.trim())try{let o=JSON.parse(r),s=
|
|
13
|
-
`).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 a of s.message.content)a.type==="text"&&typeof a.text=="string"&&a.text.trim()&&n.push(a.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}function
|
|
15
|
+
`: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 uu(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function cu(t){return t.trimStart().startsWith(su)}function lu(t){let e=t.trim();if(!e.startsWith(Ws)||!e.endsWith("]]"))return null;let n=e.slice(Ws.length,-2);if(!n)return null;try{return pu(JSON.parse(n))}catch{return null}}function pu(t){return fu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function fu(t){if(!hu(t)||Object.keys(t).some(r=>!iu.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?Gs(t.taskId)&&Gs(t.agentId):t.isError===true}function gu(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 Gs(t){return typeof t=="string"&&t.trim().length>0}function hu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ws,su,iu,Yt=v(()=>{h();Ws="[[crewx:delegation-result ",su="[[crewx:delegation-result",iu=new Set(["schema","taskId","agentId","isError"]);});function qe(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 bt=v(()=>{h();});var zs,Wn,Mr,Gn=v(()=>{h();zs=["none","minimal","low","medium","high","xhigh","max","ultra"],Wn={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"]},Mr={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(Mr).map(([t,e])=>[t,e.models]));});function Hr(t){return _u[t]??t}function Tu(t){return ku.get(t)??t}function $r(t){if(!t)return {};let e=yu.get(t);return e?{...e}:{model:t}}function Ur(t,e){return t==="antigravity"||t==="cli/antigravity"?$r(e):e===void 0?{}:{model:Tu(e)}}var mu,_u,ku,wu,yu,Qt=v(()=>{h();mu=[{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]"}],_u={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};ku=new Map(mu.map(({baseModelId:t,catalogModelId:e})=>[t,e]));wu=[{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"}],yu=new Map(wu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Ru(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function nt(t){return zn(t).models}function zn(t){return Eu[t]??Mr[t]??Ru()}function Zt(t,e){let n=zn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Ur(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Vs(t){return zn(t).modelOverrides}function Ks(){return nt("claude")}function Js(){return nt("codex")}function Xs(){return nt("copilot")}function Ys(){return nt("antigravity")}var Eu,pt=v(()=>{h();Gn();qn();Qt();Eu={};});function Qs(t){return Su[t]??t}var Su,Zs=v(()=>{h();pt();Qt();Su={auto:"default"};});function Vn(t,e){return (Wn[t]??[]).includes(e)}function rt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Iu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function ei(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 ti(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 ni(t){return !t||!Vn("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function ri(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Qs(t);return e.has(n)?["--permission-mode",n]:[]}function oi(t){return t?Vn("claude",t)?["--effort",t]:[]:[]}function si(t){return t==="default"?[]:t&&Au.has(t)?["--permission-mode",t]:[]}function ii(t){return t===true?["--always-approve"]:[]}function ai(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 di(t){return t?Vn("grok",t)?["--effort",t]:[]:[]}function ui(t){if(!t)return [];switch(Hr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function ci(t){return t?Vn("antigravity",t)?["--effort",t]:[]:[]}var Iu,Au,en=v(()=>{h();Zs();Qt();Gn();Iu=new Set(zs);Au=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function vu(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,a=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:a}}function Ou(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),a="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,u="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=a!==void 0?a:u??0;return {inputTokens:a!==void 0?r+a:r,outputTokens:o,cachedInputTokens:d}}function bu(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,a=s?Number(s.read??0):0;return {inputTokens:r+a,outputTokens:o,cachedInputTokens:a}}function li(t){let e=new Map,n;for(let s of t.split(`
|
|
16
|
+
`))if(s.trim())try{let a=JSON.parse(s);if(a.type!=="assistant")continue;let u=a.message,d=u?.id,c=u?.usage;if(typeof d!="string"||!c)continue;let l=Number(c.input_tokens??0),p=Number(c.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let g=u?.model;typeof g=="string"&&g&&(n=g);}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 xt(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
17
|
+
`))if(r.trim())try{let o=JSON.parse(r),s=bu(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 a=vu(o)??Ou(o);a&&(e=a);}catch{}return n||(e??void 0)}var tn=v(()=>{h();});function Ae(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 ft=v(()=>{h();});function pi(t){let e=t.split(`
|
|
18
|
+
`).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 a of s.message.content)a.type==="text"&&typeof a.text=="string"&&a.text.trim()&&n.push(a.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}function Cu(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
14
19
|
|
|
15
|
-
`):""}function
|
|
16
|
-
`):a=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...
|
|
17
|
-
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,a=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,
|
|
18
|
-
`).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 a=s.data.content;a.trim()&&n.push(a.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
|
|
19
|
-
`).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 a=s.item.text;a.trim()&&n.push(a.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}function Au(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return He(r)?[$e(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function vu(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=Ou(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",...Ge(r,o)}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=Ue(o);return r==="Bash"&&He(s)?$e(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",...Ge(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(a=>String(a.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 Ou(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=Ue(o);return r==="Bash"&&He(s)?$e(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var Ru,Fr,qr=v(()=>{h();Qt();At();vt();Kt();Yt();ct();lt();Ru=new Set(["turn.started","turn.completed","item.updated"]);Fr={command:"codex",meta:{displayName:"Codex",models:Bs(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=tt(e.model),s=e.effort??o,a=e.resumeSessionId?Ks(e.mode):Vs(e.mode),d=Js(s),u=r?["-m",r]:[],c=Iu(e.additionalArgs??[]),p=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...a,...d,...u,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...a,...d,...u,...c],stdinMessage:t}},extractText(t){return ai(t)??t.trim()},extractPartialText(t){return ai(t)},parseResultMeta(t){let e=Ot(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=Su(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let a;try{a=JSON.parse(s);}catch{continue}let d=a.type;if(!d||!d.startsWith("item.")&&!d.startsWith("turn.")&&!d.startsWith("thread."))continue;let u=Ie(a,n),c=a.item;if(c){if(d==="item.started"){r.push(...Au(u,c));continue}if(d==="item.completed"){let l=vu(u,c);l&&r.push(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?Ru.has(r):!1}catch{return false}}};});function Cu(t){return t?xu[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Bn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function pi(t){let e=[],n=0,r=false,o=false,s=0;for(let d=0;d<t.length;d++){let u=t[d];if(o){o=false;continue}if(u==="\\"&&r){o=true;continue}if(u==='"'){r=!r;continue}if(!r){if(u==="{")n++;else if(u==="}"&&(n--,n===0)){let c=t.slice(s,d+1).trim();c&&e.push(c),s=d+1;}}}let a=t.slice(s).trim();return a&&e.push(a),e}function xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Nu(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let a=JSON.parse(o);xt(a)?e.push(a):n=!0;continue}catch{}let s=pi(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let a of s)try{let d=JSON.parse(a);xt(d)?e.push(d):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function pt(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,li).trim()}function fi(t){let e=xt(t.error)?t.error:void 0,n=e&&xt(e.data)?e.data:void 0,r=pt(e?.name),o=pt(n?.message)??pt(e?.message)??pt(t.message)??pt(t.errorMessage)??pt(t.error),s=pt(t.ref),a=r&&o&&r!==o?`${r}: ${o}`:r??o??ci;return (s?`${a} (ref: ${s})`:a).slice(0,li)}function di(t){let e=Nu(t),n=[],r=null,o=0,s=[],a,d=false;for(let u of e.events){let c=typeof u.type=="string"?u.type:void 0;if(c){if(c==="text"){let l=xt(u.part)?u.part:void 0,p=typeof l?.text=="string"?l.text:void 0;p?.trim()&&n.push(p.trim());continue}if(c==="result"){typeof u.result=="string"&&(r=u.result);continue}if(c==="tool_use"){o++;continue}if(c==="error"){s.push(fi(u));continue}if(c==="step_finish"){d=true;let l=xt(u.part)?u.part:void 0;a=typeof l?.reason=="string"?l.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorMessages:s,terminalReason:a,hasTerminal:d}}function gi(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function jn(){return new te("OpenCode returned no assistant output.",bt,{code:"EMPTY_OUTPUT",kind:"transient"})}function Pu(){return new te("OpenCode emitted malformed JSON output.",bt,{code:"PROVIDER_CRASHED",kind:"transient"})}function ui(t,e){switch(gi(t)){case "length":return new te("OpenCode stopped because the context window was exceeded.",bt,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new te("OpenCode stopped because the content filter blocked the response.",bt,{code:"UNKNOWN",kind:"permanent"});case "error":return new te(e?`OpenCode error: ${e}`:`${ci} while generating a response.`,bt,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var bu,bt,ci,li,xu,Br,jr=v(()=>{h();Vt();Qt();vt();lt();bu=new Set(["step_start","step_finish"]),bt="cli/opencode",ci="OpenCode provider error",li=240,xu={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Br={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Bn(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:a}=Cu(e.mode);Bn(o,"--agent")||s!==void 0&&o.push("--agent",s),a&&!Bn(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!Bn(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let d;return !n&&!a&&!e.env?.OPENCODE_PERMISSION&&(d={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:d}},extractText(t){let e=di(t),n=e.errorMessages[0];if(n){let a=ui("error",n);if(a)throw a}let r=ui(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 jn();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw jn();return e.resultText}if(e.malformed)throw Pu();if(!e.hasTerminal)throw jn();let s=gi(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw jn()},interpretExit(t,e,n=""){if(t===0)return null;let o=di(n).errorMessages[0];return o?new te(`OpenCode error: ${o}`,bt,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=Ot(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=pi(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let a;try{a=JSON.parse(s);}catch{continue}let d=Ie(a,n),u=a.type;if(u){if(u==="text"){let l=a.part?.text;l&&r.push({timestamp:d,type:"text",content:l});continue}if(u==="tool_use"){let c=a.part;if(!c)continue;let l=String(c.tool||""),p=String(c.callID||""),g=c.state,m=String(g?.status||""),S=g?.input,w=Ue(S);if(r.push({timestamp:d,type:"tool_use",toolName:l,toolUseId:p,toolInput:w}),m==="completed"&&g?.output!==void 0){let T=g.output,P=typeof T=="string"?T:JSON.stringify(T);r.push({timestamp:d,type:"tool_result",toolUseId:p,resultPreview:P,isError:false});}else m==="error"&&r.push({timestamp:d,type:"tool_result",toolUseId:p,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(u==="error"){let c=fi(a);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?bu.has(r):!1}catch{return false}}};});function Zt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Du(t,e){if(!(t?et(Wr).some(s=>s.id===t):false)||!t)return e;let r=Xt(Wr,t),o=Fs(Wr)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var Wr,Gr,zr=v(()=>{h();Vt();Jt();ct();Yt();Wr="antigravity";Gr={command:"agy",meta:{displayName:"Antigravity",models:Ws(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=tt(e.model),s=Dr(r),a=s.model,d=e.effort??o??s.effort,u=Du(a,d),c=e.additionalArgs??[],l=a&&!Zt(c,"--model")?["--model",a]:[],p=Zt(c,"--effort")?[]:ri(u),g=Zt(c,"--mode")||Zt(c,"--dangerously-skip-permissions")?[]:ni(e.mode),m=Zt(c,"--print")?[]:["--print",t];return {args:[...l,...p,...g,...c,...m]}},extractText(t){let e=t.trim();if(!e)throw new te("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 hi=v(()=>{h();At();vt();Kt();lt();});function Ct(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Gn(t){return Ct(t)?t:void 0}function de(t){return typeof t=="string"?t:void 0}function ft(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Uu(t){let e=[],n=-1,r=0,o=false,s=false;for(let a=0;a<t.length;a+=1){let d=t[a];if(n===-1){(d==="{"||d==="[")&&(n=a,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,a+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function en(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Ct(n)?[n]:[]}catch{return Uu(e).flatMap(n=>{try{let r=JSON.parse(n);return Ct(r)?[r]:[]}catch{return []}})}}function tn(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function nn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(nn).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
20
|
-
`):void 0}if(
|
|
21
|
-
`).flatMap(
|
|
22
|
-
`),o=r.length>
|
|
23
|
-
`).flatMap(
|
|
24
|
-
`).flatMap(
|
|
25
|
-
`)??"";if(!n.trim())return;let r=Si(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=zu(o?.model,t.model),a=o?.usage;if(!a)return {stdout:n,adapter:r};let d=zn(a.inputTokens),u=zn(a.outputTokens),c=zn(a.cachedInputTokens),l=ys(zn(a.costUsd),d,u,c,s);return d!==0||u!==0||c!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:d,outputTokens:u,cachedInputTokens:c,costUsd:l,model:s}}:{stdout:n,adapter:r}}var Jr=v(()=>{h();Ii();Dn();});function Ku(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.terminalReason;return typeof n=="string"&&Vu.has(n)?n:void 0}catch{return}}function gt(t){switch(t.status){case "stopped":case "runner_lost":case "pending":case "running":case "paused":case "success":return t.status;case "completed":case "done":return "success";case "error":return "failed";case "failed":{let e=Ku(t.metadata);return e==="user_stop"?"stopped":e==="runner_lost"?"runner_lost":e==="launch_failed"?"failed":typeof t.error=="string"&&Ai.stopped.test(t.error)?"stopped":typeof t.error=="string"&&Ai.runnerLost.test(t.error)?"runner_lost":"failed"}default:return t.status}}var vi,Ai,Vu,Kn=v(()=>{h();vi=["success","failed","stopped","runner_lost"],Ai={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},Vu=new Set(["user_stop","runner_lost","launch_failed"]);});function Xr(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let o=Number(r);return !Number.isFinite(o)||o<=0?e:Math.max(n,Math.trunc(o))}function Yr(){return Xr("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Pt(){return Xr("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Xn(){return Xr("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Nt(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Jn(t){let e=typeof t=="object"&&t!==null&&"code"in t?String(t.code):t instanceof Error?t.name:typeof t;console.warn(`[crewx] task heartbeat write failed (${e}); execution continues`);}function Ju(t){return t?{id:t.id,status:t.status,run_epoch:t.run_epoch,stop_requested_at:t.stop_requested_at,stop_requested_epoch:t.stop_requested_epoch,pid:t.pid,metadata:t.metadata,started_at:t.started_at,duration_ms:t.duration_ms}:null}function Oi(t,e){return !!t.stop_requested_at&&Nt(t.stop_requested_epoch)===Nt(e)}function bi(t,e){let n=Nt(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=Ju(t.getTask(e.taskId));return !o||o.status!=="running"||Nt(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function Pi(t,e){let n=rn.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),rn.delete(t),true)}function on(t,e){let n=rn.get(t);return !n||e!==void 0&&n.runEpoch!==Nt(e)?false:Pi(t,n)}function Di(t,e){let n=Nt(e.runEpoch);on(e.taskId);let r=true,o=null;try{let c=bi(t,{...e,runEpoch:n});r=c.accepted,o=c.row;}catch(c){Jn(c);}if(!r)return false;let s=Yr(),a=Math.min(s,1e3),d=setInterval(()=>{let c=rn.get(e.taskId);if(!(!c||c.timer!==d))try{c.heartbeatElapsedMs+=a;let l=c.heartbeatElapsedMs>=s,p=bi(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){Pi(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=s,c.lastHeartbeatAt=Date.now()),p.row&&Oi(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(Jn));}catch(l){Jn(l);}},a),u={timer:d,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return rn.set(e.taskId,u),typeof d=="object"&&d!==null&&"unref"in d&&d.unref(),o&&Oi(o,n)&&e.onStopRequested&&(u.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(Jn)),true}var xi,Ci,Ni,rn,sn=v(()=>{h();xi=1e4,Ci=3e4,Ni=18e5;rn=new Map;});function Yn(t,e=Date.now(),n=to){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=oo(n,to,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function oo(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function Ui(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function rc(t){if(!t)return;let e=Ui(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function fe(t,e){if(!t)return {status:"not_running",finalStatus:"not_running",...e?{pid:e}:{}};let n=typeof t.pid=="number"&&t.pid>0?t.pid:e;if(t.status==="stopped"){let r=rc(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function uo(t,e,n="Process owner could not be verified"){let r=e??(t.pid&&t.pid>0?t.pid:void 0);return {status:"ownership_unverified",finalStatus:t.status,...r?{pid:r}:{},error:n}}function z(t,e,n){let r=n??(t?.pid&&t.pid>0?t.pid:void 0);return {status:"failed",finalStatus:t?.status??null,...r?{pid:r}:{},error:e}}function eo(t,e){return z(t,Qu,e)}function oc(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Pt():false}function sc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function ic(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=Ui(t.metadata),r=n.ownership==="runner"&&typeof n.providerPid=="number"&&Number.isSafeInteger(n.providerPid)&&n.providerPid>0?n.providerPid:void 0;return [...new Set([e,r].filter(o=>o!==void 0))]}function ac(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return fe(r,n)}async function dc(t,e,n,r){let o=Date.now()+n;for(;;){let s=ac(t,e);if(s)return s;let a=o-Date.now();if(a<=0)return;await new Promise(d=>{setTimeout(d,Math.min(r,a));});}}async function $i(t,e,n){let r=new Date().toISOString(),o=t.requestTaskStop({id:e,requestedAt:r}),s=t.getTask(e);if(!o.accepted){if(o.status==="pending"){let C=t.stopPendingTask(e),U=t.getTask(e);if(C||!U||U.status!=="running")return fe(U);if(o=t.requestTaskStop({id:e,requestedAt:r}),!o.accepted&&o.status!=="running"||!o.accepted&&!o.alreadyRequestedAt)return fe(t.getTask(e))}else if(!(o.status==="running"&&o.alreadyRequestedAt))return fe(s)}let a=o.runEpoch,d=oo(n.graceMs,to,0),u=oo(n.pollMs,Xu,1),c=await dc(t,e,d,u);if(c)return c;let l=t.getTask(e);if(!l||l.status!=="running")return fe(l);let p=ic(l),g=p[0];if(!g){let C=t.finalizeTaskStop({id:e,runEpoch:a,method:"forced"}),U=t.getTask(e);return C||U?.status!=="running"?fe(U):z(U,"Failed to finalize task stop")}let m=sc(n),S="unknown";if(!oc(l,Date.now())){let C=n.processControl?.checkProcessOwnershipAsync??Ln;try{S=await C(g,n.ownershipMarkers??ao,m);}catch{S="unknown";}if(S!=="owned")return uo(l)}let w=n.processControl?.terminateProcessTree??It;for(let C of p){let U;try{U=await w(C,{...m,signal:St});}catch(E){U={status:"failed",pid:C,method:m.platform==="win32"?"taskkill":"process-group",error:E instanceof Error?E.message:String(E)};}if(U.status==="failed")return z(t.getTask(e),U.error??"Failed to terminate process tree")}let T=t.finalizeTaskStop({id:e,runEpoch:a,method:"forced"}),P=t.getTask(e);return T||P?.status!=="running"?fe(P,g):z(P,"Task changed before stop was finalized")}function so(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function io(t){return Number.isSafeInteger(t)&&t>=0}function an(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function uc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function cc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function lc(t,e){let n=t?.pid&&t.pid>0?t.pid:e;return {status:"stopped",method:"forced",finalStatus:t?.status??"runner_lost",...n?{pid:n}:{}}}function pc(t){switch(t){case "epoch_mismatch":return no;case "workspace_mismatch":return ro;default:return}}async function Fi(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return eo(n,so(e.targetPid)?e.targetPid:void 0);if(!io(e.sourceRunEpoch)||!io(e.settleRunEpoch)||an(n.run_epoch)!==e.settleRunEpoch)return z(n,Qr,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,Zr,e.targetPid);let r=new Date().toISOString(),o;try{o=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return z(n,Zu,e.targetPid)}let s=t.getTask(e.taskId);if(!s||s.status!=="running")return eo(s,e.targetPid);if(o.runEpoch!==e.settleRunEpoch||an(s.run_epoch)!==e.settleRunEpoch)return z(s,Qr,e.targetPid);if(e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId)return z(s,Zr,e.targetPid);if(!so(e.targetPid))return z(s,Yu);let a=uc(e),d=e.processControl?.checkProcessOwnershipAsync??Ln,u="unknown";try{u=await d(e.targetPid,e.ownershipMarkers??ao,a);}catch{u="unknown";}if(u!=="owned")return uo(s,e.targetPid);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return eo(c,e.targetPid);if(an(c.run_epoch)!==e.settleRunEpoch)return z(c,Qr,e.targetPid);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,Zr,e.targetPid);let l=e.processControl?.terminateProcessTree??It,p;try{p=await l(e.targetPid,{...a,signal:St});}catch{return z(t.getTask(e.taskId),Li,e.targetPid)}if(p.status==="failed")return z(t.getTask(e.taskId),Li,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return z(t.getTask(e.taskId),Mi,e.targetPid)}return g?fe(t.getTask(e.taskId),e.targetPid):z(t.getTask(e.taskId),Mi,e.targetPid)}async function qi(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return fe(n);if(!io(e.expectedRunEpoch)||an(n.run_epoch)!==e.expectedRunEpoch)return z(n,no);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,ro);let r=n.pid;if(!so(r))return z(n,ec);let o=cc(e),s=e.processControl?.checkProcessOwnershipAsync??Ln,a="unknown";try{a=await s(r,e.ownershipMarkers??ao,o);}catch{a="unknown";}if(a!=="owned")return uo(n,r,tc);let d=e.processControl?.terminateProcessTree??It,u;try{u=await d(r,{...o,signal:St});}catch{return z(t.getTask(e.taskId),Hi,r)}if(u.status==="failed")return z(t.getTask(e.taskId),Hi,r);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return fe(c,r);if(an(c.run_epoch)!==e.expectedRunEpoch)return z(c,no,r);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,ro,r);let l;try{l=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return z(t.getTask(e.taskId),nc,r)}let p=pc(l);return p?z(t.getTask(e.taskId),p,r):l!=="settled"?fe(t.getTask(e.taskId),r):lc(t.getTask(e.taskId),r)}function Bi(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(lo(),ji)).then(({TaskRepository:s})=>$i(new s,r,o))}return $i(t,e,n)}var to,Xu,ao,Yu,Qr,Zr,Qu,Li,Mi,Zu,no,ro,ec,tc,Hi,nc,co=v(()=>{h();Mn();sn();to=5e3,Xu=250;ao=["crewx","claude","codex","opencode","grok","node"],Yu="INSTRUCTION_STOP_TARGET_PID_MISSING",Qr="INSTRUCTION_STOP_EPOCH_MISMATCH",Zr="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Qu="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",Li="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Mi="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Zu="INSTRUCTION_STOP_REQUEST_FAILED",no="HOST_SHUTDOWN_EPOCH_MISMATCH",ro="HOST_SHUTDOWN_WORKSPACE_MISMATCH",ec="HOST_SHUTDOWN_TARGET_PID_MISSING",tc="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",Hi="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",nc="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var ji={};ya(ji,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Yi,HOST_SHUTDOWN_TERMINAL_ERROR:()=>Ji,PENDING_ADOPT_GRACE_MS:()=>Xi,PID_NULL_REAP_GRACE_MS:()=>ko,TASK_HEARTBEAT_HARD_STALE_MS:()=>Ni,TASK_HEARTBEAT_INTERVAL_MS:()=>xi,TASK_HEARTBEAT_STALE_MS:()=>Ci,TaskRepository:()=>fn,hasRecordedUsage:()=>_o,mergeTerminalReason:()=>mo,resolveTaskHeartbeatHardStaleMs:()=>Xn,resolveTaskHeartbeatIntervalMs:()=>Yr,resolveTaskHeartbeatStaleMs:()=>Pt});function ve(t){return {...t,status:gt(t)}}function Gi(t){return {...t,status:gt(t)}}function zi(){let t=sql`
|
|
20
|
+
`):""}function Nu(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function Pu(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,a=qe(s);return r==="Bash"&&$e(a)?Ue(t,a,o):{timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:a}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",a;return typeof s=="string"?a=s:Array.isArray(s)?a=s.filter(u=>u.type==="text"&&typeof u.text=="string").map(u=>u.text).join(`
|
|
21
|
+
`):a=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...ze(a,r)}}return null}var xu,qr,Fr=v(()=>{h();Lr();Ot();Yt();bt();en();pt();tn();ft();xu=new Set(["tool_progress"]);qr={command:"claude",meta:{displayName:"Claude",models:Ks(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=rt(e.model),s=e.effort??o,a=ri(e.mode),u=oi(s),d=r?["--model",r]:[],c=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let p=[...e.additionalArgs];return p.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...c,...a,...u,...d,...p],stdinMessage:t}:{args:["--output-format","stream-json","--verbose",...c,...a,...u,...d,...p],stdinMessage:t}}return {args:["-p","--output-format","stream-json","--verbose",...c,...a,...u,...d],stdinMessage:t}},extractText(t){return pi(t)??t.trim()},extractPartialText(t){return pi(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 Ge(`Claude rate limit: ${n.rateLimitType??"unknown"} (status: ${n.status})`)}if(e.error==="rate_limit"){let n=Cu(e);return new Ge(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(Nu(n))return new Ge(`Claude rate limit: ${n}`)}}catch{}return null},parseResultMeta(t){let e=t.split(`
|
|
22
|
+
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,a=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,u=o.modelUsage,d=u?Object.keys(u)[0]??null:null;return {usage:a,model:d}}}catch{}let n=li(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 a=Ae(n,e??new Date().toISOString()),u=[];for(let d of s){let c=Pu(a,d);c&&u.push(c);}return u},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?xu.has(r):!1}catch{return false}}};});function fi(t){let e=t.split(`
|
|
23
|
+
`).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 a=s.data.content;a.trim()&&n.push(a.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 Du,Br,jr=v(()=>{h();tn();Ot();bt();Yt();pt();Gn();ft();Du=new Set(["interactive","plan","autopilot"]);Br={command:"copilot",meta:{displayName:"Copilot",models:Xs()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&Du.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Wn.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){return fi(t)??t.trim()},extractPartialText(t){return fi(t)},parseResultMeta(t){let e=xt(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=Ae(n,e??new Date().toISOString()),a=o.toolCallId;if(r==="tool.execution_start"){let u=String(o.toolName||""),d=o.arguments,c=qe(d);return (u==="bash"||u==="Bash")&&$e(c)?[Ue(s,c,a)]:[{timestamp:s,type:"tool_use",toolName:u,toolInput:c,...a&&{toolUseId:a}}]}if(r==="tool.execution_complete"){let u=o.error;if(u)return [{timestamp:s,type:"tool_result",...a&&{toolUseId:a},...ze(String(u.message||""),true)}];let d=o.result,c=String(d?.content||"");return [{timestamp:s,type:"tool_result",...a&&{toolUseId:a},...ze(c,false)}]}if(r==="assistant.message"){let u=String(o.content||"");return u?[{timestamp:s,type:"text",content:u}]:[]}return []}};});function Mu(t){let e=[],n=0,r=false,o=false,s=0;for(let u=0;u<t.length;u++){let d=t[u];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let c=t.slice(s,u+1).trim();c&&e.push(c),s=u+1;}}}let a=t.slice(s).trim();return a&&e.push(a),e}function Hu(t){return t[0]==="exec"?t.slice(1):t}function gi(t){let e=t.split(`
|
|
24
|
+
`).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 a=s.item.text;a.trim()&&n.push(a.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}function $u(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return $e(r)?[Ue(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function Uu(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=qu(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",...ze(r,o)}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=qe(o);return r==="Bash"&&$e(s)?Ue(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",...ze(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(a=>String(a.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 qu(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=qe(o);return r==="Bash"&&$e(s)?Ue(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var Lu,Wr,Gr=v(()=>{h();tn();Ot();bt();Yt();en();pt();ft();Lu=new Set(["turn.started","turn.completed","item.updated"]);Wr={command:"codex",meta:{displayName:"Codex",models:Js(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=rt(e.model),s=e.effort??o,a=e.resumeSessionId?ti(e.mode):ei(e.mode),u=ni(s),d=r?["-m",r]:[],c=Hu(e.additionalArgs??[]),p=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...a,...u,...d,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...a,...u,...d,...c],stdinMessage:t}},extractText(t){return gi(t)??t.trim()},extractPartialText(t){return gi(t)},parseResultMeta(t){let e=xt(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=Mu(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let a;try{a=JSON.parse(s);}catch{continue}let u=a.type;if(!u||!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread."))continue;let d=Ae(a,n),c=a.item;if(c){if(u==="item.started"){r.push(...$u(d,c));continue}if(u==="item.completed"){let l=Uu(d,c);l&&r.push(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?Lu.has(r):!1}catch{return false}}};});function ju(t){return t?Bu[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Kn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ti(t){let e=[],n=0,r=false,o=false,s=0;for(let u=0;u<t.length;u++){let d=t[u];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let c=t.slice(s,u+1).trim();c&&e.push(c),s=u+1;}}}let a=t.slice(s).trim();return a&&e.push(a),e}function Nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Wu(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let a=JSON.parse(o);Nt(a)?e.push(a):n=!0;continue}catch{}let s=Ti(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let a of s)try{let u=JSON.parse(a);Nt(u)?e.push(u):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function gt(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,ki).trim()}function wi(t){let e=Nt(t.error)?t.error:void 0,n=e&&Nt(e.data)?e.data:void 0,r=gt(e?.name),o=gt(n?.message)??gt(e?.message)??gt(t.message)??gt(t.errorMessage)??gt(t.error),s=gt(t.ref),a=r&&o&&r!==o?`${r}: ${o}`:r??o??_i;return (s?`${a} (ref: ${s})`:a).slice(0,ki)}function hi(t){let e=Wu(t),n=[],r=null,o=0,s=[],a,u=false;for(let d of e.events){let c=typeof d.type=="string"?d.type:void 0;if(c){if(c==="text"){let l=Nt(d.part)?d.part:void 0,p=typeof l?.text=="string"?l.text:void 0;p?.trim()&&n.push(p.trim());continue}if(c==="result"){typeof d.result=="string"&&(r=d.result);continue}if(c==="tool_use"){o++;continue}if(c==="error"){s.push(wi(d));continue}if(c==="step_finish"){u=true;let l=Nt(d.part)?d.part:void 0;a=typeof l?.reason=="string"?l.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorMessages:s,terminalReason:a,hasTerminal:u}}function yi(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Jn(){return new ne("OpenCode returned no assistant output.",Ct,{code:"EMPTY_OUTPUT",kind:"transient"})}function Gu(){return new ne("OpenCode emitted malformed JSON output.",Ct,{code:"PROVIDER_CRASHED",kind:"transient"})}function mi(t,e){switch(yi(t)){case "length":return new ne("OpenCode stopped because the context window was exceeded.",Ct,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new ne("OpenCode stopped because the content filter blocked the response.",Ct,{code:"UNKNOWN",kind:"permanent"});case "error":return new ne(e?`OpenCode error: ${e}`:`${_i} while generating a response.`,Ct,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var Fu,Ct,_i,ki,Bu,zr,Vr=v(()=>{h();Xt();tn();bt();ft();Fu=new Set(["step_start","step_finish"]),Ct="cli/opencode",_i="OpenCode provider error",ki=240,Bu={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};zr={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Kn(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:a}=ju(e.mode);Kn(o,"--agent")||s!==void 0&&o.push("--agent",s),a&&!Kn(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!Kn(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let u;return !n&&!a&&!e.env?.OPENCODE_PERMISSION&&(u={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:u}},extractText(t){let e=hi(t),n=e.errorMessages[0];if(n){let a=mi("error",n);if(a)throw a}let r=mi(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 Jn();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Jn();return e.resultText}if(e.malformed)throw Gu();if(!e.hasTerminal)throw Jn();let s=yi(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Jn()},interpretExit(t,e,n=""){if(t===0)return null;let o=hi(n).errorMessages[0];return o?new ne(`OpenCode error: ${o}`,Ct,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=xt(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=Ti(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let a;try{a=JSON.parse(s);}catch{continue}let u=Ae(a,n),d=a.type;if(d){if(d==="text"){let l=a.part?.text;l&&r.push({timestamp:u,type:"text",content:l});continue}if(d==="tool_use"){let c=a.part;if(!c)continue;let l=String(c.tool||""),p=String(c.callID||""),g=c.state,m=String(g?.status||""),T=g?.input,E=qe(T);if(r.push({timestamp:u,type:"tool_use",toolName:l,toolUseId:p,toolInput:E}),m==="completed"&&g?.output!==void 0){let w=g.output,C=typeof w=="string"?w:JSON.stringify(w);r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:C,isError:false});}else m==="error"&&r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(d==="error"){let c=wi(a);r.push({timestamp:u,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?Fu.has(r):!1}catch{return false}}};});function nn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function zu(t,e){if(!(t?nt(Kr).some(s=>s.id===t):false)||!t)return e;let r=Zt(Kr,t),o=Vs(Kr)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var Kr,Jr,Xr=v(()=>{h();Xt();Qt();pt();en();Kr="antigravity";Jr={command:"agy",meta:{displayName:"Antigravity",models:Ys(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=rt(e.model),s=$r(r),a=s.model,u=e.effort??o??s.effort,d=zu(a,u),c=e.additionalArgs??[],l=a&&!nn(c,"--model")?["--model",a]:[],p=nn(c,"--effort")?[]:ci(d),g=nn(c,"--mode")||nn(c,"--dangerously-skip-permissions")?[]:ui(e.mode),m=nn(c,"--print")?[]:["--print",t];return {args:[...l,...p,...g,...c,...m]}},extractText(t){let e=t.trim();if(!e)throw new ne("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 Ei=v(()=>{h();Ot();bt();Yt();ft();});function Pt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yn(t){return Pt(t)?t:void 0}function ce(t){return typeof t=="string"?t:void 0}function ht(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Yu(t){let e=[],n=-1,r=0,o=false,s=false;for(let a=0;a<t.length;a+=1){let u=t[a];if(n===-1){(u==="{"||u==="[")&&(n=a,r=1);continue}if(s){s=false;continue}if(u==="\\"&&o){s=true;continue}if(u==='"'){o=!o;continue}o||(u==="{"||u==="["?r+=1:(u==="}"||u==="]")&&(r-=1,r===0&&(e.push(t.slice(n,a+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function rn(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Pt(n)?[n]:[]}catch{return Yu(e).flatMap(n=>{try{let r=JSON.parse(n);return Pt(r)?[r]:[]}catch{return []}})}}function on(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function sn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(sn).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
25
|
+
`):void 0}if(Pt(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=sn(t[e]);if(n!==void 0)return n}}}function Qu(t){if(t.rawOutput!==null&&t.rawOutput!==void 0)return sn(t.rawOutput)??on(t.rawOutput);if(t.content!==null&&t.content!==void 0)return sn(t.content)??on(t.content);if(t.result!==null&&t.result!==void 0)return sn(t.result)??on(t.result)}function vi(t){let e=Yn(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?Oi(n):"Grok CLI reported an error."}function Oi(t){return (t.replace(Xu,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Ai(t){return Ju.test(t)}function Zu(t){let e=Yn(t.modelUsage);return e?Object.keys(e)[0]??null:null}function ec(t){let e=Yn(t.usage);if(!e)return null;let n=ht(e.cache_read_input_tokens);return {inputTokens:ht(e.input_tokens)+n,cachedInputTokens:n,outputTokens:ht(e.output_tokens),costUsd:ht(t.total_cost_usd)}}function tc(t){let e=0,n=0,r=0,o=false,s=new Set;for(let a of t.split(`
|
|
26
|
+
`).flatMap(rn)){if(a.type!=="usage")continue;let u=Yn(a.usage);if(!u)continue;let d=ce(a.signature);if(d&&d.length>0){let l=`signature:${d}`;if(s.has(l))continue;s.add(l);}let c=ht(u.cache_read_input_tokens);e+=ht(u.input_tokens)+c,n+=c,r+=ht(u.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function nc(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,Ri)){if(!Pt(s))continue;let a=ce(s.content)?.trim();if(!a)continue;let u=ce(s.status)?.trim(),d=ce(s.priority)?.trim(),c=[u?`status=${u}`:void 0,d?`priority=${d}`:void 0].filter(p=>!!p),l=c.length>0?` (${c.join(", ")})`:"";n.push(`- ${a}${l}`);}if(n.length===0)return [];e.entries.length>Ri&&n.push(Ii);let r=n.join(`
|
|
27
|
+
`),o=r.length>Si?`${r.slice(0,Si-1)}${Ii}`:r;return [{timestamp:t,type:"info",content:o}]}function rc(t,e){let n=ce(e.type);if(n==="thought"){let r=ce(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=ce(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return nc(t,e);if(n==="tool_call"){let r=ce(e.toolCallId),o=ce(e.toolName)??ce(e.title),s=e.rawInput===void 0?void 0:on(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=ce(e.status);return r!=="completed"&&r!=="failed"&&r!=="error"?[]:[{timestamp:t,type:"tool_result",toolUseId:ce(e.toolCallId),toolName:ce(e.toolName)??ce(e.title),resultPreview:Qu(e),isError:r!=="completed"||e.isError===true}]}if(n==="error"){let r=vi(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var Xn,Ku,Ju,Xu,Ri,Si,Ii,Yr,Qr=v(()=>{h();Xt();Lr();pt();en();ft();Xn="cli/grok",Ku=new Set(["available_commands","usage","end"]),Ju=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,Xu=/\u001b\[[0-?]*[ -/]*[@-~]/g,Ri=20,Si=4e3,Ii="\u2026";Yr={command:"grok",createSessionId:()=>randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=rt(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],a=n?["--model",n]:[],u=n?nt("grok").some(q=>q.id===n):false,d=n&&u?Zt("grok",n):[],c=!o||d.length===0||d.includes(o)?o:void 0,l=di(c),p=e.additionalArgs??[],g=q=>p.some(y=>y===q||y.startsWith(`${q}=`)),m=e.providerOptions,T=m?.alwaysApprove,E=m?.sandbox,w=g("--permission-mode")?[]:si(e.mode),C=g("--always-approve")?[]:ii(T),M=g("--sandbox")?[]:ai(E);return {args:["--no-auto-update",...s,"--single",t,"--output-format","streaming-json","--no-alt-screen",...a,...l,...w,...C,...M,...p]}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
28
|
+
`).flatMap(rn))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 rn(t))if(e.type==="error"){let n=vi(e);return Ai(on(e))?new Ge(n,Xn):new ne(n,Xn)}return null},interpretExit(t,e){if(t===0)return null;let n=Oi(e)||`Grok CLI exited with code ${t}.`;return Ai(e)?new Ge(n,Xn):new ne(n,Xn)},parseResultMeta(t){let n=t.split(`
|
|
29
|
+
`).flatMap(rn).find(r=>r.type==="end");return n?{usage:ec(n),model:Zu(n)}:{usage:tc(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return rn(t).flatMap(r=>rc(Ae(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return Pt(n)&&typeof n.type=="string"?Ku.has(n.type):!1}catch{return false}}};});var bi,xi=v(()=>{h();Fr();jr();Gr();Vr();Xr();Ei();Qr();Fr();jr();Gr();Vr();Xr();Qr();Ot();bi={codex:Wr,claude:qr,opencode:zr,antigravity:Jr,copilot:Br,grok:Yr};});function Ci(t){if(t.startsWith("cli/"))return bi[t.slice(4)]}var Ni=v(()=>{h();js();xi();});function Qn(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function oc(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function Zn(t){if(typeof t.provider!="string"||t.provider.length===0)return;let n=t.taskLogRepository.readLogs(t.taskId)?.entries.filter(g=>g.level==="stdout").map(g=>g.message).join(`
|
|
30
|
+
`)??"";if(!n.trim())return;let r=Ci(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=oc(o?.model,t.model),a=o?.usage;if(!a)return {stdout:n,adapter:r};let u=Qn(a.inputTokens),d=Qn(a.outputTokens),c=Qn(a.cachedInputTokens),l=Os(Qn(a.costUsd),u,d,c,s);return u!==0||d!==0||c!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:u,outputTokens:d,cachedInputTokens:c,costUsd:l,model:s}}:{stdout:n,adapter:r}}var Zr=v(()=>{h();Ni();qn();});function ic(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.terminalReason;return typeof n=="string"&&sc.has(n)?n:void 0}catch{return}}function mt(t){switch(t.status){case "stopped":case "runner_lost":case "pending":case "running":case "paused":case "success":return t.status;case "completed":case "done":return "success";case "error":return "failed";case "failed":{let e=ic(t.metadata);return e==="user_stop"?"stopped":e==="runner_lost"?"runner_lost":e==="launch_failed"?"failed":typeof t.error=="string"&&Pi.stopped.test(t.error)?"stopped":typeof t.error=="string"&&Pi.runnerLost.test(t.error)?"runner_lost":"failed"}default:return t.status}}var Di,Pi,sc,er=v(()=>{h();Di=["success","failed","stopped","runner_lost"],Pi={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},sc=new Set(["user_stop","runner_lost","launch_failed"]);});function eo(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let o=Number(r);return !Number.isFinite(o)||o<=0?e:Math.max(n,Math.trunc(o))}function to(){return eo("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Lt(){return eo("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function nr(){return eo("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Dt(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function tr(t){let e=typeof t=="object"&&t!==null&&"code"in t?String(t.code):t instanceof Error?t.name:typeof t;console.warn(`[crewx] task heartbeat write failed (${e}); execution continues`);}function ac(t){return t?{id:t.id,status:t.status,run_epoch:t.run_epoch,stop_requested_at:t.stop_requested_at,stop_requested_epoch:t.stop_requested_epoch,pid:t.pid,metadata:t.metadata,started_at:t.started_at,duration_ms:t.duration_ms}:null}function Li(t,e){return !!t.stop_requested_at&&Dt(t.stop_requested_epoch)===Dt(e)}function Mi(t,e){let n=Dt(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=ac(t.getTask(e.taskId));return !o||o.status!=="running"||Dt(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function qi(t,e){let n=an.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),an.delete(t),true)}function dn(t,e){let n=an.get(t);return !n||e!==void 0&&n.runEpoch!==Dt(e)?false:qi(t,n)}function Fi(t,e){let n=Dt(e.runEpoch);dn(e.taskId);let r=true,o=null;try{let c=Mi(t,{...e,runEpoch:n});r=c.accepted,o=c.row;}catch(c){tr(c);}if(!r)return false;let s=to(),a=Math.min(s,1e3),u=setInterval(()=>{let c=an.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=a;let l=c.heartbeatElapsedMs>=s,p=Mi(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){qi(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=s,c.lastHeartbeatAt=Date.now()),p.row&&Li(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(tr));}catch(l){tr(l);}},a),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return an.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),o&&Li(o,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(tr)),true}var Hi,$i,Ui,an,un=v(()=>{h();Hi=1e4,$i=3e4,Ui=18e5;an=new Map;});function rr(t,e=Date.now(),n=so){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=uo(n,so,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function uo(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function zi(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function hc(t){if(!t)return;let e=zi(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function ge(t,e){if(!t)return {status:"not_running",finalStatus:"not_running",...e?{pid:e}:{}};let n=typeof t.pid=="number"&&t.pid>0?t.pid:e;if(t.status==="stopped"){let r=hc(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function fo(t,e,n="Process owner could not be verified"){let r=e??(t.pid&&t.pid>0?t.pid:void 0);return {status:"ownership_unverified",finalStatus:t.status,...r?{pid:r}:{},error:n}}function z(t,e,n){let r=n??(t?.pid&&t.pid>0?t.pid:void 0);return {status:"failed",finalStatus:t?.status??null,...r?{pid:r}:{},error:e}}function oo(t,e){return z(t,cc,e)}function mc(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Lt():false}function _c(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function kc(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=zi(t.metadata),r=n.ownership==="runner"&&typeof n.providerPid=="number"&&Number.isSafeInteger(n.providerPid)&&n.providerPid>0?n.providerPid:void 0;return [...new Set([e,r].filter(o=>o!==void 0))]}function Tc(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return ge(r,n)}async function wc(t,e,n,r){let o=Date.now()+n;for(;;){let s=Tc(t,e);if(s)return s;let a=o-Date.now();if(a<=0)return;await new Promise(u=>{setTimeout(u,Math.min(r,a));});}}async function Gi(t,e,n){let r=new Date().toISOString(),o={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},s=t.requestTaskStop({id:e,requestedAt:r,...o}),a=t.getTask(e);if(!s.accepted){if(s.status==="pending"){let q=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),y=t.getTask(e);if(q||!y||y.status!=="running")return ge(y);if(s=t.requestTaskStop({id:e,requestedAt:r,...o}),!s.accepted&&s.status!=="running"||!s.accepted&&!s.alreadyRequestedAt)return ge(t.getTask(e))}else if(!(s.status==="running"&&s.alreadyRequestedAt))return ge(a)}let u=s.runEpoch,d=uo(n.graceMs,so,0),c=uo(n.pollMs,dc,1),l=await wc(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return ge(p);let g=kc(p),m=g[0];if(!m){let q=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),y=t.getTask(e);return q||y?.status!=="running"?ge(y):z(y,"Failed to finalize task stop")}let T=_c(n),E="unknown";if(!mc(p,Date.now())){let q=n.processControl?.checkProcessOwnershipAsync??Fn;try{E=await q(m,n.ownershipMarkers??po,T);}catch{E="unknown";}if(E!=="owned")return fo(p)}let w=n.processControl?.terminateProcessTree??vt;for(let q of g){let y;try{y=await w(q,{...T,signal:At});}catch(x){y={status:"failed",pid:q,method:T.platform==="win32"?"taskkill":"process-group",error:x instanceof Error?x.message:String(x)};}if(y.status==="failed")return z(t.getTask(e),y.error??"Failed to terminate process tree")}let C=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),M=t.getTask(e);return C||M?.status!=="running"?ge(M,m):z(M,"Task changed before stop was finalized")}function co(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function lo(t){return Number.isSafeInteger(t)&&t>=0}function cn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function yc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Ec(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Rc(t,e){let n=t?.pid&&t.pid>0?t.pid:e;return {status:"stopped",method:"forced",finalStatus:t?.status??"runner_lost",...n?{pid:n}:{}}}function Sc(t){switch(t){case "epoch_mismatch":return io;case "workspace_mismatch":return ao;default:return}}async function Vi(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return oo(n,co(e.targetPid)?e.targetPid:void 0);if(!lo(e.sourceRunEpoch)||!lo(e.settleRunEpoch)||cn(n.run_epoch)!==e.settleRunEpoch)return z(n,no,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,ro,e.targetPid);let r=new Date().toISOString(),o;try{o=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return z(n,lc,e.targetPid)}let s=t.getTask(e.taskId);if(!s||s.status!=="running")return oo(s,e.targetPid);if(o.runEpoch!==e.settleRunEpoch||cn(s.run_epoch)!==e.settleRunEpoch)return z(s,no,e.targetPid);if(e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId)return z(s,ro,e.targetPid);if(!co(e.targetPid))return z(s,uc);let a=yc(e),u=e.processControl?.checkProcessOwnershipAsync??Fn,d="unknown";try{d=await u(e.targetPid,e.ownershipMarkers??po,a);}catch{d="unknown";}if(d!=="owned")return fo(s,e.targetPid);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return oo(c,e.targetPid);if(cn(c.run_epoch)!==e.settleRunEpoch)return z(c,no,e.targetPid);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,ro,e.targetPid);let l=e.processControl?.terminateProcessTree??vt,p;try{p=await l(e.targetPid,{...a,signal:At});}catch{return z(t.getTask(e.taskId),Bi,e.targetPid)}if(p.status==="failed")return z(t.getTask(e.taskId),Bi,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return z(t.getTask(e.taskId),ji,e.targetPid)}return g?ge(t.getTask(e.taskId),e.targetPid):z(t.getTask(e.taskId),ji,e.targetPid)}async function Ki(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return ge(n);if(!lo(e.expectedRunEpoch)||cn(n.run_epoch)!==e.expectedRunEpoch)return z(n,io);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,ao);let r=n.pid;if(!co(r))return z(n,pc);let o=Ec(e),s=e.processControl?.checkProcessOwnershipAsync??Fn,a="unknown";try{a=await s(r,e.ownershipMarkers??po,o);}catch{a="unknown";}if(a!=="owned")return fo(n,r,fc);let u=e.processControl?.terminateProcessTree??vt,d;try{d=await u(r,{...o,signal:At});}catch{return z(t.getTask(e.taskId),Wi,r)}if(d.status==="failed")return z(t.getTask(e.taskId),Wi,r);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return ge(c,r);if(cn(c.run_epoch)!==e.expectedRunEpoch)return z(c,io,r);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,ao,r);let l;try{l=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return z(t.getTask(e.taskId),gc,r)}let p=Sc(l);return p?z(t.getTask(e.taskId),p,r):l!=="settled"?ge(t.getTask(e.taskId),r):Rc(t.getTask(e.taskId),r)}function Ji(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(ho(),Xi)).then(({TaskRepository:s})=>Gi(new s,r,o))}return Gi(t,e,n)}var so,dc,po,uc,no,ro,cc,Bi,ji,lc,io,ao,pc,fc,Wi,gc,go=v(()=>{h();Bn();un();so=5e3,dc=250;po=["crewx","claude","codex","opencode","grok","node"],uc="INSTRUCTION_STOP_TARGET_PID_MISSING",no="INSTRUCTION_STOP_EPOCH_MISMATCH",ro="INSTRUCTION_STOP_WORKSPACE_MISMATCH",cc="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",Bi="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",ji="INSTRUCTION_STOP_SETTLE_CAS_FAILED",lc="INSTRUCTION_STOP_REQUEST_FAILED",io="HOST_SHUTDOWN_EPOCH_MISMATCH",ao="HOST_SHUTDOWN_WORKSPACE_MISMATCH",pc="HOST_SHUTDOWN_TARGET_PID_MISSING",fc="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",Wi="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",gc="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var Xi={};xa(Xi,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>sa,HOST_SHUTDOWN_TERMINAL_ERROR:()=>na,PENDING_ADOPT_GRACE_MS:()=>oa,PID_NULL_REAP_GRACE_MS:()=>Ro,TASK_HEARTBEAT_HARD_STALE_MS:()=>Ui,TASK_HEARTBEAT_INTERVAL_MS:()=>Hi,TASK_HEARTBEAT_STALE_MS:()=>$i,TaskRepository:()=>hn,hasRecordedUsage:()=>Eo,mergeTerminalReason:()=>yo,resolveTaskHeartbeatHardStaleMs:()=>nr,resolveTaskHeartbeatIntervalMs:()=>to,resolveTaskHeartbeatStaleMs:()=>Lt});function Oe(t){return {...t,status:mt(t)}}function Yi(t){return {...t,status:mt(t)}}function Qi(){let t=sql`
|
|
26
31
|
CASE
|
|
27
32
|
WHEN ${i.model} LIKE 'claude-%' OR ${i.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
28
33
|
WHEN ${i.model} LIKE 'gpt-%' OR ${i.model} LIKE 'codex-%' THEN 'codex'
|
|
@@ -51,7 +56,7 @@ ${r.join(`
|
|
|
51
56
|
WHEN trim(${o}) = '' THEN 'unknown'
|
|
52
57
|
ELSE ${o}
|
|
53
58
|
END
|
|
54
|
-
`}function
|
|
59
|
+
`}function gn(t){return sql`${t} NOT IN (${sql.join(Pc.map(e=>sql`${e}`),sql`, `)})`}function or(t){let e=sql`
|
|
55
60
|
CASE
|
|
56
61
|
WHEN json_valid(${t}) = 1
|
|
57
62
|
THEN json_extract(${t}, '$.usageAccounting')
|
|
@@ -61,29 +66,27 @@ ${r.join(`
|
|
|
61
66
|
COALESCE(SUM(
|
|
62
67
|
CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
|
|
63
68
|
), 0)
|
|
64
|
-
`}function pn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ue(t){if(!t)return {};try{let e=JSON.parse(t);return pn(e)?{...e}:{}}catch{return {}}}function mo(t,e){let n=ue(t??null);return n.terminalReason=e,JSON.stringify(n)}function ho(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==Vi&&(n[Tc]=e),{error:Vi,metadata:n}}function ne(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function _o(t){return ne(t.input_tokens)!==0||ne(t.output_tokens)!==0||ne(t.cached_input_tokens)!==0||ne(t.cost_usd)!==0}function V(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Ki(t){return {inputTokens:ne(t.inputTokens??0),outputTokens:ne(t.outputTokens??0),cachedInputTokens:ne(t.cachedInputTokens??0),costUsd:ne(t.costUsd??0)}}function Ec(t){if(pn(t))return {inputTokens:ne(t.inputTokens),outputTokens:ne(t.outputTokens),cachedInputTokens:ne(t.cachedInputTokens),costUsd:ne(t.costUsd)}}function Rc(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=Ec(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Zn(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}var fo,Ve,_c,Ke,Je,kc,go,cn,Oe,Vi,Ji,Tc,wc,yc,ko,Xi,Yi,fn,lo=v(()=>{h();it();_t();Tt();ot();Et();Dn();Mn();Ls();Jr();Kn();sn();co();sn();fo=40,Ve="2026-05-09",_c="0.8.9-rc.13",Ke=10,Je=parseInt(_c.split("rc.")[1]);kc=new Set(["workflow","mcp"]),go="usageByEpoch",cn="lateUsage",Oe="usageAccounting",Vi="Stopped by user",Ji="Stopped by app shutdown",Tc="terminalErrorOriginal",wc=new Set(["stopped","runner_lost"]),yc=["pending","running"];ko=600*1e3,Xi=600*1e3,Yi=300*1e3,fn=class extends he{dbPath;clock;taskLogRepository;lastReaperTickAt;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Hn({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?st(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 f("NOT_FOUND","Database not found");let r=W(n);if(e)try{Ce(r.db,n);}catch(o){throw r.close(),o}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=V(e.runEpoch),o=r===0?or$1(eq(i.run_epoch,0),isNull(i.run_epoch)):eq(i.run_epoch,r);return n.db.update(i).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(and(eq(i.id,e.id),o,eq(i.status,"running"))).run().changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:i.id,status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!s)return;let a=V(s.run_epoch);if(s.status!=="running"){r={accepted:!1,status:s.status,runEpoch:a};return}let u=s.stop_requested_at!==null&&V(s.stop_requested_epoch)===a?s.stop_requested_at:e.requestedAt;if(o.update(i).set({stop_requested_at:e.requestedAt,stop_requested_epoch:sql`${i.run_epoch}`}).where(and(eq(i.id,e.id),eq(i.status,"running"),sql`${i.stop_requested_at} IS NULL
|
|
65
|
-
OR COALESCE(${i.stop_requested_epoch}, 0) <> COALESCE(${i.run_epoch}, 0)`)).run().changes===0){let g=o.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!g||g.status!=="running"){r={accepted:!1,status:g?.status??"not_running",runEpoch:V(g?.run_epoch)};return}r={accepted:!1,status:g.status,runEpoch:V(g.run_epoch),...g.stop_requested_at&&V(g.stop_requested_epoch)===V(g.run_epoch)?{alreadyRequestedAt:g.stop_requested_at}:{}};}else r={accepted:!0,status:s.status,runEpoch:a};let l=new Set([e.id]),p=(g,m)=>{if(m>=8)return;let S=o.select({id:i.id,status:i.status}).from(i).where(and(eq(i.parent_task_id,g),eq(i.status,"running"))).all();for(let w of S)l.has(w.id)||(l.add(w.id),o.update(i).set({stop_requested_at:u,stop_requested_epoch:sql`${i.run_epoch}`}).where(and(eq(i.id,w.id),eq(i.status,"running"),sql`${i.stop_requested_at} IS NULL
|
|
66
|
-
OR COALESCE(${i.stop_requested_epoch}, 0) <> COALESCE(${i.run_epoch}, 0)`)).run(),p(w.id,m+1));};p(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:i.id,status:i.status,run_epoch:i.run_epoch,workspace_id:i.workspace_id,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!s)return;let a=V(s.run_epoch),d=V(e.sourceRunEpoch),u=V(e.settleRunEpoch);if(s.status!=="running"||a!==u||e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId){r={accepted:!1,status:s.status,runEpoch:a};return}let c=u===0?or$1(eq(i.run_epoch,0),isNull(i.run_epoch)):eq(i.run_epoch,u),l=or$1(isNull(i.stop_requested_at),isNull(i.stop_requested_epoch),ne$1(i.stop_requested_epoch,d)),p=w=>o.update(i).set({stop_requested_at:e.requestedAt,stop_requested_epoch:d}).where(and(eq(i.id,e.id),eq(i.status,"running"),c,w,l)).run();if((e.workspaceId===void 0?p():e.workspaceId===null?p(isNull(i.workspace_id)):p(eq(i.workspace_id,e.workspaceId))).changes>0){r={accepted:!0,status:s.status,runEpoch:u};return}let m=o.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:V(m?.run_epoch)};return}let S=V(m.run_epoch);r={accepted:!1,status:m.status,runEpoch:S,...m.stop_requested_at&&V(m.stop_requested_epoch)===d?{alreadyRequestedAt:m.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=!1;return n.db.transaction(s=>{let a=s.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch,started_at:i.started_at,duration_ms:i.duration_ms,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!a||a.status!=="running"||V(a.run_epoch)!==V(e.runEpoch))return;let d=a.stop_requested_at!==null&&V(a.stop_requested_epoch)===V(e.runEpoch),u=ue(a.metadata),c=d?ho(u,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...u}:{...u,terminalReason:e.terminalReason}},l={...c.metadata,stopMethod:e.method},p=a.duration_ms??e.durationMs??Zn(a.started_at,r,void 0),g=a.run_epoch===null?isNull(i.run_epoch):eq(i.run_epoch,a.run_epoch);o=s.update(i).set({status:"stopped",error:c.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(and(eq(i.id,e.id),eq(i.status,"running"),g)).run().changes>0;},{behavior:"immediate"}),o}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=V(e.expectedRunEpoch),s="not_running";return n.db.transaction(a=>{let d=a.select({status:i.status,run_epoch:i.run_epoch,workspace_id:i.workspace_id,started_at:i.started_at,duration_ms:i.duration_ms,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!d||d.status!=="running"){s="not_running";return}if(V(d.run_epoch)!==o){s="epoch_mismatch";return}if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId){s="workspace_mismatch";return}let c=d.run_epoch===null?isNull(i.run_epoch):eq(i.run_epoch,d.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?isNull(i.workspace_id):eq(i.workspace_id,e.workspaceId),p={...ue(d.metadata),terminalReason:"runner_lost"},g=d.duration_ms??Zn(d.started_at,r,void 0);s=a.update(i).set({status:"runner_lost",error:Ji,completed_at:r,duration_ms:g,metadata:JSON.stringify(p)}).where(and(eq(i.id,e.id),eq(i.status,"running"),c,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),s}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return Bi(this,e,n)}async stopTaskGenerationForInstruction(e){return Fi({requestTaskStop:n=>this.requestTaskStopForInstruction(n),getTask:n=>this.getTask(n),finalizeTaskStop:n=>this.finalizeTaskStop(n)},e)}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(i).values(s).onConflictDoUpdate({target:i.id,set:{status:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN 'running' ELSE ${i.status} END`,pid:sql`COALESCE(excluded.pid, ${i.pid})`,command:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.command ELSE ${i.command} END`,metadata:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.metadata ELSE ${i.metadata} END`,workspace_id:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN COALESCE(${i.workspace_id}, excluded.workspace_id) ELSE ${i.workspace_id} END`,project_id:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN COALESCE(${i.project_id}, excluded.project_id) ELSE ${i.project_id} END`,crewx_version:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.crewx_version ELSE ${i.crewx_version} END`,model:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.model ELSE ${i.model} END`,rendered_prompt:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.rendered_prompt ELSE ${i.rendered_prompt} END`,coding_agent_command:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.coding_agent_command ELSE ${i.coding_agent_command} END`},setWhere:or$1(eq(i.status,"running"),and(eq(i.status,"pending"),isNull(i.pid)))}).run();};try{o(r);}catch(s){let a=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch/i.test(a)||!/no such column|no column named/i.test(a))throw s;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(g=>g.name)).has("log_storage"),c=u?", log_storage":"",l=u?", ?":"",p=u?`,
|
|
69
|
+
`}function Ht(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Z(t){if(!t)return {};try{let e=JSON.parse(t);return Ht(e)?{...e}:{}}catch{return {}}}function sr(t,e){let n=t.origin&&ra.has(t.origin)?t.origin:"internal",r=t.callerPid!==void 0&&Number.isInteger(t.callerPid)&&t.callerPid>0?t.callerPid:process.pid;return {origin:n,at:t.at??e,callerPid:r,...t.callerTaskId?{callerTaskId:t.callerTaskId}:{}}}function Dc(t){let e=Z(t).stopRequest;if(Ht(e)&&!(typeof e.origin!="string"||!ra.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function ea(){return or$1(isNull(i.stop_requested_at),ne$1(sql`COALESCE(${i.stop_requested_epoch}, 0)`,sql`COALESCE(${i.run_epoch}, 0)`))}function yo(t,e){let n=Z(t??null);return n.terminalReason=e,JSON.stringify(n)}function To(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==Zi&&(n[Cc]=e),{error:Zi,metadata:n}}function re(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Eo(t){return re(t.input_tokens)!==0||re(t.output_tokens)!==0||re(t.cached_input_tokens)!==0||re(t.cost_usd)!==0}function V(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function ta(t){return {inputTokens:re(t.inputTokens??0),outputTokens:re(t.outputTokens??0),cachedInputTokens:re(t.cachedInputTokens??0),costUsd:re(t.costUsd??0)}}function Lc(t){if(Ht(t))return {inputTokens:re(t.inputTokens),outputTokens:re(t.outputTokens),cachedInputTokens:re(t.cachedInputTokens),costUsd:re(t.costUsd)}}function Mc(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=Lc(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function ir(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}var _o,Ke,bc,Je,Xe,xc,ko,fn,be,Zi,na,Cc,Nc,Pc,ra,Ro,oa,sa,hn,ho=v(()=>{h();dt();wt();yt();it();St();qn();Bn();Bs();Zr();er();un();go();un();_o=40,Ke="2026-05-09",bc="0.8.9-rc.13",Je=10,Xe=parseInt(bc.split("rc.")[1]);xc=new Set(["workflow","mcp"]),ko="usageByEpoch",fn="lateUsage",be="usageAccounting",Zi="Stopped by user",na="Stopped by app shutdown",Cc="terminalErrorOriginal",Nc=new Set(["stopped","runner_lost"]),Pc=["pending","running"];ra=new Set(["http","cli","instruction","workflow","internal"]);Ro=600*1e3,oa=600*1e3,sa=300*1e3,hn=class extends ke{dbPath;clock;taskLogRepository;lastReaperTickAt;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new jn({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?at(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 f("NOT_FOUND","Database not found");let r=W(n);if(e)try{Ne(r.db,n);}catch(o){throw r.close(),o}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=V(e.runEpoch),o=r===0?or$1(eq(i.run_epoch,0),isNull(i.run_epoch)):eq(i.run_epoch,r);return n.db.update(i).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(and(eq(i.id,e.id),o,eq(i.status,"running"))).run().changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:i.id,status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!s)return;let a=V(s.run_epoch);if(s.status!=="running"){r={accepted:!1,status:s.status,runEpoch:a};return}let u=s.stop_requested_at!==null&&V(s.stop_requested_epoch)===a,d=u?s.stop_requested_at:e.requestedAt,c=Z(s.metadata),l=u?Dc(s.metadata)??sr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):sr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(o.update(i).set({stop_requested_at:e.requestedAt,stop_requested_epoch:sql`${i.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(and(eq(i.id,e.id),eq(i.status,"running"),ea())).run().changes===0){let T=o.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!T||T.status!=="running"){r={accepted:!1,status:T?.status??"not_running",runEpoch:V(T?.run_epoch)};return}r={accepted:!1,status:T.status,runEpoch:V(T.run_epoch),...T.stop_requested_at&&V(T.stop_requested_epoch)===V(T.run_epoch)?{alreadyRequestedAt:T.stop_requested_at}:{}};}else r={accepted:!0,status:s.status,runEpoch:a};let g=new Set([e.id]),m=(T,E)=>{if(E>=8)return;let w=o.select({id:i.id,status:i.status,metadata:i.metadata}).from(i).where(and(eq(i.parent_task_id,T),eq(i.status,"running"))).all();for(let C of w)g.has(C.id)||(g.add(C.id),o.update(i).set({stop_requested_at:d,stop_requested_epoch:sql`${i.run_epoch}`,metadata:JSON.stringify({...Z(C.metadata),stopRequest:l})}).where(and(eq(i.id,C.id),eq(i.status,"running"),ea())).run(),m(C.id,E+1));};m(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:i.id,status:i.status,run_epoch:i.run_epoch,workspace_id:i.workspace_id,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!s)return;let a=V(s.run_epoch),u=V(e.sourceRunEpoch),d=V(e.settleRunEpoch);if(s.status!=="running"||a!==d||e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId){r={accepted:!1,status:s.status,runEpoch:a};return}let c=d===0?or$1(eq(i.run_epoch,0),isNull(i.run_epoch)):eq(i.run_epoch,d),l=or$1(isNull(i.stop_requested_at),isNull(i.stop_requested_epoch),ne$1(i.stop_requested_epoch,u)),p=sr({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),g=w=>o.update(i).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:JSON.stringify({...Z(s.metadata),stopRequest:p})}).where(and(eq(i.id,e.id),eq(i.status,"running"),c,w,l)).run();if((e.workspaceId===void 0?g():e.workspaceId===null?g(isNull(i.workspace_id)):g(eq(i.workspace_id,e.workspaceId))).changes>0){r={accepted:!0,status:s.status,runEpoch:d};return}let T=o.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!T||T.status!=="running"){r={accepted:!1,status:T?.status??"not_running",runEpoch:V(T?.run_epoch)};return}let E=V(T.run_epoch);r={accepted:!1,status:T.status,runEpoch:E,...T.stop_requested_at&&V(T.stop_requested_epoch)===u?{alreadyRequestedAt:T.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=!1;return n.db.transaction(s=>{let a=s.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch,started_at:i.started_at,duration_ms:i.duration_ms,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!a||a.status!=="running"||V(a.run_epoch)!==V(e.runEpoch))return;let u=a.stop_requested_at!==null&&V(a.stop_requested_epoch)===V(e.runEpoch),d=Z(a.metadata),c=u?To(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...c.metadata,stopMethod:e.method},p=a.duration_ms??e.durationMs??ir(a.started_at,r,void 0),g=a.run_epoch===null?isNull(i.run_epoch):eq(i.run_epoch,a.run_epoch);o=s.update(i).set({status:"stopped",error:c.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(and(eq(i.id,e.id),eq(i.status,"running"),g)).run().changes>0;},{behavior:"immediate"}),o}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=V(e.expectedRunEpoch),s="not_running";return n.db.transaction(a=>{let u=a.select({status:i.status,run_epoch:i.run_epoch,workspace_id:i.workspace_id,started_at:i.started_at,duration_ms:i.duration_ms,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!u||u.status!=="running"){s="not_running";return}if(V(u.run_epoch)!==o){s="epoch_mismatch";return}if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId){s="workspace_mismatch";return}let c=u.run_epoch===null?isNull(i.run_epoch):eq(i.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?isNull(i.workspace_id):eq(i.workspace_id,e.workspaceId),p={...Z(u.metadata),terminalReason:"runner_lost"},g=u.duration_ms??ir(u.started_at,r,void 0);s=a.update(i).set({status:"runner_lost",error:na,completed_at:r,duration_ms:g,metadata:JSON.stringify(p)}).where(and(eq(i.id,e.id),eq(i.status,"running"),c,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),s}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return Ji(this,e,n)}async stopTaskGenerationForInstruction(e){return Vi({requestTaskStop:n=>this.requestTaskStopForInstruction(n),getTask:n=>this.getTask(n),finalizeTaskStop:n=>this.finalizeTaskStop(n)},e)}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,cwd:e.cwd??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(i).values(s).onConflictDoUpdate({target:i.id,set:{status:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN 'running' ELSE ${i.status} END`,pid:sql`COALESCE(excluded.pid, ${i.pid})`,command:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.command ELSE ${i.command} END`,metadata:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.metadata ELSE ${i.metadata} END`,workspace_id:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN COALESCE(${i.workspace_id}, excluded.workspace_id) ELSE ${i.workspace_id} END`,cwd:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN COALESCE(${i.cwd}, excluded.cwd) ELSE ${i.cwd} END`,project_id:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN COALESCE(${i.project_id}, excluded.project_id) ELSE ${i.project_id} END`,crewx_version:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.crewx_version ELSE ${i.crewx_version} END`,model:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.model ELSE ${i.model} END`,rendered_prompt:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.rendered_prompt ELSE ${i.rendered_prompt} END`,coding_agent_command:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.coding_agent_command ELSE ${i.coding_agent_command} END`},setWhere:or$1(eq(i.status,"running"),and(eq(i.status,"pending"),isNull(i.pid)))}).run();};try{o(r);}catch(s){let a=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|cwd/i.test(a)||!/no such column|no column named/i.test(a))throw s;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(w=>w.name)),d=u.has("cwd"),c=u.has("log_storage"),l=d?", cwd":"",p=d?", ?":"",g=d?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",m=c?", log_storage":"",T=c?", ?":"",E=c?`,
|
|
67
70
|
log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
|
|
68
71
|
id, agent_id, prompt, mode, status, started_at, pid,
|
|
69
72
|
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
70
|
-
workspace_id, project_id, platform, crewx_version, thread_id,
|
|
71
|
-
model, rendered_prompt, coding_agent_command${
|
|
72
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${
|
|
73
|
+
workspace_id${l}, project_id, platform, crewx_version, thread_id,
|
|
74
|
+
model, rendered_prompt, coding_agent_command${m}
|
|
75
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${p}${T})
|
|
73
76
|
ON CONFLICT(id) DO UPDATE SET
|
|
74
77
|
status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
|
|
75
78
|
pid = COALESCE(excluded.pid, tasks.pid),
|
|
76
79
|
command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.command ELSE tasks.command END,
|
|
77
80
|
metadata = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.metadata ELSE tasks.metadata END,
|
|
78
|
-
workspace_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.workspace_id, excluded.workspace_id) ELSE tasks.workspace_id END,
|
|
81
|
+
workspace_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.workspace_id, excluded.workspace_id) ELSE tasks.workspace_id END${g},
|
|
79
82
|
project_id = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.project_id, excluded.project_id) ELSE tasks.project_id END,
|
|
80
83
|
crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
|
|
81
84
|
model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
|
|
82
85
|
rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
|
|
83
|
-
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${
|
|
84
|
-
WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[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,...
|
|
85
|
-
AND COALESCE(${i.stop_requested_epoch}, 0) <> COALESCE(${i.run_epoch}, 0)`)).run(),a.changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(i).set({status:"running"}).where(and(eq(i.id,e),eq(i.status,"pending"),isNull(i.pid))).run().changes===1}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let o=this.openHandle(true);try{return o.db.update(i).set({status:"failed",error:n,completed_at:r}).where(and(eq(i.id,e),eq(i.status,"pending"))).run().changes>0}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to fail pending task",s)}finally{o.close();}}stopPendingTask(e,n,r=new Date().toISOString()){let
|
|
86
|
-
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=and(eq(i.id,e.id),eq(i.workspace_id,e.workspaceId)),o={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let s=n.db.select({metadata:i.metadata}).from(i).where(r).limit(1).get(),a=
|
|
86
|
+
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${E}
|
|
87
|
+
WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[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,...d?[r.cwd]:[],r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command,...c?[r.log_storage]:[]]);}}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to start task",r)}finally{n.close();}}updateTaskOwnership(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:i.status,run_epoch:i.run_epoch,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!r||r.status!=="running"||V(r.run_epoch)!==V(e.runEpoch))return !1;let o=Z(r.metadata);o.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0&&(o.providerPid=e.providerPid);let s=r.run_epoch===null?isNull(i.run_epoch):eq(i.run_epoch,r.run_epoch),a=n.db.update(i).set({metadata:JSON.stringify(o)}).where(and(eq(i.id,e.id),eq(i.status,"running"),s)).run();return a.changes>0&&V(e.runEpoch)>0&&n.db.update(i).set({stop_requested_at:null,stop_requested_epoch:null}).where(and(eq(i.id,e.id),eq(i.status,"running"),s,sql`${i.stop_requested_at} IS NOT NULL
|
|
88
|
+
AND COALESCE(${i.stop_requested_epoch}, 0) <> COALESCE(${i.run_epoch}, 0)`)).run(),a.changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(i).set({status:"running"}).where(and(eq(i.id,e),eq(i.status,"pending"),isNull(i.pid))).run().changes===1}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let o=this.openHandle(true);try{return o.db.update(i).set({status:"failed",error:n,completed_at:r}).where(and(eq(i.id,e),eq(i.status,"pending"))).run().changes>0}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to fail pending task",s)}finally{o.close();}}stopPendingTask(e,n,r=new Date().toISOString(),o={}){let s=this.openHandle(true);try{let a=!1;return s.db.transaction(u=>{let d=u.select({metadata:i.metadata}).from(i).where(and(eq(i.id,e),eq(i.status,"pending"))).limit(1).get();if(!d)return;let c=To(Z(d.metadata),n),l={...c.metadata,stopMethod:"cooperative",stopRequest:sr(o,r)};a=u.update(i).set({status:"stopped",error:c.error,completed_at:r,metadata:JSON.stringify(l)}).where(and(eq(i.id,e),eq(i.status,"pending"))).run().changes===1;},{behavior:"immediate"}),a}catch(a){throw a instanceof f?a:new f("DB_ERROR","Failed to stop pending task",a)}finally{s.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(i).where(eq(i.project_id,e)).orderBy(desc(i.started_at)).all().map(Oe)}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true),r,o;try{n.db.transaction(s=>{let a=s.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch,started_at:i.started_at,duration_ms:i.duration_ms,result:i.result,exit_code:i.exit_code,error:i.error,metadata:i.metadata,model:i.model,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cached_input_tokens:i.cached_input_tokens,cost_usd:i.cost_usd}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!a)return;let u=V(a.run_epoch),d=V(e.runEpoch),c=a.status==="running"&&u===d,l=a.stop_requested_at!==null&&V(a.stop_requested_epoch)===u,p=c&&l,g=a.status==="stopped"&&u===d&&l,m=Z(a.metadata),T=Ht(m[fn])?m[fn]:{},E=String(d),w=Nc.has(a.status),C=w&&u===d&&!Eo(a)&&!Object.prototype.hasOwnProperty.call(T,E),M=w&&u===d&&!Object.prototype.hasOwnProperty.call(T,E),q=u>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||u!==d,y={},x;if(a.status!=="running"&&(r=a.status,o=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),q&&(a.status==="running"||M)){x=Z(a.metadata);let A=Ht(x[ko])?{...x[ko]}:{};A[String(d)]=ta(e),x[ko]=A;let Q=Mc(A),_e=Q.inputTokens!==0||Q.outputTokens!==0||Q.cachedInputTokens!==0||Q.costUsd!==0;_e&&m[be]==="unavailable"?x[be]="recorded":a.status!=="running"&&!_e&&m[be]===void 0&&(x[be]="unavailable"),y.metadata=JSON.stringify(x),y.input_tokens=Q.inputTokens,y.output_tokens=Q.outputTokens,y.cached_input_tokens=Q.cachedInputTokens,y.cost_usd=Q.costUsd;}else if(c||C)if(c)y.input_tokens=re(e.inputTokens??0),y.output_tokens=re(e.outputTokens??0),y.cached_input_tokens=re(e.cachedInputTokens??0),y.cost_usd=re(e.costUsd??0);else {let A=ta(e),Q=A.inputTokens!==0||A.outputTokens!==0||A.cachedInputTokens!==0||A.costUsd!==0;Q&&(y.input_tokens=A.inputTokens,y.output_tokens=A.outputTokens,y.cached_input_tokens=A.cachedInputTokens,y.cost_usd=A.costUsd),x={...m};let _e=Ht(m[fn])?{...m[fn]}:{};_e[E]={at:e.completedAt},x[fn]=_e,x[be]===void 0?x[be]=Q?"recorded":"unavailable":Q&&x[be]==="unavailable"&&(x[be]="recorded"),y.metadata=JSON.stringify(x);}if((c||C)&&e.model!==void 0&&e.model!==null&&(!C||a.model===null)&&(y.model=e.model),p){x??=Z(a.metadata);let A=To(x,e.error);x={...A.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:rr(a.stop_requested_at,e.completedAt)},y.status="stopped",y.result=e.result??a.result,y.error=A.error,y.completed_at=e.completedAt,y.duration_ms=a.duration_ms??e.durationMs??ir(a.started_at,e.completedAt,void 0),y.exit_code=e.exitCode??a.exit_code,y.metadata=JSON.stringify(x);}else if(c)e.partialResultRecovered===!0&&(x??=Z(a.metadata),x.partialResultRecovered=!0,y.metadata=JSON.stringify(x)),y.status=e.status,y.result=e.result??null,y.error=e.error??null,y.completed_at=e.completedAt,y.duration_ms=u>0?ir(a.started_at,e.completedAt,e.durationMs):e.durationMs??null,y.exit_code=e.exitCode??null;else if(g){let A=!1;a.result===null&&e.result!==void 0&&e.result!==null&&(y.result=e.result,A=!0),a.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(y.exit_code=e.exitCode),e.partialResultRecovered===!0&&(x??=Z(a.metadata),x.partialResultRecovered=!0,y.metadata=JSON.stringify(x)),A&&(r=void 0,o=void 0);}Object.keys(y).length>0&&s.update(i).set(y).where(eq(i.id,e.id)).run();},{behavior:"immediate"});}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to finish task",s)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:o??`task:end status=${e.status}`});}catch(s){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${s instanceof Error?s.message:String(s)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
|
|
89
|
+
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=and(eq(i.id,e.id),eq(i.workspace_id,e.workspaceId)),o={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let s=n.db.select({metadata:i.metadata}).from(i).where(r).limit(1).get(),a=Z(s?.metadata??null);a.terminalReason=e.terminalReason,o.metadata=JSON.stringify(a);}n.db.update(i).set(o).where(r).run();}catch(r){throw r instanceof f?r:new f("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(i).where(eq(i.status,"running")).orderBy(desc(i.started_at)).all().map(Oe)}catch(n){throw new f("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getActiveTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(i).where(inArray(i.status,["pending","running"])).orderBy(desc(i.started_at)).all().map(Oe)}catch(n){throw new f("DB_ERROR","Failed to get active tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(i).orderBy(desc(i.started_at)).limit(100).all().map(Oe)}catch(n){throw new f("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select().from(i).where(eq(i.id,e)).limit(1).get();return r?Oe(r):void 0}catch(r){throw new f("DB_ERROR","Failed to get task",r)}finally{n.close();}}async killTask(e){let n=await this.stopTask(e);return n.status==="stopped"?{status:"terminated",killed:n.method==="forced"||n.method==="cooperative",...n.pid?{pid:n.pid}:{}}:n.status==="not_running"?{status:"not_running",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}:{status:"failed",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}}reapOrphanedTasks(e={}){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=n.db.select({id:i.id,status:i.status,pid:i.pid,platform:i.platform,run_epoch:i.run_epoch,heartbeat_at:i.heartbeat_at,started_at:i.started_at,metadata:i.metadata,model:i.model,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cached_input_tokens:i.cached_input_tokens,cost_usd:i.cost_usd}).from(i).where(or$1(eq(i.status,"running"),eq(i.status,"pending"))).all(),o=this.clock(),s=Math.max(1,Math.trunc(e.tickIntervalMs??sa)),a=this.lastReaperTickAt,u=a===void 0?Number.POSITIVE_INFINITY:o-a,d=a!==void 0&&u>=0&&u<=s*2;this.lastReaperTickAt=o;let c=Lt(),l=nr(),p=new Date(o-oa).toISOString(),g=new Date(o).toISOString(),m=new Set,T=0,E=(w,C)=>{let M=Z(yo(w.metadata,"runner_lost")),q=typeof M.provider=="string"?M.provider:void 0,y;try{y=Zn({taskLogRepository:this.taskLogRepository,taskId:w.id,provider:q,model:w.model})?.usage;}catch{}let x={status:"runner_lost",error:C,completed_at:g};y?(x.input_tokens=y.inputTokens,x.output_tokens=y.outputTokens,x.cached_input_tokens=y.cachedInputTokens,x.cost_usd=y.costUsd,w.model===null&&y.model!==null&&(x.model=y.model),M[be]="recorded"):!Eo(w)&&M[be]!=="recorded"&&(M[be]="unavailable"),x.metadata=JSON.stringify(M);let A=w.run_epoch===null?isNull(i.run_epoch):eq(i.run_epoch,w.run_epoch),Q=w.heartbeat_at===null?isNull(i.heartbeat_at):eq(i.heartbeat_at,w.heartbeat_at),_e=n.db.update(i).set(x).where(and(eq(i.id,w.id),eq(i.status,"running"),A,Q)).run();return _e.changes>0&&T++,_e.changes>0};for(let w of r){if(w.status==="pending"){if(w.pid!==null||w.started_at>=p)continue;let y=yo(w.metadata,"launch_failed");n.db.update(i).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:g,metadata:y}).where(and(eq(i.id,w.id),eq(i.status,"pending"),isNull(i.pid),lt$1(i.started_at,p))).run().changes>0&&T++;continue}if(xc.has(w.platform??"cli"))continue;if(w.pid===null){let y=`${w.id}:${w.run_epoch??0}`;m.add(y);let x=this.pidNullObservedSince.get(y);if(x===void 0){this.pidNullObservedSince.set(y,o);continue}o-x>=Ro&&E(w,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(y);continue}if(w.heartbeat_at===null){lt(w.pid)==="not_found"&&E(w,"Reaped: process not found (orphaned task)");continue}let C=Date.parse(w.heartbeat_at),M=Number.isFinite(C)?o-C:Number.POSITIVE_INFINITY;if(M<=c)continue;lt(w.pid)==="not_found"?E(w,"Reaped: process not found (orphaned task)"):M>l&&d&&E(w,"Reaped: heartbeat stale beyond hard limit (orphaned task)");}for(let w of Array.from(this.pidNullObservedSince.keys()))m.has(w)||this.pidNullObservedSince.delete(w);return T}finally{n.close();}}reapRunningWorkflowTasks(e=Ro){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),o=and(eq(i.status,"running"),eq(i.platform,"workflow"),isNull(i.pid),lt$1(i.started_at,r),or$1(isNull(i.metadata),and(notLike(i.metadata,'%"kind":"workflow_card"%'),notLike(i.metadata,'%"kind":"workflow_ui_instance"%')))),s=n.db.select({id:i.id,metadata:i.metadata}).from(i).where(o).all(),a=new Date().toISOString(),u=0;for(let d of s){let c=Z(d.metadata);c.terminalReason="runner_lost";let l=n.db.update(i).set({status:"runner_lost",error:"Reaped: stale workflow run (finally not executed)",completed_at:a,metadata:JSON.stringify(c)}).where(and(eq(i.id,d.id),eq(i.status,"running"))).run();u+=l.changes??0;}return u}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=W(o);try{let a=n?eq(i.workspace_id,n):void 0,u=a?and(eq(i.id,e),a):eq(i.id,e),d=s.db.select().from(i).where(u).limit(1).get()??void 0;if(!d){let c=a?and(eq(i.thread_id,e),a):eq(i.thread_id,e);d=s.db.select().from(i).where(c).orderBy(desc(i.started_at)).limit(1).get()??void 0;}if(d)return Oe(d)}catch(a){throw new f("DB_ERROR","Failed to find task status",a)}finally{s.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let a of r){if(!existsSync(a))continue;let u=W(a);try{let d=n?and(eq(i.parent_task_id,e),eq(i.workspace_id,n)):eq(i.parent_task_id,e),c=u.db.select().from(i).where(d).orderBy(asc(i.started_at)).all();for(let l of c)o.has(l.id)||(o.add(l.id),s.push(Oe(l)));}catch(d){throw new f("DB_ERROR","Failed to find child tasks",d)}finally{u.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?sql`
|
|
87
90
|
SELECT
|
|
88
91
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
89
92
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -104,7 +107,7 @@ ${r.join(`
|
|
|
104
107
|
FROM tasks
|
|
105
108
|
GROUP BY workspace_id
|
|
106
109
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
107
|
-
`)}catch(r){throw new f("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,a=0,
|
|
110
|
+
`)}catch(r){throw new f("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,a=0,u=0;for(let d of r){if(!existsSync(d))continue;let c=W(d);try{let l=eq(i.thread_id,e),p=n?and(l,eq(i.workspace_id,n)):l,g=c.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(p).all();for(let m of g)o.has(m.id)||(o.add(m.id),s+=m.input_tokens??0,a+=m.output_tokens??0,u+=m.cost_usd??0);}catch(l){throw new f("DB_ERROR","Failed to get thread token usage",l)}finally{c.close();}}return {inputTokens:s,outputTokens:a,costUsd:u}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,a=[],u=r?.projection==="activity-log";for(let d of o){if(!existsSync(d))continue;let c=W(d);try{let l=eq(i.thread_id,e),p=n?and(l,eq(i.workspace_id,n)):l,g=u?c.db.select({id:i.id,thread_id:i.thread_id,agent_id:i.agent_id,parent_task_id:i.parent_task_id,started_at:i.started_at,completed_at:i.completed_at}).from(i).where(p).orderBy(asc(i.started_at)).all():c.db.select().from(i).where(p).orderBy(asc(i.started_at)).all().map(Oe);for(let m of g)s.has(m.id)||(s.add(m.id),a.push(m));}catch(l){throw new f("DB_ERROR","Failed to find tasks by thread",l)}finally{c.close();}}return a}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=W(n);try{e.push(...r.db.select({id:i.id,agent_id:i.agent_id,thread_id:i.thread_id,workspace_id:i.workspace_id,platform:i.platform,status:i.status,error:i.error,completed_at:i.completed_at,duration_ms:i.duration_ms,started_at:i.started_at,metadata:i.metadata}).from(i).where(and(eq(i.platform,"workflow"),or$1(like(i.metadata,'%"kind":"workflow_card"%'),like(i.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(i.started_at)).all().map(Yi));}catch(o){throw new f("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=W(n);try{let o=r.db.select({id:i.id,agent_id:i.agent_id,thread_id:i.thread_id,workspace_id:i.workspace_id,platform:i.platform,status:i.status,error:i.error,completed_at:i.completed_at,duration_ms:i.duration_ms,started_at:i.started_at,metadata:i.metadata}).from(i).where(and(eq(i.platform,"workflow"),eq(i.workspace_id,e.workspaceId))).orderBy(desc(i.started_at),desc(i.id)).all();for(let s of o){let a=this.parseWorkflowCardMetadata(s.metadata);if(a.kind===e.kind&&a.workflowRunId===e.workflowRunId)return Yi(s)}}catch(o){throw new f("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,a=n?eq(i.workspace_id,n):void 0,u=(d,c)=>{if(!d)return;let l=s.get(d);if(l&&c.started_at<=l)return;let p=this.parseWorkflowCardMetadata(c.metadata);p.kind!=="workflow_card"&&p.kind!=="workflow_ui_instance"||(s.set(d,c.started_at),r.set(d,{taskId:c.id,workflowRunId:p.workflowRunId,raw:c.result??void 0}));};for(let d of this.resolveDbPaths()){if(!existsSync(d))continue;let c=W(d);try{let l=and(inArray(i.thread_id,e),or$1(like(i.metadata,'%"kind":"workflow_card"%'),like(i.metadata,'%"kind":"workflow_ui_instance"%'))),p=c.db.select({id:i.id,thread_id:i.thread_id,metadata:i.metadata,result:i.result,started_at:i.started_at}).from(i).where(a?and(l,a):l).all();for(let T of p)u(T.thread_id,T);let g=and(isNull(i.thread_id),or$1(like(i.metadata,'%"kind":"workflow_card"%'),like(i.metadata,'%"kind":"workflow_ui_instance"%'))),m=c.db.select({id:i.id,command:i.command,metadata:i.metadata,result:i.result,started_at:i.started_at}).from(i).where(a?and(g,a):g).all();for(let T of m){let E=this.extractThreadIdFromCommand(T.command);!E||!o.has(E)||u(E,T);}}catch(l){throw new f("DB_ERROR","Failed to batch fetch workflow cards",l)}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(i.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(inArray(i.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(inArray(i.status,s));let a=e.q??e.search;a&&r.push(like(i.prompt,`%${a}%`)),e.from&&r.push(gte(i.started_at,e.from)),e.to&&r.push(lt$1(i.started_at,e.to));let u=r.length>0?and(...r):void 0,d=n.db.select({count:sql`count(*)`}).from(i).where(u).get(),c=(e.sortDir??"DESC")==="ASC"?asc(i.started_at):desc(i.started_at);return {rows:n.db.select().from(i).where(u).orderBy(c).limit(e.limit).offset(e.offset).all().map(Oe),total:d?.count??0}}catch(r){throw new f("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{let s=gn(sql.raw("t.status")),a=or(sql.raw("t.metadata"));return o.db.all(r?sql`
|
|
108
111
|
SELECT
|
|
109
112
|
t.agent_id,
|
|
110
113
|
t.workspace_id,
|
|
@@ -113,11 +116,11 @@ ${r.join(`
|
|
|
113
116
|
COALESCE(SUM(
|
|
114
117
|
COALESCE(t.input_tokens, 0)
|
|
115
118
|
+ CASE
|
|
116
|
-
WHEN t.started_at >= ${
|
|
119
|
+
WHEN t.started_at >= ${Ke}
|
|
117
120
|
AND (
|
|
118
121
|
t.crewx_version IS NULL
|
|
119
122
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
120
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
123
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Je}) AS INTEGER) < ${Xe})
|
|
121
124
|
)
|
|
122
125
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
123
126
|
ELSE 0
|
|
@@ -136,11 +139,11 @@ ${r.join(`
|
|
|
136
139
|
COALESCE(SUM(
|
|
137
140
|
COALESCE(t.input_tokens, 0)
|
|
138
141
|
+ CASE
|
|
139
|
-
WHEN t.started_at >= ${
|
|
142
|
+
WHEN t.started_at >= ${Ke}
|
|
140
143
|
AND (
|
|
141
144
|
t.crewx_version IS NULL
|
|
142
145
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
143
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
146
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Je}) AS INTEGER) < ${Xe})
|
|
144
147
|
)
|
|
145
148
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
146
149
|
ELSE 0
|
|
@@ -157,11 +160,11 @@ ${r.join(`
|
|
|
157
160
|
COALESCE(SUM(
|
|
158
161
|
COALESCE(t.input_tokens, 0)
|
|
159
162
|
+ CASE
|
|
160
|
-
WHEN t.started_at >= ${
|
|
163
|
+
WHEN t.started_at >= ${Ke}
|
|
161
164
|
AND (
|
|
162
165
|
t.crewx_version IS NULL
|
|
163
166
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
164
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
167
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Je}) AS INTEGER) < ${Xe})
|
|
165
168
|
)
|
|
166
169
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
167
170
|
ELSE 0
|
|
@@ -179,11 +182,11 @@ ${r.join(`
|
|
|
179
182
|
COALESCE(SUM(
|
|
180
183
|
COALESCE(t.input_tokens, 0)
|
|
181
184
|
+ CASE
|
|
182
|
-
WHEN t.started_at >= ${
|
|
185
|
+
WHEN t.started_at >= ${Ke}
|
|
183
186
|
AND (
|
|
184
187
|
t.crewx_version IS NULL
|
|
185
188
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
186
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
189
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Je}) AS INTEGER) < ${Xe})
|
|
187
190
|
)
|
|
188
191
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
189
192
|
ELSE 0
|
|
@@ -191,7 +194,7 @@ ${r.join(`
|
|
|
191
194
|
), 0)
|
|
192
195
|
+ COALESCE(SUM(t.output_tokens), 0)
|
|
193
196
|
) DESC
|
|
194
|
-
`).map(
|
|
197
|
+
`).map(d=>({agentId:d.agent_id,workspaceId:d.workspace_id??null,totalTasks:d.total_tasks,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(s){throw new f("DB_ERROR","Failed to get agent usage",s)}finally{o.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=gn(sql.raw("t.status")),a=or(sql.raw("t.metadata"));return o.db.all(r?sql`
|
|
195
198
|
SELECT
|
|
196
199
|
date(t.started_at) AS date,
|
|
197
200
|
t.agent_id,
|
|
@@ -199,11 +202,11 @@ ${r.join(`
|
|
|
199
202
|
COALESCE(SUM(
|
|
200
203
|
COALESCE(t.input_tokens, 0)
|
|
201
204
|
+ CASE
|
|
202
|
-
WHEN t.started_at >= ${
|
|
205
|
+
WHEN t.started_at >= ${Ke}
|
|
203
206
|
AND (
|
|
204
207
|
t.crewx_version IS NULL
|
|
205
208
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
206
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
209
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Je}) AS INTEGER) < ${Xe})
|
|
207
210
|
)
|
|
208
211
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
209
212
|
ELSE 0
|
|
@@ -227,11 +230,11 @@ ${r.join(`
|
|
|
227
230
|
COALESCE(SUM(
|
|
228
231
|
COALESCE(t.input_tokens, 0)
|
|
229
232
|
+ CASE
|
|
230
|
-
WHEN t.started_at >= ${
|
|
233
|
+
WHEN t.started_at >= ${Ke}
|
|
231
234
|
AND (
|
|
232
235
|
t.crewx_version IS NULL
|
|
233
236
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
234
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${
|
|
237
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Je}) AS INTEGER) < ${Xe})
|
|
235
238
|
)
|
|
236
239
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
237
240
|
ELSE 0
|
|
@@ -246,14 +249,14 @@ ${r.join(`
|
|
|
246
249
|
AND t.started_at < ${n}
|
|
247
250
|
GROUP BY date(t.started_at), t.agent_id
|
|
248
251
|
ORDER BY date(t.started_at) ASC
|
|
249
|
-
`).map(
|
|
252
|
+
`).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(s){throw new f("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{let o=r.db.select().from(i).where(and(eq(i.id,e),eq(i.workspace_id,n))).limit(1).get();return o?Oe(o):void 0}catch(o){throw new f("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:i.id,thread_id:i.thread_id,status:i.status,result:i.result,error:i.error,started_at:i.started_at,completed_at:i.completed_at,metadata:i.metadata}).from(i).where(and(eq(i.agent_id,e.agentId),eq(i.workspace_id,e.workspaceId),sql`${i.metadata} IS NOT NULL AND json_valid(${i.metadata}) AND json_extract(${i.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(i.started_at)).limit(1).get()??null}catch(r){throw new f("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r,o="failed",s){if(!this.dbExists())return;let a=this.openHandle(true);try{let u=new Date().toISOString(),d=r?and(eq(i.id,e),eq(i.status,"running"),eq(i.workspace_id,r)):and(eq(i.id,e),eq(i.status,"running")),c=a.db.select({metadata:i.metadata}).from(i).where(d).limit(1).get();if(!c)return;let l={status:o,error:n,completed_at:u};if(s){let p=Z(c.metadata);p.terminalReason=s,l.metadata=JSON.stringify(p);}a.db.update(i).set(l).where(d).run();}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to mark task failed",u)}finally{a.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let a of r){if(!existsSync(a))continue;let u=W(a);try{let d=n?and(like(i.prompt,`%${e}%`),eq(i.workspace_id,n)):like(i.prompt,`%${e}%`),c=u.db.select().from(i).where(d).orderBy(asc(i.started_at)).all();for(let l of c)o.has(l.id)||(o.add(l.id),s.push(Oe(l)));}catch(d){throw new f("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{u.close();}}return s}getProviderUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=Qi(),a=gn(i.status),u=or(i.metadata),d=sql`
|
|
250
253
|
COALESCE(${i.input_tokens}, 0)
|
|
251
254
|
+ CASE
|
|
252
|
-
WHEN ${i.started_at} >= ${
|
|
255
|
+
WHEN ${i.started_at} >= ${Ke}
|
|
253
256
|
AND (
|
|
254
257
|
${i.crewx_version} IS NULL
|
|
255
258
|
OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
|
|
256
|
-
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${
|
|
259
|
+
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Je}) AS INTEGER) < ${Xe})
|
|
257
260
|
)
|
|
258
261
|
THEN COALESCE(${i.cached_input_tokens}, 0)
|
|
259
262
|
ELSE 0
|
|
@@ -262,8 +265,8 @@ ${r.join(`
|
|
|
262
265
|
SELECT
|
|
263
266
|
${s} AS provider,
|
|
264
267
|
COUNT(*) AS total_tasks,
|
|
265
|
-
${
|
|
266
|
-
COALESCE(SUM(${
|
|
268
|
+
${u} AS unavailable_task_count,
|
|
269
|
+
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
267
270
|
COALESCE(SUM(${i.output_tokens}), 0) AS output_tokens,
|
|
268
271
|
COALESCE(SUM(${i.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
269
272
|
COALESCE(SUM(${i.cost_usd}), 0) AS cost_usd,
|
|
@@ -272,15 +275,15 @@ ${r.join(`
|
|
|
272
275
|
FROM ${i}
|
|
273
276
|
${c}
|
|
274
277
|
GROUP BY ${s}
|
|
275
|
-
ORDER BY (COALESCE(SUM(${
|
|
276
|
-
`).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(s){throw new f("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=
|
|
278
|
+
ORDER BY (COALESCE(SUM(${d}), 0) + COALESCE(SUM(${i.output_tokens}), 0)) DESC
|
|
279
|
+
`).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(s){throw new f("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=Qi(),a=gn(i.status),u=or(i.metadata),d=sql`
|
|
277
280
|
COALESCE(${i.input_tokens}, 0)
|
|
278
281
|
+ CASE
|
|
279
|
-
WHEN ${i.started_at} >= ${
|
|
282
|
+
WHEN ${i.started_at} >= ${Ke}
|
|
280
283
|
AND (
|
|
281
284
|
${i.crewx_version} IS NULL
|
|
282
285
|
OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
|
|
283
|
-
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${
|
|
286
|
+
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Je}) AS INTEGER) < ${Xe})
|
|
284
287
|
)
|
|
285
288
|
THEN COALESCE(${i.cached_input_tokens}, 0)
|
|
286
289
|
ELSE 0
|
|
@@ -290,8 +293,8 @@ ${r.join(`
|
|
|
290
293
|
${i.model} AS model,
|
|
291
294
|
${s} AS provider,
|
|
292
295
|
COUNT(*) AS total_tasks,
|
|
293
|
-
${
|
|
294
|
-
COALESCE(SUM(${
|
|
296
|
+
${u} AS unavailable_task_count,
|
|
297
|
+
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
295
298
|
COALESCE(SUM(${i.output_tokens}), 0) AS output_tokens,
|
|
296
299
|
COALESCE(SUM(${i.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
297
300
|
COALESCE(SUM(${i.cost_usd}), 0) AS cost_usd,
|
|
@@ -300,7 +303,7 @@ ${r.join(`
|
|
|
300
303
|
FROM ${i}
|
|
301
304
|
${c}
|
|
302
305
|
GROUP BY ${i.model}, ${s}
|
|
303
|
-
`),p=new Map;for(let g of l){let m=
|
|
306
|
+
`),p=new Map;for(let g of l){let m=Dr(g.model??""),T=JSON.stringify([g.provider,m]),E=p.get(T);E?(E.totalTasks+=g.total_tasks,E.unavailableTaskCount=(E.unavailableTaskCount??0)+g.unavailable_task_count,E.inputTokens+=g.input_tokens,E.outputTokens+=g.output_tokens,E.cachedInputTokens+=g.cached_input_tokens,E.costUsd+=g.cost_usd,E.totalTokens+=g.input_tokens+g.output_tokens,E.activeDurationMs+=g.active_duration_ms??0,g.last_active_at&&(!E.lastActiveAt||g.last_active_at>E.lastActiveAt)&&(E.lastActiveAt=g.last_active_at)):p.set(T,{model:m,provider:g.provider,totalTasks:g.total_tasks,unavailableTaskCount:g.unavailable_task_count,inputTokens:g.input_tokens,outputTokens:g.output_tokens,cachedInputTokens:g.cached_input_tokens,costUsd:g.cost_usd,totalTokens:g.input_tokens+g.output_tokens,activeDurationMs:g.active_duration_ms??0,lastActiveAt:g.last_active_at??null});}return Array.from(p.values()).sort((g,m)=>m.costUsd-g.costUsd)}catch(s){throw new f("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 ${i.started_at} >= ${e} AND ${i.started_at} < ${n} AND ${i.workspace_id} = ${r}`:sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${n}`;return o.db.all(sql`
|
|
304
307
|
SELECT
|
|
305
308
|
${i.thread_id} AS thread_id,
|
|
306
309
|
${i.agent_id} AS agent_id,
|
|
@@ -311,19 +314,19 @@ ${r.join(`
|
|
|
311
314
|
FROM ${i}
|
|
312
315
|
${s}
|
|
313
316
|
ORDER BY ${i.started_at} ASC
|
|
314
|
-
`).map(
|
|
317
|
+
`).map(u=>({threadId:u.thread_id,agentId:u.agent_id,startedAt:u.started_at,status:u.status,error:u.error,exitCode:u.exit_code}))}catch(s){throw new f("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`
|
|
315
318
|
COALESCE(${i.input_tokens}, 0)
|
|
316
319
|
+ CASE
|
|
317
|
-
WHEN ${i.started_at} >= ${
|
|
320
|
+
WHEN ${i.started_at} >= ${Ke}
|
|
318
321
|
AND (
|
|
319
322
|
${i.crewx_version} IS NULL
|
|
320
323
|
OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
|
|
321
|
-
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${
|
|
324
|
+
OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Je}) AS INTEGER) < ${Xe})
|
|
322
325
|
)
|
|
323
326
|
THEN COALESCE(${i.cached_input_tokens}, 0)
|
|
324
327
|
ELSE 0
|
|
325
328
|
END
|
|
326
|
-
`,a=
|
|
329
|
+
`,a=gn(i.status),u=r?sql`WHERE ${a} AND ${i.started_at} >= ${e} AND ${i.started_at} < ${n} AND ${i.workspace_id} = ${r}`:sql`WHERE ${a} AND ${i.started_at} >= ${e} AND ${i.started_at} < ${n}`,d=o.db.all(sql`
|
|
327
330
|
SELECT
|
|
328
331
|
${i.caller_agent_id} AS caller_agent_id,
|
|
329
332
|
${i.agent_id} AS agent_id,
|
|
@@ -331,26 +334,26 @@ ${r.join(`
|
|
|
331
334
|
COALESCE(SUM(${s}), 0) AS input_tokens,
|
|
332
335
|
COALESCE(SUM(${i.output_tokens}), 0) AS output_tokens
|
|
333
336
|
FROM ${i}
|
|
334
|
-
${
|
|
337
|
+
${u}
|
|
335
338
|
GROUP BY ${i.caller_agent_id}, ${i.agent_id}
|
|
336
339
|
ORDER BY task_count DESC, ${i.caller_agent_id} ASC, ${i.agent_id} ASC
|
|
337
|
-
LIMIT ${
|
|
338
|
-
`),c=
|
|
340
|
+
LIMIT ${_o+1}
|
|
341
|
+
`),c=d.length>_o;return {edges:d.slice(0,_o).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:c}}catch(s){throw new f("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(i.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(inArray(i.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(inArray(i.status,e.statuses)),e.from&&r.push(gte(i.started_at,e.from)),e.to&&r.push(lt$1(i.started_at,e.to));let o=r.length>0?and(...r):void 0,s=(e.order??"DESC")==="ASC"?asc(i.started_at):desc(i.started_at),a={id:i.id,agent_id:i.agent_id,status:i.status,prompt:i.prompt,started_at:i.started_at,completed_at:i.completed_at,thread_id:i.thread_id,error:i.error,metadata:i.metadata};return (e.limit?n.db.select(a).from(i).where(o).orderBy(s).limit(e.limit).all():n.db.select(a).from(i).where(o).orderBy(s).all()).map(({error:d,metadata:c,...l})=>({...l,status:mt({status:l.status,error:d,metadata:c})}))}catch(r){throw new f("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(i.thread_id),isNull(i.parent_task_id),isNull(i.caller_agent_id),or$1(isNull(i.platform),ne$1(i.platform,"workflow")),or$1(isNull(i.metadata),and(notLike(i.metadata,'%"kind":"workflow_card"%'),notLike(i.metadata,'%"kind":"workflow_ui_instance"%'))),or$1(isNull(i.metadata),notLike(i.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(i.workspace_id,e.workspaceId)),e.from&&s.push(gte(i.started_at,e.from)),e.to&&s.push(lt$1(i.started_at,e.to));let a=n.db.select({id:i.id,agent_id:i.agent_id,status:i.status,prompt:i.prompt,started_at:i.started_at,completed_at:i.completed_at,thread_id:i.thread_id}).from(i).where(and(...s)).orderBy(asc(i.started_at),asc(i.id)).all(),u=new Map;for(let c of a){if(!c.thread_id)continue;let l={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},p=u.get(c.thread_id);p?p.push(l):u.set(c.thread_id,[l]);}let d=[];for(let[c,l]of u){let p=l.filter(g=>g.agentId===e.targetAgentId).length;p<2||d.push({threadId:c,targetAgentTurnCount:p,turns:l});}return d.sort((c,l)=>{let p=c.turns[c.turns.length-1].startedAt,g=l.turns[l.turns.length-1].startedAt;return p<g?1:p>g?-1:0}),d.slice(0,r).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-o)}))}catch(r){throw new f("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}};});h();h();h();var Qe=class{detach(e){}};h();function Mo(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 kr(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var Tr=class extends Qe{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=Mo(n.timestamp),o=join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,o);let s=`=== TASK LOG: ${n.traceId} ===
|
|
339
342
|
CrewX Version: ${this.version}
|
|
340
343
|
Mode: ${n.mode}
|
|
341
344
|
Agent: ${n.agentRef}
|
|
342
|
-
Started: ${
|
|
345
|
+
Started: ${kr(n.timestamp)}
|
|
343
346
|
Message: ${n.message}
|
|
344
347
|
|
|
345
348
|
`;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}
|
|
346
|
-
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=
|
|
349
|
+
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=kr(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",a=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
|
|
347
350
|
[${o}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
348
|
-
`;appendFileSync(r,a,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};h();h();function
|
|
349
|
-
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>Sc(r,e))}function ke(t){return typeof t=="object"&&t!==null}function Qi(t,e){if(e==="assistant"||e==="user"){let n=t.message;return ke(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||ke(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?ke(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function Ic(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Qi(t,e)}function Ac(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 ke(n)&&typeof n.type=="string"}return false}function vc(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||ke(t.part):e==="text"||e==="tool_use"?ke(t.part):e==="result"?typeof t.result=="string":false}function Oc(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||ke(t.part)||e==="result"&&typeof t.result=="string")}function bc(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?ke(t.data):e==="result"?typeof t.result=="string":false}function xc(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 Cc(t,e){return e==="available_commands"?ke(t.tools)||ke(t.commands):e==="usage"?ke(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||ke(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var Zi={claude:Qi,codex:Ac,opencode:vc,copilot:bc,gemini:xc},Nc={...Zi,claude:Ic,opencode:Oc,grok:Cc,antigravity:()=>false};Jr();sn();co();Mn();var Dc=200,Lc=200;function Mc(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 Hc(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=Mc(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function ta(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function $c(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function na(t){if(!t)return {};try{let e=JSON.parse(t);return $c(e)?e:{}}catch{return {}}}function gn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Uc=new Set(["workflow","mcp"]),To=class extends Ye{name="sqlite-tracing";unsubs=[];dbPath;version;runnerIdentity;taskRepo;heartbeatTaskIds=new Set;ownedTaskRuns=new Map;ignoredDetachedTaskIds=new Set;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super();let n=process.env.CREWX_DB||process.env.CREWX_TRACES_DB;this.dbPath=e?.dbRoot!==void 0?join(e.dbRoot,".crewx","crewx.db"):n??join(homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown";let r=e?.runnerIdentity;this.runnerIdentity={detachedRunner:r?.detachedRunner===true,assignedTaskId:r?.detachedRunner===true&&r.assignedTaskId?.trim()||void 0};}attach(e){let n=new fn({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),s=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml"))?Lo(r):null,a=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let u=d.callerAgentId??null,c=d.parentTaskId??null,l=d.rootTraceId??d.traceId,{detachedRunner:p,assignedTaskId:g}=this.runnerIdentity,m=g??d.traceId,S=gn(d.metadata?.runEpoch),w=p?"runner":"caller",T=d.workspaceId??s,P=p?n.getTask(m):void 0,C=d.pid??null,U={...d.metadata??{provider:d.provider??"cli/claude"},ownership:w,...p&&C!==null?{providerPid:C}:{}},E=JSON.stringify(U);if(p&&P?.status==="running"&&P.pid!==null&&S===0){this.ignoredDetachedTaskIds.add(m);return}n.startTask({id:m,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:p?process.pid:C,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:a,codingAgentCommand:d.codingAgentCommand??null,workspaceId:T,projectId:d.projectId??null,callerAgentId:u,parentTaskId:c,traceId:l,metadata:E,threadId:d.threadId??null}),n.updateTaskOwnership({id:m,runEpoch:S,ownership:w,...p?{providerPid:C}:{}})&&this.recordOwnedTaskRun({taskId:m,runEpoch:S,workspaceId:T,ownership:w}),Uc.has(d.platform??"cli")||Di(n,{taskId:m,runEpoch:S,onStopRequested:ce=>this.handleStopRequested(n,ce)})&&this.heartbeatTaskIds.add(m);}catch{}}),e.on("task:output",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(u))return;this.enqueueLog(u,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(u){let c={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(u,[c],ta(c));}}),e.on("task:end",d=>{try{let u=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(u))return;let c=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(u,gn(c)),on(u,c)&&this.heartbeatTaskIds.delete(u),this.flushTaskLogs(u);let p=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{},...d.error.mode?{mode:d.error.mode}:{}}):null,g=d.result??null,m=!1;if(d.error&&(!g||g.trim()==="")){let S=this.recoverPartialResult(u,d,c);S&&(g=S,m=!0);}n.finishTask({id:u,status:d.error?"failed":"success",result:g,error:p,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch:c,partialResultRecovered:m});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)on(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let o=await qi(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(o.status==="failed"||o.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:o.status,...o.error?{error:o.error}:{}});}catch(o){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:o instanceof Error?o.name:typeof o});}}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}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}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+=ta(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>=Dc){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));},Lc);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo;if(!o)return;let s=o.getTask(e);if(!s||s.status!=="running"||gn(s.run_epoch)!==gn(r))return;let a=na(s.metadata),d=typeof a.provider=="string"?a.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!d)return;let u=Vn({taskLogRepository:o,taskId:e,provider:d,model:s.model});if(!u?.adapter.extractPartialText)return;let c=u.adapter.extractPartialText(u.stdout);return !c||!c.trim()||er(c,d)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let o=gn(n.run_epoch),s=na(n.metadata??null),a=s.ownership==="runner"?"runner":"caller";if(a==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let d=typeof s.providerPid=="number"&&Number.isSafeInteger(s.providerPid)&&s.providerPid>0?s.providerPid:void 0,u=a==="runner"?d:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(u!==void 0){let c;try{c=await It(u,{signal:St});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(c.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:c.error??"process termination failed"});return}}try{let c=e.finalizeTaskStop({id:r,runEpoch:o,method:Yn(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&on(r,o)&&this.heartbeatTaskIds.delete(r);}catch(c){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:c instanceof Error?c.name:typeof c});}}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(a){this.recordAppendFailure(a,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=Hc(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});}};h();h();h();it();_t();Tt();ot();Et();Kn();function nr(t){return {...t,status:gt(t)}}function Wc({metadata:t,...e}){return {...e,status:gt({...e,metadata:t})}}var Lt=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function hn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Gc(t){let n=hn(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 rr=class extends he{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 f("NOT_FOUND","Database not found");let r=W(n);if(e)try{Ce(r.db,n);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,n){return e.db.select({id:wt.id}).from(wt).where(eq(wt.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
351
|
+
`;appendFileSync(r,a,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};h();h();var Tt=new Map;function An(t){let e=le.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 Fo(t){let e=An(t);return createHash("sha256").update(e).digest("hex")}function Bo(t){let e=An(t),n=Tt.get(e);if(n!==void 0)return n;let r=e;try{let o=le.join(e,".git");if(!lstatSync(o).isFile())return Tt.set(e,r),r;let s=/^gitdir:\s*(.+?)\s*$/i.exec(readFileSync(o,"utf8").trim());if(!s)return Tt.set(e,r),r;let a=s[1],u=le.isAbsolute(a)?a:le.resolve(le.dirname(o),a),d=readFileSync(le.join(u,"commondir"),"utf8").trim();if(!d)return Tt.set(e,r),r;let c=le.isAbsolute(d)?d:le.resolve(u,d);if(le.basename(c)!==".git"||!statSync(c).isDirectory())return Tt.set(e,r),r;let l=An(realpathSync.native(e)),p=An(realpathSync.native(le.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return Tt.set(e,r),r}it();ho();h();function Hc(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?Gc[e]:void 0;return s?s(r,o):Object.values(aa).some(a=>a(r,o))}function ar(t,e){let n=t.split(`
|
|
352
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>Hc(r,e))}function we(t){return typeof t=="object"&&t!==null}function ia(t,e){if(e==="assistant"||e==="user"){let n=t.message;return we(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||we(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?we(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function $c(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:ia(t,e)}function Uc(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 we(n)&&typeof n.type=="string"}return false}function qc(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||we(t.part):e==="text"||e==="tool_use"?we(t.part):e==="result"?typeof t.result=="string":false}function Fc(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||we(t.part)||e==="result"&&typeof t.result=="string")}function Bc(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?we(t.data):e==="result"?typeof t.result=="string":false}function jc(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 Wc(t,e){return e==="available_commands"?we(t.tools)||we(t.commands):e==="usage"?we(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||we(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var aa={claude:ia,codex:Uc,opencode:qc,copilot:Bc,gemini:jc},Gc={...aa,claude:$c,opencode:Fc,grok:Wc,antigravity:()=>false};Zr();un();go();Bn();var Vc=200,Kc=200;function Jc(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 Xc(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=Jc(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function ua(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Yc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ca(t){if(!t)return {};try{let e=JSON.parse(t);return Yc(e)?e:{}}catch{return {}}}function mn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Qc=new Set(["workflow","mcp"]),So=class extends Qe{name="sqlite-tracing";unsubs=[];dbPath;version;inheritWorktreeOwner;runnerIdentity;taskRepo;heartbeatTaskIds=new Set;ownedTaskRuns=new Map;ignoredDetachedTaskIds=new Set;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super();let n=process.env.CREWX_DB||process.env.CREWX_TRACES_DB;this.dbPath=e?.dbRoot!==void 0?join(e.dbRoot,".crewx","crewx.db"):n??join(homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown",this.inheritWorktreeOwner=e?.inheritWorktreeOwner===true;let r=e?.runnerIdentity;this.runnerIdentity={detachedRunner:r?.detachedRunner===true,assignedTaskId:r?.detachedRunner===true&&r.assignedTaskId?.trim()||void 0};}attach(e){let n=new hn({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),o=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml")),s=this.inheritWorktreeOwner?Bo(r):r,a=o?Fo(s):null,u=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let c=d.callerAgentId??null,l=d.parentTaskId??null,p=d.rootTraceId??d.traceId,{detachedRunner:g,assignedTaskId:m}=this.runnerIdentity,T=m??d.traceId,E=mn(d.metadata?.runEpoch),w=g?"runner":"caller",C=d.workspaceId??a,M=g?n.getTask(T):void 0,q=d.pid??null,y={...d.metadata??{provider:d.provider??"cli/claude"},ownership:w,...g&&q!==null?{providerPid:q}:{}},x=JSON.stringify(y);if(g&&M?.status==="running"&&M.pid!==null&&E===0){this.ignoredDetachedTaskIds.add(T);return}n.startTask({id:T,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:g?process.pid:q,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:u,codingAgentCommand:d.codingAgentCommand??null,workspaceId:C,projectId:d.projectId??null,callerAgentId:c,parentTaskId:l,traceId:p,metadata:x,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:T,runEpoch:E,ownership:w,...g?{providerPid:q}:{}})&&this.recordOwnedTaskRun({taskId:T,runEpoch:E,workspaceId:C,ownership:w}),Qc.has(d.platform??"cli")||Fi(n,{taskId:T,runEpoch:E,onStopRequested:Oa=>this.handleStopRequested(n,Oa)})&&this.heartbeatTaskIds.add(T);}catch{}}),e.on("task:output",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;this.enqueueLog(c,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(c){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(c,[l],ua(l));}}),e.on("task:end",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(c))return;let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(c,mn(l)),dn(c,l)&&this.heartbeatTaskIds.delete(c),this.flushTaskLogs(c);let g=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{},...d.error.mode?{mode:d.error.mode}:{}}):null,m=d.result??null,T=!1;if(d.error&&(!m||m.trim()==="")){let E=this.recoverPartialResult(c,d,l);E&&(m=E,T=!0);}n.finishTask({id:c,status:d.error?"failed":"success",result:m,error:g,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:T});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)dn(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let o=await Ki(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(o.status==="failed"||o.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:o.status,...o.error?{error:o.error}:{}});}catch(o){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:o instanceof Error?o.name:typeof o});}}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}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}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+=ua(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>=Vc){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));},Kc);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo;if(!o)return;let s=o.getTask(e);if(!s||s.status!=="running"||mn(s.run_epoch)!==mn(r))return;let a=ca(s.metadata),u=typeof a.provider=="string"?a.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=Zn({taskLogRepository:o,taskId:e,provider:u,model:s.model});if(!d?.adapter.extractPartialText)return;let c=d.adapter.extractPartialText(d.stdout);return !c||!c.trim()||ar(c,u)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let o=mn(n.run_epoch),s=ca(n.metadata??null),a=s.ownership==="runner"?"runner":"caller";if(a==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let u=typeof s.providerPid=="number"&&Number.isSafeInteger(s.providerPid)&&s.providerPid>0?s.providerPid:void 0,d=a==="runner"?u:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(d!==void 0){let c;try{c=await vt(d,{signal:At});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(c.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:c.error??"process termination failed"});return}}try{let c=e.finalizeTaskStop({id:r,runEpoch:o,method:rr(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&dn(r,o)&&this.heartbeatTaskIds.delete(r);}catch(c){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:c instanceof Error?c.name:typeof c});}}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(a){this.recordAppendFailure(a,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=Xc(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});}};h();h();h();dt();wt();yt();it();St();er();function ur(t){return {...t,status:mt(t)}}function rl({metadata:t,...e}){return {...e,status:mt({...e,metadata:t})}}var $t=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function _n(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function ol(t){let n=_n(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 cr=class extends ke{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 f("NOT_FOUND","Database not found");let r=W(n);if(e)try{Ne(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 (
|
|
350
353
|
SELECT 1 FROM tasks parent
|
|
351
354
|
WHERE parent.id = ${e}.parent_task_id
|
|
352
355
|
AND parent.thread_id = ${e}.thread_id
|
|
353
|
-
)`)}findAllThreads(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!existsSync(s))continue;let a=W(s);try{let
|
|
356
|
+
)`)}findAllThreads(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!existsSync(s))continue;let a=W(s);try{let u=e?eq(_.workspace_id,e):void 0,d=a.db.select().from(_).where(u).orderBy(desc(_.updated_at)).all();for(let c of d)r.has(c.id)||(r.add(c.id),o.push(c));}catch(u){throw new f("DB_ERROR","Failed to find all threads",u)}finally{a.close();}}return o}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let a of r){if(!existsSync(a))continue;let u=W(a);try{let d=or$1(inArray(_.id,e),inArray(_.title,e)),c=n?and(d,eq(_.workspace_id,n)):d,l=u.db.select().from(_).where(c).orderBy(desc(_.updated_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(p));}catch(d){throw new f("DB_ERROR","Failed to find threads by ids or titles",d)}finally{u.close();}}return s}findThreadById(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=W(o);try{let a=eq(_.id,e),u=n?and(a,eq(_.workspace_id,n)):a,d=s.db.select().from(_).where(u).limit(1).get()??void 0;if(d)return d}catch(a){throw new f("DB_ERROR","Failed to find thread by id",a)}finally{s.close();}}}threadExists(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=W(o);try{let a=eq(_.id,e),u=n?and(a,eq(_.workspace_id,n)):a;if(s.db.select({id:_.id}).from(_).where(u).limit(1).get())return !0}catch(a){throw new f("DB_ERROR","Failed to check thread existence",a)}finally{s.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),o=0,s=0,a=0,u=0,d=0,c=new Set;for(let l of r){if(!existsSync(l))continue;let p=W(l);try{let g=p.db.get(sql`
|
|
354
357
|
SELECT
|
|
355
358
|
count(*) AS cnt,
|
|
356
359
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -361,13 +364,13 @@ Message: ${n.message}
|
|
|
361
364
|
WHERE child.thread_id = ${e}
|
|
362
365
|
AND ${this.topLevelTaskPredicateSql()}
|
|
363
366
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
364
|
-
`);g&&(o+=g.cnt,s+=g.total_input,a+=g.total_output,
|
|
367
|
+
`);g&&(o+=g.cnt,s+=g.total_input,a+=g.total_output,u+=g.total_cached,d+=g.total_cost);let m=p.db.all(sql`
|
|
365
368
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
366
369
|
WHERE child.thread_id = ${e}
|
|
367
370
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
368
371
|
AND ${this.topLevelTaskPredicateSql()}
|
|
369
372
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
370
|
-
`);for(let
|
|
373
|
+
`);for(let T of m)c.add(T.agent_id);}catch(g){throw new f("DB_ERROR","Failed to aggregate task stats",g)}finally{p.close();}}return {taskCount:o,inputTokens:s,outputTokens:a,cachedInputTokens:u,costUsd:d,agentIds:Array.from(c)}}findTopLevelTasks(e,n,r){let o=this.resolveDbPaths(),s=new Set,a=[];for(let u of o){if(!existsSync(u))continue;let d=W(u);try{let c;r!==void 0?c=d.db.all(sql`
|
|
371
374
|
SELECT * FROM (
|
|
372
375
|
SELECT child.*,
|
|
373
376
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -378,13 +381,13 @@ Message: ${n.message}
|
|
|
378
381
|
) ranked
|
|
379
382
|
WHERE rn <= ${r}
|
|
380
383
|
ORDER BY started_at ASC
|
|
381
|
-
`):c=
|
|
384
|
+
`):c=d.db.all(sql`
|
|
382
385
|
SELECT child.* FROM tasks child
|
|
383
386
|
WHERE child.thread_id = ${e}
|
|
384
387
|
AND ${this.topLevelTaskPredicateSql()}
|
|
385
388
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
386
389
|
ORDER BY child.started_at ASC
|
|
387
|
-
`);for(let l of c)s.has(l.id)||(s.add(l.id),a.push(
|
|
390
|
+
`);for(let l of c)s.has(l.id)||(s.add(l.id),a.push(ur(l)));}catch(c){throw new f("DB_ERROR","Failed to find top-level tasks",c)}finally{d.close();}}if(r!==void 0&&o.length>1){let u=new Map;for(let d of a){let c=d.agent_id??"";u.has(c)||u.set(c,[]),u.get(c).push(d);}a=[];for(let d of u.values())d.sort((c,l)=>(l.started_at??"").localeCompare(c.started_at??"")),a.push(...d.slice(0,r));a.sort((d,c)=>(d.started_at??"").localeCompare(c.started_at??""));}return a}findAllTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let a of r){if(!existsSync(a))continue;let u=W(a);try{let d=eq(i.thread_id,e),c=n?and(d,eq(i.workspace_id,n)):d,l=u.db.select().from(i).where(c).orderBy(asc(i.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(ur(p)));}catch(d){throw new f("DB_ERROR","Failed to find all tasks for thread",d)}finally{u.close();}}return s}findTaskById(e,n,r){let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let a=W(s);try{let u=and(eq(i.id,n),eq(i.thread_id,e)),d=r?and(u,eq(i.workspace_id,r)):u,c=a.db.select().from(i).where(d).limit(1).get();if(!c)continue;let l=a.db.select().from(i).where(eq(i.parent_task_id,c.id)).orderBy(asc(i.started_at)).all().map(ur);return {task:ur(c),children:l}}catch(u){throw new f("DB_ERROR","Failed to find task by id",u)}finally{a.close();}}}batchFetchTasksQuery(e,n){return sql`
|
|
388
391
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
389
392
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
390
393
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -394,7 +397,7 @@ Message: ${n.message}
|
|
|
394
397
|
AND ${this.topLevelTaskPredicateSql()}
|
|
395
398
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
396
399
|
ORDER BY child.started_at ASC
|
|
397
|
-
`}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 a=W(s);try{let
|
|
400
|
+
`}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 a=W(s);try{let u=a.db.all(this.batchFetchTasksQuery(e,n));for(let d of u){let c=d.thread_id;r.has(c)||r.set(c,[]),r.get(c).push(rl(d));}}catch(u){throw new f("DB_ERROR","Failed to batch fetch tasks",u)}finally{a.close();}}return r}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=W(o);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(u=>u.detail)}finally{s.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=eq(_.id,e),a=r?and(s,eq(_.workspace_id,r)):s;if(!o.db.select({id:_.id}).from(_).where(a).limit(1).get())return;o.db.update(_).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(_.id,e)).run();}catch(s){throw s instanceof f?s:new f("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:_.id,message_count:_.message_count}).from(_).where(eq(_.id,e)).limit(1).get()){let u={updated_at:s};n.title!==void 0&&(u.title=n.title),n.titleLocked!==void 0&&(u.title_locked=n.titleLocked?1:0),r.db.update(_).set(u).where(eq(_.id,e)).run();}else r.db.insert(_).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 f?o:new f("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,a=o.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(eq(_.id,e)).limit(1).get();if(a){s&&!a.workspace_id&&o.db.update(_).set({workspace_id:s}).where(eq(_.id,e)).run();return}let u=new Date().toISOString();o.db.insert(_).values({id:e,platform:n,workspace_id:s,message_count:0,created_at:u,updated_at:u}).run();}catch(s){throw s instanceof f?s:new f("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(u=>{let c=u.select({message_count:_.message_count}).from(_).where(eq(_.id,e)).limit(1).get()?.message_count===0;return u.run(sql`
|
|
398
401
|
UPDATE threads
|
|
399
402
|
SET first_message = COALESCE(first_message, ${n}),
|
|
400
403
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
@@ -402,11 +405,11 @@ Message: ${n.message}
|
|
|
402
405
|
message_count = message_count + 1,
|
|
403
406
|
updated_at = ${s}
|
|
404
407
|
WHERE id = ${e}
|
|
405
|
-
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof f?s:new f("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(_).set({last_message:n,updated_at:s}).where(eq(_.id,e)).run();}catch(s){throw s instanceof f?s:new f("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(_).set(o).where(eq(_.id,e)).run();}catch(o){throw o instanceof f?o:new f("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 Lt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(u=>u!=="priority"&&u!=="state"))return new Lt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let a=o;if(a.priority===void 0&&a.state===void 0)return new Lt("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let u of [a.priority,a.state])if(u!=null&&(typeof u!="string"||u.length===0))return new Lt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let u=r?and(eq(_.id,e),eq(_.workspace_id,r)):eq(_.id,e);return d.db.transaction(c=>{let l=c.select({metadata:_.metadata}).from(_).where(u).get();if(!l)return null;let p=hn(l.metadata),g=p.threadTitle,m=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};a.priority===null?delete m.priority:a.priority!==void 0&&(m.priority=a.priority),a.state===null?delete m.state:a.state!==void 0&&(m.state=a.state),Object.keys(m).length>0?p.threadTitle=m:delete p.threadTitle;let S=Object.keys(p).length>0?JSON.stringify(p):null,w=new Date().toISOString();c.update(_).set({metadata:S,updated_at:w}).where(u).run();let T=c.select({metadata:_.metadata}).from(_).where(u).get();if(!T)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let P=Gc(T.metadata);return {threadId:e,priority:P.priority,state:P.state}},{behavior:"immediate"})}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to patch thread-title metadata",u)}finally{d.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?and(eq(_.id,e),eq(_.workspace_id,n)):eq(_.id,e);return r.db.transaction(s=>{let a=s.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(o).get();if(!a)return null;let d=a.pinned?0:1,u=hn(a.metadata);if(d){let c=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),l=s.select({metadata:_.metadata}).from(_).where(c).all(),p=null;for(let g of l){let m=hn(g.metadata);typeof m.pinOrder=="number"&&(p===null||m.pinOrder<p)&&(p=m.pinOrder);}u.pinOrder=p===null?0:p-1;}else delete u.pinOrder;return s.update(_).set({pinned:d,metadata:Object.keys(u).length>0?JSON.stringify(u):null}).where(o).run(),{pinned:!!d}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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 a=n?and(eq(_.id,e[s]),eq(_.workspace_id,n)):eq(_.id,e[s]),d=o.select({metadata:_.metadata}).from(_).where(a).get();if(!d)continue;let u=hn(d.metadata);u.pinOrder=s+1,o.update(_).set({metadata:JSON.stringify(u)}).where(a).run();}},{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?and(eq(_.id,e),eq(_.workspace_id,n)):eq(_.id,e),s=r.db.select({starred:_.starred}).from(_).where(o).get();if(!s)return null;let a=s.starred?0:1;return r.db.update(_).set({starred:a}).where(o).run(),{starred:!!a}}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let a=this.openHandle(true);try{let d=n?and(eq(_.id,e),eq(_.workspace_id,n)):eq(_.id,e);return a.db.transaction(c=>{let l=c.select({metadata:_.metadata}).from(_).where(d).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},g=p.overdrive??{},m=o?.defaultTurns??g.defaultTurns??3,S=o?.updatedBy??"ui",w=new Date().toISOString(),T,P,C,U;switch(r){case "enable-count":{let E=o?.turns??m,x=o?.consumeCurrent?Math.max(E-1,0):E;T=x>0?"count":"off",P=x,C=!0,U="count";break}case "enable-latch":{T="latch",P=0,C=!0,U="latch";break}case "disable":{T="off",P=0,C=!1;break}default:{let E=g.state??"off",x=typeof g.remaining=="number"?g.remaining:0;if(E==="count"&&x>0){let A=x-1;A<=0?(T="off",P=0):(T="count",P=A),C=!0,U="count";}else E==="latch"?(T="latch",P=0,C=!0,U="latch"):(T="off",P=0,C=!1);break}}return p.overdrive={state:T,remaining:P,defaultTurns:m,updatedAt:w,updatedBy:S},c.update(_).set({metadata:JSON.stringify(p),updated_at:w}).where(d).run(),{applied:C,appliedMode:U,state:T,remaining:P}},{behavior:"immediate"})}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to resolve overdrive",d)}finally{a.close();}}};h();it();_t();Tt();ot();h();var wo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function zc(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+=wo[o%62]);}for(;n.length<t;)n+=wo[randomBytes(1)[0]%62];return n}function mn(t){return `${t}_${zc(8)}`}function aa(t,e){let{createHash:n}=mt("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let a=0;a<32;a++)o[a%8]^=r[a];let s="";for(let a of o)s+=wo[a%62];return `${t}_${s}`}Et();h();var Vc=["urgent","high","medium","low"],Kc=["investigating","in-progress","in-review","on-hold","done"],da="custom:";var Jc=new Set(Vc),Xc=new Set(Kc);function yo(t){return typeof t=="string"&&Jc.has(t)}function Eo(t){if(typeof t!="string")return false;if(Xc.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(da))return false;let e=t.slice(da.length);return e.length>=1&&e.length<=20}function ua(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 Ro(t){let e=ua(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return yo(r.priority)&&(o.priority=r.priority),Eo(r.state)&&(o.state=r.state),o}function ca(t,e){let n=ua(t)??{},r={...Ro(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)}Kn();var tl="regeneration_replaced";var nl="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var rl="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Ao=class extends f{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;}},Rn=class extends Ao{},vo=class extends f{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},ol=new Set(fs),sl=new Set(ps),il=new Set(gs),al=new Set(hs),dl=50,pa=100,fa=280,ga=40,ul=new Set(ms),or=["queued","running"];function Io(t){return ul.has(t)}function B(t){throw new f("VALIDATION",t)}function xe(t){throw new f("NOT_FOUND",t)}function N(t,e){(typeof t!="string"||t.trim().length===0)&&B(`${e} is required`);}function kn(t={}){let e=t.actor??t,n=e.actorType??"system";return ol.has(n)||B(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&B("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function cl(t){N(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&N(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&B("title must not be empty"),t.title.length>120&&B("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!yo(t.priority)&&B(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Eo(t.state)&&B(`invalid state: ${String(t.state)}`);}function ll(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&B("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)&&B(`${n} must be a non-negative integer`);let e=t.limit??dl;return (!Number.isInteger(e)||e<1||e>pa)&&B(`limit must be between 1 and ${pa}`),e}function Oo(t){typeof t!="string"&&B("text is required");let e=t.trim();return e.length===0&&B("text must not be empty"),e.length>fa&&B(`text must be at most ${fa} characters`),e}function Xe(t,e){return N(t??"",e),t}function bo(t){al.has(t)||B(`invalid highlight kind: ${String(t)}`);}function pl(t){il.has(t)||B(`invalid highlight source: ${String(t)}`);}function fl(t){N(t.threadId,"threadId"),N(t.workspaceId,"workspaceId");let e=t.source??"manual";pl(e),bo(t.kind);let n=Oo(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&o&&r===o?r:void 0),p=Xe(l,"taskId");return (r!==p||o!==p)&&B("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Xe(r,"coversFromTaskId"),a=Xe(o,"coversToTaskId"),d=t.sourceTaskId??s,u=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Xe(d??void 0,"sourceTaskId"),Xe(u??void 0,"detectorVersion"),Xe(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:a,agentId:t.agentId??null,sourceTaskId:d,detectorVersion:u,contentFingerprint:c}}function gl(t,e){(!t||typeof t!="object")&&B(`candidates[${e}] is required`),bo(t.kind);let n=Oo(t.text),r=Xe(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Xe(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Xe(t.coversToTaskId,`candidates[${e}].coversToTaskId`),a=t.contentFingerprint?.trim()||aa("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return N(a,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:a}}function hl(t){Array.isArray(t)||B("candidates must be an array"),t.length>ga&&B(`candidates must contain at most ${ga} items`);let e=new Map;for(let[n,r]of t.entries()){let o=gl(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function En(t){let e=Ro(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 ml(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&B("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function Tn(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${F.seq}), 0)`}).from(F).where(eq(F.thread_id,e)).get()?.maxSeq??0}function wn(t,e){return !!t.select({id:F.id}).from(F).where(eq(F.thread_id,e)).limit(1).get()}function ht(t,e){sl.has(e.type)||B(`invalid thread event type: ${String(e.type)}`);let n=mn("the");t.insert(F).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:ml(e.payload),created_at:e.createdAt}).run();let r=t.select().from(F).where(eq(F.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function yn(t,e,n,r,o){let s=En(e);ht(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 ir(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 sr(t,e,n,r,o,s,a){let d=o==="thread.highlight.created"?ir(e):{before:a?ir({...e,...a,id:e.id}):void 0,after:ir(e)};return ht(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 _l(t,e,n,r,o,s){return ht(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:ir(e),...s??{}}})}var ar=class extends he{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 f("NOT_FOUND","Database not found");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=W(n);if(e)try{Ce(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=eq(_.id,n),s=r===void 0?o:r===null?and(o,isNull(_.workspace_id)):and(o,eq(_.workspace_id,r));return e.select().from(_).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(H).where(eq(H.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(N(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:_.workspace_id}).from(_).where(eq(_.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(N(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?En(o):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){cl(e);let n=kn(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.findThread(s,e.threadId,e.workspaceId);a||xe(`Thread ${e.threadId} not found`);let d=En(a),u=e.title!==void 0,c=u&&e.title!==d.title,l=u&&a.title_locked!==1,p=e.priority!==void 0&&e.priority!==d.priority,g=e.state!==void 0&&e.state!==d.state,m=c||p||g;if(!m&&!l)return d;let S=a.metadata;(p||g)&&(S=ca(a.metadata,{priority:e.priority,state:e.state}));let w={};if(m&&(w.metadata=S,w.updated_at=r),c&&(w.title=e.title),u&&(w.title_locked=1),s.update(_).set(w).where(e.workspaceId===void 0?eq(_.id,e.threadId):e.workspaceId===null?and(eq(_.id,e.threadId),isNull(_.workspace_id)):and(eq(_.id,e.threadId),eq(_.workspace_id,e.workspaceId))).run(),!m){let C={...a,title_locked:1};return En(C)}let T=Tn(s,a.id)+1;wn(s,a.id)||(yn(s,a,n,r,T),T+=1),c&&(ht(s,{threadId:a.id,seq:T,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),T+=1),p&&(ht(s,{threadId:a.id,seq:T,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),T+=1),g&&ht(s,{threadId:a.id,seq:T,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let P={...a,title:c?e.title:a.title,metadata:S,title_locked:u?1:a.title_locked,updated_at:r};return En(P)},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("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(N(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(${F.seq}), 0)`}).from(F).where(eq(F.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(N(e,"threadId"),N(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:i.id,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.started_at,completedAt:i.completed_at}).from(i).where(and(eq(i.thread_id,e),eq(i.workspace_id,n),inArray(i.status,[...vi,"completed","done","error"]),or$1(isNull(i.parent_task_id),eq(i.parent_task_id,"")),sql`${i.result} IS NOT NULL AND length(trim(${i.result})) > 0`)).orderBy(asc(i.started_at),asc(i.id)).all().map(a=>({taskId:a.taskId,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.startedAt,completedAt:a.completedAt})):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.requestId,"requestId"),N(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&N(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||xe(`Thread ${e.threadId} not found`);let a=o.select().from(H).where(and(eq(H.thread_id,s.id),eq(H.request_id,e.requestId))).orderBy(desc(H.requested_at),desc(H.id)).limit(1).get();if(a)return {run:a,created:!1};let d=o.select().from(H).where(and(eq(H.thread_id,s.id),inArray(H.status,or))).orderBy(asc(H.requested_at),asc(H.id)).limit(1).get();if(d)throw new vo(d);let u=e.runId??mn("thr");o.insert(H).values({id:u,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(H).where(eq(H.id,u)).get();if(!c)throw new f("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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(N(e,"runId"),n!==void 0&&N(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 f?o:new f("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(N(e,"threadId"),N(n,"workspaceId"),N(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(H).where(and(eq(H.thread_id,e),eq(H.request_id,r))).orderBy(desc(H.requested_at),desc(H.id)).limit(1).get()??null:null}catch(s){throw s instanceof f?s:new f("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){N(e,"runId"),n!==void 0&&N(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.findRegenerationRun(s,e,n);if(a||xe(`Highlight regeneration run ${e} not found`),Io(a.status)||B(`invalid highlight regeneration status: ${a.status}`),a.status!=="queued")return a;s.update(H).set({status:"running",started_at:r}).where(and(eq(H.id,a.id),eq(H.status,"queued"))).run();let d=s.select().from(H).where(eq(H.id,a.id)).get();if(!d)throw new f("DB_ERROR","Highlight regeneration run start did not return a row");return d},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){N(e.runId,"runId"),N(e.errorCode,"errorCode"),e.workspaceId!==void 0&&N(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||xe(`Highlight regeneration run ${e.runId} not found`),Io(s.status)||B(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(H).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(H.id,s.id),inArray(H.status,or))).run();let a=o.select().from(H).where(eq(H.id,s.id)).get();if(!a)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return a},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=nl){N(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(H).set({status:"failed",completed_at:n,error_code:e}).where(inArray(H.status,or)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){N(e.runId,"runId"),N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.detectorVersion,"detectorVersion");let n=hl(e.candidates),r=kn(e),o=this.openHandle(true),s=false;try{return o.db.transaction(a=>{let d=this.findRegenerationRun(a,e.runId,e.workspaceId);if((!d||d.thread_id!==e.threadId)&&xe(`Highlight regeneration run ${e.runId} not found`),Io(d.status)||B(`invalid highlight regeneration status: ${d.status}`),d.status==="failed")throw new f("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 u=this.findThread(a,e.threadId,e.workspaceId);u||xe(`Thread ${e.threadId} not found`),d.detector_version!==e.detectorVersion&&B("detectorVersion does not match the regeneration run");let c=a.select().from(D).where(eq(D.thread_id,u.id)).orderBy(asc(D.created_at),asc(D.id)).all(),l=new Set(n.map(A=>A.contentFingerprint)),p=c.filter(A=>A.source==="auto"&&A.status==="active"&&A.revision===0&&!l.has(A.content_fingerprint??"")),g=c.filter(A=>A.source==="auto"&&A.status==="active").length,m=new Set(c.filter(A=>!p.includes(A)&&A.content_fingerprint).map(A=>A.content_fingerprint)),S=n.filter(A=>!m.has(A.contentFingerprint)),w=new Date().toISOString(),T=Tn(a,u.id)+1;wn(a,u.id)||(yn(a,u,r,w,T),T+=1);for(let A of p)a.delete(D).where(eq(D.id,A.id)).run(),_l(a,A,r,w,T,{runId:e.runId,reason:tl}),T+=1;let P=0,C=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let A of S){let Q=mn("thl");a.insert(D).values({id:Q,thread_id:u.id,source:"auto",kind:A.kind,status:"active",text:A.text,covers_from_task_id:A.coversFromTaskId,covers_to_task_id:A.coversToTaskId,revision:0,created_at:w,updated_at:w,agent_id:C,source_task_id:A.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:A.contentFingerprint,dismissed_at:null}).run();let ce=a.select().from(D).where(eq(D.id,Q)).get();if(!ce)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");sr(a,ce,r,w,"thread.highlight.created",T),T+=1,P+=1;}let E=a.select().from(D).where(eq(D.thread_id,u.id)).all().filter(A=>A.source==="auto"&&A.status==="active").length;ht(a,{threadId:u.id,seq:T,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:w,payload:{runId:d.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:E,deletedCount:p.length,createdCount:P}}),a.update(H).set({status:"completed",started_at:d.started_at??w,completed_at:w,error_code:null,previous_auto_count:g,new_auto_count:E}).where(and(eq(H.id,d.id),inArray(H.status,or))).run();let x=a.select().from(H).where(eq(H.id,d.id)).get();if(!x)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:x,deletedCount:p.length,createdCount:P,previousAutoCount:g,newAutoCount:E}},{behavior:"immediate"})}catch(a){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:rl});}catch{}throw a instanceof f?a:new f("DB_ERROR","Failed to complete highlight regeneration",a)}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;N(o.threadId,"threadId"),N(o.workspaceId,"workspaceId");let s=ll(o);if(!existsSync(this.resolveDbPath()))return null;let a=this.openHandle(false);try{if(!this.findThread(a.db,o.threadId,o.workspaceId))return null;let d=a.db.select({maxSeq:sql`COALESCE(MAX(${F.seq}), 0)`}).from(F).where(eq(F.thread_id,o.threadId)).get()?.maxSeq??0,u;o.beforeSeq!==void 0?u=a.db.select().from(F).where(and(eq(F.thread_id,o.threadId),lt$1(F.seq,o.beforeSeq))).orderBy(desc(F.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?u=a.db.select().from(F).where(and(eq(F.thread_id,o.threadId),sql`${F.seq} > ${o.afterSeq}`)).orderBy(asc(F.seq)).limit(s+1).all():u=a.db.select().from(F).where(eq(F.thread_id,o.threadId)).orderBy(desc(F.seq)).limit(s+1).all().reverse();let c=u.length>s,l=o.afterSeq!==void 0?u.slice(0,s):c?u.slice(1):u,p=!1,g=l[0];return g&&(p=!!a.db.select({id:F.id}).from(F).where(and(eq(F.thread_id,o.threadId),lt$1(F.seq,g.seq))).limit(1).get()),{items:l,latestSeq:d,hasMoreOlder:p}}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to list thread timeline",d)}finally{a.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=fl(e),r=kn(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(a=>{let d=this.findThread(a,e.threadId,e.workspaceId);if(d||xe(`Thread ${e.threadId} not found`),n.source==="auto"){let g=a.select().from(D).where(and(eq(D.thread_id,e.threadId),eq(D.source_task_id,n.sourceTaskId),eq(D.detector_version,n.detectorVersion),eq(D.content_fingerprint,n.contentFingerprint))).orderBy(asc(D.created_at),asc(D.id)).limit(1).get();if(g)return g}let u=e.id??mn("thl"),c={id:u,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};a.insert(D).values(c).run();let l=a.select().from(D).where(eq(D.id,u)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=Tn(a,d.id)+1;return wn(a,d.id)||(yn(a,d,r,o,p),p+=1),sr(a,l,r,o,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(a){throw a instanceof f?a:new f("DB_ERROR","Failed to create thread highlight",a)}finally{s.close();}}updateHighlight(e){N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&B("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&B("highlight update requires at least one field"),e.kind!==void 0&&bo(e.kind);let n=e.text===void 0?void 0:Oo(e.text),r=kn(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(a=>{let d=this.findThread(a,e.threadId,e.workspaceId);d||xe(`Thread ${e.threadId} not found`);let u=a.select().from(D).where(and(eq(D.id,e.highlightId),eq(D.thread_id,d.id))).limit(1).get();if(u||xe(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new Rn(d.id,u.id,e.expectedRevision,u.revision);if(u.status!=="active")throw new Rn(d.id,u.id,e.expectedRevision,u.revision);let c=e.kind??u.kind,l=n??u.text,p=e.coversFromTaskId??u.covers_from_task_id,g=e.coversToTaskId??u.covers_to_task_id;(!l||p.length===0||g.length===0)&&B("highlight projection is incomplete");let m=c!==u.kind||l!==u.text||p!==u.covers_from_task_id||g!==u.covers_to_task_id,S=r.actorType==="user"&&u.source==="auto"&&m?"manual":u.source;if(!(m||S!==u.source))return u;let T=u.revision+1;a.update(D).set({source:S,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:g,revision:T,updated_at:o}).where(and(eq(D.id,u.id),eq(D.revision,u.revision))).run();let P=a.select().from(D).where(eq(D.id,u.id)).get();if(!P)throw new f("DB_ERROR","Highlight update did not return a row");let C=Tn(a,d.id)+1;return wn(a,d.id)||(yn(a,d,r,o,C),C+=1),sr(a,P,r,o,"thread.highlight.updated",C,u),P},{behavior:"immediate"})}catch(a){throw a instanceof f?a:new f("DB_ERROR","Failed to update thread highlight",a)}finally{s.close();}}dismissHighlight(e){N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&B("expectedRevision must be a non-negative integer");let n=kn(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.findThread(s,e.threadId,e.workspaceId);a||xe(`Thread ${e.threadId} not found`);let d=s.select().from(D).where(and(eq(D.id,e.highlightId),eq(D.thread_id,a.id))).limit(1).get();if(d||xe(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new Rn(a.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let u=d.revision+1;s.update(D).set({status:"dismissed",text:null,revision:u,updated_at:r,dismissed_at:r}).where(and(eq(D.id,d.id),eq(D.revision,d.revision))).run();let c=s.select().from(D).where(eq(D.id,d.id)).get();if(!c)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=Tn(s,a.id)+1;return wn(s,a.id)||(yn(s,a,n,r,l),l+=1),sr(s,c,n,r,"thread.highlight.deleted",l,d),c},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(N(e,"threadId"),N(n,"workspaceId"),r.taskId!==void 0&&N(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&N(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&N(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let a=o.db.select().from(D).where(and(eq(D.thread_id,e),eq(D.status,"active"))).orderBy(asc(D.created_at),asc(D.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return a;let d=o.db.all(sql`
|
|
408
|
+
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof f?s:new f("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(_).set({last_message:n,updated_at:s}).where(eq(_.id,e)).run();}catch(s){throw s instanceof f?s:new f("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(_).set(o).where(eq(_.id,e)).run();}catch(o){throw o instanceof f?o:new f("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 $t("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(d=>d!=="priority"&&d!=="state"))return new $t("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let a=o;if(a.priority===void 0&&a.state===void 0)return new $t("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [a.priority,a.state])if(d!=null&&(typeof d!="string"||d.length===0))return new $t("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let u=this.openHandle(true);try{let d=r?and(eq(_.id,e),eq(_.workspace_id,r)):eq(_.id,e);return u.db.transaction(c=>{let l=c.select({metadata:_.metadata}).from(_).where(d).get();if(!l)return null;let p=_n(l.metadata),g=p.threadTitle,m=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};a.priority===null?delete m.priority:a.priority!==void 0&&(m.priority=a.priority),a.state===null?delete m.state:a.state!==void 0&&(m.state=a.state),Object.keys(m).length>0?p.threadTitle=m:delete p.threadTitle;let T=Object.keys(p).length>0?JSON.stringify(p):null,E=new Date().toISOString();c.update(_).set({metadata:T,updated_at:E}).where(d).run();let w=c.select({metadata:_.metadata}).from(_).where(d).get();if(!w)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let C=ol(w.metadata);return {threadId:e,priority:C.priority,state:C.state}},{behavior:"immediate"})}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to patch thread-title metadata",d)}finally{u.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?and(eq(_.id,e),eq(_.workspace_id,n)):eq(_.id,e);return r.db.transaction(s=>{let a=s.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(o).get();if(!a)return null;let u=a.pinned?0:1,d=_n(a.metadata);if(u){let c=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),l=s.select({metadata:_.metadata}).from(_).where(c).all(),p=null;for(let g of l){let m=_n(g.metadata);typeof m.pinOrder=="number"&&(p===null||m.pinOrder<p)&&(p=m.pinOrder);}d.pinOrder=p===null?0:p-1;}else delete d.pinOrder;return s.update(_).set({pinned:u,metadata:Object.keys(d).length>0?JSON.stringify(d):null}).where(o).run(),{pinned:!!u}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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 a=n?and(eq(_.id,e[s]),eq(_.workspace_id,n)):eq(_.id,e[s]),u=o.select({metadata:_.metadata}).from(_).where(a).get();if(!u)continue;let d=_n(u.metadata);d.pinOrder=s+1,o.update(_).set({metadata:JSON.stringify(d)}).where(a).run();}},{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?and(eq(_.id,e),eq(_.workspace_id,n)):eq(_.id,e),s=r.db.select({starred:_.starred}).from(_).where(o).get();if(!s)return null;let a=s.starred?0:1;return r.db.update(_).set({starred:a}).where(o).run(),{starred:!!a}}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let a=this.openHandle(true);try{let u=n?and(eq(_.id,e),eq(_.workspace_id,n)):eq(_.id,e);return a.db.transaction(c=>{let l=c.select({metadata:_.metadata}).from(_).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},g=p.overdrive??{},m=o?.defaultTurns??g.defaultTurns??3,T=o?.updatedBy??"ui",E=new Date().toISOString(),w,C,M,q;switch(r){case "enable-count":{let y=o?.turns??m,x=o?.consumeCurrent?Math.max(y-1,0):y;w=x>0?"count":"off",C=x,M=!0,q="count";break}case "enable-latch":{w="latch",C=0,M=!0,q="latch";break}case "disable":{w="off",C=0,M=!1;break}default:{let y=g.state??"off",x=typeof g.remaining=="number"?g.remaining:0;if(y==="count"&&x>0){let A=x-1;A<=0?(w="off",C=0):(w="count",C=A),M=!0,q="count";}else y==="latch"?(w="latch",C=0,M=!0,q="latch"):(w="off",C=0,M=!1);break}}return p.overdrive={state:w,remaining:C,defaultTurns:m,updatedAt:E,updatedBy:T},c.update(_).set({metadata:JSON.stringify(p),updated_at:E}).where(u).run(),{applied:M,appliedMode:q,state:w,remaining:C}},{behavior:"immediate"})}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to resolve overdrive",u)}finally{a.close();}}};h();dt();wt();yt();it();h();var Io="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function sl(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+=Io[o%62]);}for(;n.length<t;)n+=Io[randomBytes(1)[0]%62];return n}function kn(t){return `${t}_${sl(8)}`}function ha(t,e){let{createHash:n}=kt("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let a=0;a<32;a++)o[a%8]^=r[a];let s="";for(let a of o)s+=Io[a%62];return `${t}_${s}`}St();h();var il=["urgent","high","medium","low"],al=["investigating","in-progress","in-review","on-hold","done"],ma="custom:";var dl=new Set(il),ul=new Set(al);function Ao(t){return typeof t=="string"&&dl.has(t)}function vo(t){if(typeof t!="string")return false;if(ul.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(ma))return false;let e=t.slice(ma.length);return e.length>=1&&e.length<=20}function _a(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 Oo(t){let e=_a(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return Ao(r.priority)&&(o.priority=r.priority),vo(r.state)&&(o.state=r.state),o}function ka(t,e){let n=_a(t)??{},r={...Oo(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)}er();var gl="regeneration_replaced";var hl="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var ml="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Co=class extends f{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;}},In=class extends Co{},No=class extends f{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},_l=new Set(ws),kl=new Set(Ts),Tl=new Set(ys),wl=new Set(Es),yl=50,wa=100,ya=280,Ea=40,El=new Set(Rs),lr=["queued","running"];function xo(t){return El.has(t)}function B(t){throw new f("VALIDATION",t)}function Ce(t){throw new f("NOT_FOUND",t)}function N(t,e){(typeof t!="string"||t.trim().length===0)&&B(`${e} is required`);}function wn(t={}){let e=t.actor??t,n=e.actorType??"system";return _l.has(n)||B(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&B("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Rl(t){N(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&N(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&B("title must not be empty"),t.title.length>120&&B("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Ao(t.priority)&&B(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!vo(t.state)&&B(`invalid state: ${String(t.state)}`);}function Sl(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&B("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)&&B(`${n} must be a non-negative integer`);let e=t.limit??yl;return (!Number.isInteger(e)||e<1||e>wa)&&B(`limit must be between 1 and ${wa}`),e}function Po(t){typeof t!="string"&&B("text is required");let e=t.trim();return e.length===0&&B("text must not be empty"),e.length>ya&&B(`text must be at most ${ya} characters`),e}function Ye(t,e){return N(t??"",e),t}function Do(t){wl.has(t)||B(`invalid highlight kind: ${String(t)}`);}function Il(t){Tl.has(t)||B(`invalid highlight source: ${String(t)}`);}function Al(t){N(t.threadId,"threadId"),N(t.workspaceId,"workspaceId");let e=t.source??"manual";Il(e),Do(t.kind);let n=Po(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&o&&r===o?r:void 0),p=Ye(l,"taskId");return (r!==p||o!==p)&&B("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Ye(r,"coversFromTaskId"),a=Ye(o,"coversToTaskId"),u=t.sourceTaskId??s,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Ye(u??void 0,"sourceTaskId"),Ye(d??void 0,"detectorVersion"),Ye(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:a,agentId:t.agentId??null,sourceTaskId:u,detectorVersion:d,contentFingerprint:c}}function vl(t,e){(!t||typeof t!="object")&&B(`candidates[${e}] is required`),Do(t.kind);let n=Po(t.text),r=Ye(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Ye(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Ye(t.coversToTaskId,`candidates[${e}].coversToTaskId`),a=t.contentFingerprint?.trim()||ha("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return N(a,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:a}}function Ol(t){Array.isArray(t)||B("candidates must be an array"),t.length>Ea&&B(`candidates must contain at most ${Ea} items`);let e=new Map;for(let[n,r]of t.entries()){let o=vl(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function Sn(t){let e=Oo(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 bl(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&B("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function yn(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${U.seq}), 0)`}).from(U).where(eq(U.thread_id,e)).get()?.maxSeq??0}function En(t,e){return !!t.select({id:U.id}).from(U).where(eq(U.thread_id,e)).limit(1).get()}function _t(t,e){kl.has(e.type)||B(`invalid thread event type: ${String(e.type)}`);let n=kn("the");t.insert(U).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:bl(e.payload),created_at:e.createdAt}).run();let r=t.select().from(U).where(eq(U.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function Rn(t,e,n,r,o){let s=Sn(e);_t(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 fr(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 pr(t,e,n,r,o,s,a){let u=o==="thread.highlight.created"?fr(e):{before:a?fr({...e,...a,id:e.id}):void 0,after:fr(e)};return _t(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:u})}function xl(t,e,n,r,o,s){return _t(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:fr(e),...s??{}}})}var gr=class extends ke{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 f("NOT_FOUND","Database not found");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=W(n);if(e)try{Ne(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=eq(_.id,n),s=r===void 0?o:r===null?and(o,isNull(_.workspace_id)):and(o,eq(_.workspace_id,r));return e.select().from(_).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(H).where(eq(H.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(N(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:_.workspace_id}).from(_).where(eq(_.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(N(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?Sn(o):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Rl(e);let n=wn(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.findThread(s,e.threadId,e.workspaceId);a||Ce(`Thread ${e.threadId} not found`);let u=Sn(a),d=e.title!==void 0,c=d&&e.title!==u.title,l=d&&a.title_locked!==1,p=e.priority!==void 0&&e.priority!==u.priority,g=e.state!==void 0&&e.state!==u.state,m=c||p||g;if(!m&&!l)return u;let T=a.metadata;(p||g)&&(T=ka(a.metadata,{priority:e.priority,state:e.state}));let E={};if(m&&(E.metadata=T,E.updated_at=r),c&&(E.title=e.title),d&&(E.title_locked=1),s.update(_).set(E).where(e.workspaceId===void 0?eq(_.id,e.threadId):e.workspaceId===null?and(eq(_.id,e.threadId),isNull(_.workspace_id)):and(eq(_.id,e.threadId),eq(_.workspace_id,e.workspaceId))).run(),!m){let M={...a,title_locked:1};return Sn(M)}let w=yn(s,a.id)+1;En(s,a.id)||(Rn(s,a,n,r,w),w+=1),c&&(_t(s,{threadId:a.id,seq:w,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),w+=1),p&&(_t(s,{threadId:a.id,seq:w,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),w+=1),g&&_t(s,{threadId:a.id,seq:w,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let C={...a,title:c?e.title:a.title,metadata:T,title_locked:d?1:a.title_locked,updated_at:r};return Sn(C)},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("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(N(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(${U.seq}), 0)`}).from(U).where(eq(U.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(N(e,"threadId"),N(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:i.id,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.started_at,completedAt:i.completed_at}).from(i).where(and(eq(i.thread_id,e),eq(i.workspace_id,n),inArray(i.status,[...Di,"completed","done","error"]),or$1(isNull(i.parent_task_id),eq(i.parent_task_id,"")),sql`${i.result} IS NOT NULL AND length(trim(${i.result})) > 0`)).orderBy(asc(i.started_at),asc(i.id)).all().map(a=>({taskId:a.taskId,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.startedAt,completedAt:a.completedAt})):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.requestId,"requestId"),N(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&N(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||Ce(`Thread ${e.threadId} not found`);let a=o.select().from(H).where(and(eq(H.thread_id,s.id),eq(H.request_id,e.requestId))).orderBy(desc(H.requested_at),desc(H.id)).limit(1).get();if(a)return {run:a,created:!1};let u=o.select().from(H).where(and(eq(H.thread_id,s.id),inArray(H.status,lr))).orderBy(asc(H.requested_at),asc(H.id)).limit(1).get();if(u)throw new No(u);let d=e.runId??kn("thr");o.insert(H).values({id:d,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(H).where(eq(H.id,d)).get();if(!c)throw new f("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("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(N(e,"runId"),n!==void 0&&N(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 f?o:new f("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(N(e,"threadId"),N(n,"workspaceId"),N(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(H).where(and(eq(H.thread_id,e),eq(H.request_id,r))).orderBy(desc(H.requested_at),desc(H.id)).limit(1).get()??null:null}catch(s){throw s instanceof f?s:new f("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){N(e,"runId"),n!==void 0&&N(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.findRegenerationRun(s,e,n);if(a||Ce(`Highlight regeneration run ${e} not found`),xo(a.status)||B(`invalid highlight regeneration status: ${a.status}`),a.status!=="queued")return a;s.update(H).set({status:"running",started_at:r}).where(and(eq(H.id,a.id),eq(H.status,"queued"))).run();let u=s.select().from(H).where(eq(H.id,a.id)).get();if(!u)throw new f("DB_ERROR","Highlight regeneration run start did not return a row");return u},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){N(e.runId,"runId"),N(e.errorCode,"errorCode"),e.workspaceId!==void 0&&N(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||Ce(`Highlight regeneration run ${e.runId} not found`),xo(s.status)||B(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(H).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(H.id,s.id),inArray(H.status,lr))).run();let a=o.select().from(H).where(eq(H.id,s.id)).get();if(!a)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return a},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=hl){N(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(H).set({status:"failed",completed_at:n,error_code:e}).where(inArray(H.status,lr)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){N(e.runId,"runId"),N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.detectorVersion,"detectorVersion");let n=Ol(e.candidates),r=wn(e),o=this.openHandle(true),s=false;try{return o.db.transaction(a=>{let u=this.findRegenerationRun(a,e.runId,e.workspaceId);if((!u||u.thread_id!==e.threadId)&&Ce(`Highlight regeneration run ${e.runId} not found`),xo(u.status)||B(`invalid highlight regeneration status: ${u.status}`),u.status==="failed")throw new f("CONFLICT","Highlight regeneration run has already failed");if(u.status==="completed")return {run:u,deletedCount:0,createdCount:0,previousAutoCount:u.previous_auto_count??0,newAutoCount:u.new_auto_count??0};s=!0;let d=this.findThread(a,e.threadId,e.workspaceId);d||Ce(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&B("detectorVersion does not match the regeneration run");let c=a.select().from(P).where(eq(P.thread_id,d.id)).orderBy(asc(P.created_at),asc(P.id)).all(),l=new Set(n.map(A=>A.contentFingerprint)),p=c.filter(A=>A.source==="auto"&&A.status==="active"&&A.revision===0&&!l.has(A.content_fingerprint??"")),g=c.filter(A=>A.source==="auto"&&A.status==="active").length,m=new Set(c.filter(A=>!p.includes(A)&&A.content_fingerprint).map(A=>A.content_fingerprint)),T=n.filter(A=>!m.has(A.contentFingerprint)),E=new Date().toISOString(),w=yn(a,d.id)+1;En(a,d.id)||(Rn(a,d,r,E,w),w+=1);for(let A of p)a.delete(P).where(eq(P.id,A.id)).run(),xl(a,A,r,E,w,{runId:e.runId,reason:gl}),w+=1;let C=0,M=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let A of T){let Q=kn("thl");a.insert(P).values({id:Q,thread_id:d.id,source:"auto",kind:A.kind,status:"active",text:A.text,covers_from_task_id:A.coversFromTaskId,covers_to_task_id:A.coversToTaskId,revision:0,created_at:E,updated_at:E,agent_id:M,source_task_id:A.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:A.contentFingerprint,dismissed_at:null}).run();let _e=a.select().from(P).where(eq(P.id,Q)).get();if(!_e)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");pr(a,_e,r,E,"thread.highlight.created",w),w+=1,C+=1;}let y=a.select().from(P).where(eq(P.thread_id,d.id)).all().filter(A=>A.source==="auto"&&A.status==="active").length;_t(a,{threadId:d.id,seq:w,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:E,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:y,deletedCount:p.length,createdCount:C}}),a.update(H).set({status:"completed",started_at:u.started_at??E,completed_at:E,error_code:null,previous_auto_count:g,new_auto_count:y}).where(and(eq(H.id,u.id),inArray(H.status,lr))).run();let x=a.select().from(H).where(eq(H.id,u.id)).get();if(!x)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:x,deletedCount:p.length,createdCount:C,previousAutoCount:g,newAutoCount:y}},{behavior:"immediate"})}catch(a){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:ml});}catch{}throw a instanceof f?a:new f("DB_ERROR","Failed to complete highlight regeneration",a)}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;N(o.threadId,"threadId"),N(o.workspaceId,"workspaceId");let s=Sl(o);if(!existsSync(this.resolveDbPath()))return null;let a=this.openHandle(false);try{if(!this.findThread(a.db,o.threadId,o.workspaceId))return null;let u=a.db.select({maxSeq:sql`COALESCE(MAX(${U.seq}), 0)`}).from(U).where(eq(U.thread_id,o.threadId)).get()?.maxSeq??0,d;o.beforeSeq!==void 0?d=a.db.select().from(U).where(and(eq(U.thread_id,o.threadId),lt$1(U.seq,o.beforeSeq))).orderBy(desc(U.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?d=a.db.select().from(U).where(and(eq(U.thread_id,o.threadId),sql`${U.seq} > ${o.afterSeq}`)).orderBy(asc(U.seq)).limit(s+1).all():d=a.db.select().from(U).where(eq(U.thread_id,o.threadId)).orderBy(desc(U.seq)).limit(s+1).all().reverse();let c=d.length>s,l=o.afterSeq!==void 0?d.slice(0,s):c?d.slice(1):d,p=!1,g=l[0];return g&&(p=!!a.db.select({id:U.id}).from(U).where(and(eq(U.thread_id,o.threadId),lt$1(U.seq,g.seq))).limit(1).get()),{items:l,latestSeq:u,hasMoreOlder:p}}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to list thread timeline",u)}finally{a.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=Al(e),r=wn(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(a=>{let u=this.findThread(a,e.threadId,e.workspaceId);if(u||Ce(`Thread ${e.threadId} not found`),n.source==="auto"){let g=a.select().from(P).where(and(eq(P.thread_id,e.threadId),eq(P.source_task_id,n.sourceTaskId),eq(P.detector_version,n.detectorVersion),eq(P.content_fingerprint,n.contentFingerprint))).orderBy(asc(P.created_at),asc(P.id)).limit(1).get();if(g)return g}let d=e.id??kn("thl"),c={id:d,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};a.insert(P).values(c).run();let l=a.select().from(P).where(eq(P.id,d)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=yn(a,u.id)+1;return En(a,u.id)||(Rn(a,u,r,o,p),p+=1),pr(a,l,r,o,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(a){throw a instanceof f?a:new f("DB_ERROR","Failed to create thread highlight",a)}finally{s.close();}}updateHighlight(e){N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&B("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&B("highlight update requires at least one field"),e.kind!==void 0&&Do(e.kind);let n=e.text===void 0?void 0:Po(e.text),r=wn(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(a=>{let u=this.findThread(a,e.threadId,e.workspaceId);u||Ce(`Thread ${e.threadId} not found`);let d=a.select().from(P).where(and(eq(P.id,e.highlightId),eq(P.thread_id,u.id))).limit(1).get();if(d||Ce(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new In(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new In(u.id,d.id,e.expectedRevision,d.revision);let c=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,g=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||g.length===0)&&B("highlight projection is incomplete");let m=c!==d.kind||l!==d.text||p!==d.covers_from_task_id||g!==d.covers_to_task_id,T=r.actorType==="user"&&d.source==="auto"&&m?"manual":d.source;if(!(m||T!==d.source))return d;let w=d.revision+1;a.update(P).set({source:T,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:g,revision:w,updated_at:o}).where(and(eq(P.id,d.id),eq(P.revision,d.revision))).run();let C=a.select().from(P).where(eq(P.id,d.id)).get();if(!C)throw new f("DB_ERROR","Highlight update did not return a row");let M=yn(a,u.id)+1;return En(a,u.id)||(Rn(a,u,r,o,M),M+=1),pr(a,C,r,o,"thread.highlight.updated",M,d),C},{behavior:"immediate"})}catch(a){throw a instanceof f?a:new f("DB_ERROR","Failed to update thread highlight",a)}finally{s.close();}}dismissHighlight(e){N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&B("expectedRevision must be a non-negative integer");let n=wn(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.findThread(s,e.threadId,e.workspaceId);a||Ce(`Thread ${e.threadId} not found`);let u=s.select().from(P).where(and(eq(P.id,e.highlightId),eq(P.thread_id,a.id))).limit(1).get();if(u||Ce(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new In(a.id,u.id,e.expectedRevision,u.revision);if(u.status==="dismissed")return u;let d=u.revision+1;s.update(P).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(and(eq(P.id,u.id),eq(P.revision,u.revision))).run();let c=s.select().from(P).where(eq(P.id,u.id)).get();if(!c)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=yn(s,a.id)+1;return En(s,a.id)||(Rn(s,a,n,r,l),l+=1),pr(s,c,n,r,"thread.highlight.deleted",l,u),c},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(N(e,"threadId"),N(n,"workspaceId"),r.taskId!==void 0&&N(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&N(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&N(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let a=o.db.select().from(P).where(and(eq(P.thread_id,e),eq(P.status,"active"))).orderBy(asc(P.created_at),asc(P.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return a;let u=o.db.all(sql`
|
|
406
409
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
407
410
|
ORDER BY started_at ASC, id ASC
|
|
408
|
-
`),
|
|
411
|
+
`),d=new Map(u.map((g,m)=>[g.id,m])),c=r.taskId===void 0?void 0:d.get(r.taskId),l=r.coversFromTaskId===void 0?void 0:d.get(r.coversFromTaskId),p=r.coversToTaskId===void 0?void 0:d.get(r.coversToTaskId);return a.filter(g=>{let m=d.get(g.covers_from_task_id),T=d.get(g.covers_to_task_id);if(m===void 0||T===void 0)return !1;let E=Math.min(m,T),w=Math.max(m,T);return !(c!==void 0&&(c<E||c>w)||l!==void 0&&w<l||p!==void 0&&E>p)})}catch(s){throw s instanceof f?s:new f("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)}};h();dt();wt();yt();it();St();xr();var J=class extends f{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Sa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Ul(){let t=randomBytes(16),e="";for(let n of t)e+=Sa[n%Sa.length];return e.slice(0,12)}function Ia(){return `c_${Ul()}`}function ql(t){return typeof t=="string"&&Or.includes(t)}function Fl(t){return typeof t=="string"&&br.includes(t)}function Bt(t){if(!ql(t))throw new J("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Aa(t){if(!Fl(t))throw new J("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function va(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new J("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function jt(t){if(typeof t!="string"||t.trim().length===0)throw new J("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function hr(t){if(typeof t!="string"||t.trim().length===0)throw new J("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function st(t,e){return and(eq(I.code_group,t),or$1(isNull(I.workspace_id),eq(I.workspace_id,e)))}var mr=class extends ke{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 f("NOT_FOUND","Database not found");e&&mkdirSync(dirname(n),{recursive:true});let r=W(n);if(e)try{Ne(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(Bt(e),jt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(I).where(and(st(e,n),eq(I.is_archived,0))).orderBy(asc(I.sort_order),asc(I.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(Bt(e),jt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(I).where(st(e,n)).orderBy(asc(I.sort_order),asc(I.code)).all()}catch(o){throw new f("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(Bt(n),jt(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)hr(o);if(new Set(e.codes).size!==e.codes.length)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new J("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(I).where(st(n,e.workspaceId)).all(),a=s.filter(m=>m.is_archived===0),u=new Set(s.map(m=>m.code)),d=new Set(a.map(m=>m.code)),c=e.codes.find(m=>!u.has(m));if(c)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==a.length||e.codes.some(m=>!d.has(m)))throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let l=new Map(a.map(m=>[m.code,m])),p=e.codes.map(m=>{let T=l.get(m);if(!T)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${m}`);return T}),g;for(let[m,T]of p.entries())T.sort_order!==m&&(g??=new Date().toISOString(),o.update(I).set({sort_order:m,updated_at:g}).where(and(eq(I.code_group,n),eq(I.code,T.code))).run());return o.select().from(I).where(st(n,e.workspaceId)).orderBy(asc(I.sort_order),asc(I.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(Bt(e),hr(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(I).where(and(eq(I.code_group,e),eq(I.code,n))).limit(1).get()??null}catch(o){throw new f("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){jt(e.workspaceId);let n=va(e.name);Aa(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:I.code}).from(I).where(and(st("THREAD_STATE",e.workspaceId),eq(I.is_archived,0),eq(I.code_name,n))).limit(1).get())throw new J("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let a=o.select({maxSortOrder:sql`max(${I.sort_order})`}).from(I).where(st("THREAD_STATE",e.workspaceId)).get(),u=new Date().toISOString(),d=Ia();for(;o.select({code:I.code}).from(I).where(and(eq(I.code_group,"THREAD_STATE"),eq(I.code,d))).limit(1).get();)d=Ia();o.insert(I).values({code_group:"THREAD_STATE",code:d,code_name:n,color:e.color,sort_order:(a?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:u,updated_at:u}).run();let c=o.select().from(I).where(and(eq(I.code_group,"THREAD_STATE"),eq(I.code,d))).limit(1).get();if(!c)throw new f("DB_ERROR","Created common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(Bt(e.group),hr(e.code),jt(e.workspaceId),e.name===void 0&&e.color===void 0)throw new J("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:va(e.name);e.color!==void 0&&Aa(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(I).where(and(eq(I.code_group,e.group),eq(I.code,e.code))).limit(1).get();if(!s)throw new J("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),n===null&&s.is_builtin!==1)throw new J("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let d=and(st(e.group,e.workspaceId),eq(I.is_archived,0));if(o.select({code:I.code}).from(I).where(and(d,eq(I.code_name,n),sql`${I.code} <> ${e.code}`)).limit(1).get())throw new J("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`)}let a={updated_at:new Date().toISOString()};e.name!==void 0&&(a.code_name=n??null),e.color!==void 0&&(a.color=e.color),o.update(I).set(a).where(and(eq(I.code_group,e.group),eq(I.code,e.code))).run();let u=o.select().from(I).where(and(eq(I.code_group,e.group),eq(I.code,e.code))).limit(1).get();if(!u)throw new f("DB_ERROR","Updated common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(Bt(e),hr(n),jt(r),typeof o!="boolean")throw new J("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(a=>{let u=a.select().from(I).where(and(eq(I.code_group,e),eq(I.code,n))).limit(1).get();if(!u)throw new J("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(u.is_builtin===1)throw new J("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(u,r),!o&&u.code_name!==null&&a.select({code:I.code}).from(I).where(and(st(e,r),eq(I.is_archived,0),eq(I.code_name,u.code_name),ne$1(I.code,n))).limit(1).get())throw new J("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${u.code_name}`);a.update(I).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(and(eq(I.code_group,e),eq(I.code,n))).run();let d=a.select().from(I).where(and(eq(I.code_group,e),eq(I.code,n))).limit(1).get();if(!d)throw new f("DB_ERROR","Archived common code could not be read back");return d},{behavior:"immediate"})}catch(a){throw a instanceof f?a:new f("DB_ERROR","Failed to archive common code",a)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new J("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function Wl(t){return t.replace(/<crewx_thread_context[^>]*>[\s\S]*?<\/crewx_thread_context>/g,"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
409
412
|
`).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(`
|
|
410
|
-
`).trim()}function
|
|
411
|
-
`):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=
|
|
412
|
-
`)[0].slice(0,200)),n.push({id:`${r.id}-assistant`,text:a,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:
|
|
413
|
+
`).trim()}function Gl(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 zl(t,e,n){if(!t||e==="failed"&&ar(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(`
|
|
414
|
+
`):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=Wl(r);}return r}var _r=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new cr({dbPath:this.dbPath})}getThreadHistoryRepo(){return new gr({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),a=o.findTopLevelTasks(e,void 0,r),u=new Set(["queued","cancelled"]);a=a.filter(p=>(!p.status||!u.has(p.status))&&(!n?.currentTraceId||p.trace_id!==n.currentTraceId));let d=s?.platform??"cli",c=this.rowsToMessages(a),l=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,s?.workspace_id??null);return {threadId:e,platform:d,messages:c,...l?{highlights:l}:{},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 mr({dbPath:this.dbPath}),o=(s,a)=>{try{return r.resolve(s,a)?.code_name||a}catch{return a}};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=Gl(r.metadata),a=zl(r.result,o??r.status??null,s);if(a||o==="running"||o==="failed"){let u={agent_id:r.agent_id,task_id:r.id};o&&(u.status=o),o==="failed"&&r.error&&(u.reason=r.error.split(`
|
|
415
|
+
`)[0].slice(0,200)),n.push({id:`${r.id}-assistant`,text:a,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:u});}}return n}};var Lo=class extends Qe{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new _r(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{Lo as ConversationPlugin,Tr as FileLoggerPlugin,So as SqliteTracingPlugin};
|