@crewx/sdk 0.9.0-rc.104 → 0.9.0-rc.106
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/boxing/box.types.d.ts +4 -0
- package/dist/config/default-agent-models.d.ts +11 -0
- package/dist/esm/index.js +230 -278
- package/dist/esm/plugins/index.js +163 -220
- package/dist/esm/repository/index.js +126 -182
- package/dist/events/types.d.ts +1 -0
- package/dist/index.browser.d.ts +2 -0
- package/dist/index.browser.js +4 -4
- package/dist/index.d.ts +12 -6
- package/dist/index.js +232 -280
- 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 +163 -220
- package/dist/plugins/sqlite-tracing.d.ts +2 -0
- package/dist/repository/index.d.ts +2 -2
- package/dist/repository/index.js +126 -182
- package/dist/repository/task.repository.d.ts +23 -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,57 +1,64 @@
|
|
|
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 Ko,{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,desc,inArray,lt as lt$1,notLike,asc,like,gte,isNotNull}from'drizzle-orm';import {spawn}from'child_process';var xa=Object.defineProperty;var mt=(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 Ca=(t,e)=>{for(var n in e)xa(t,n,{get:e[n],enumerable:true});};var Da,La,R,h=v(()=>{Da=()=>fileURLToPath(import.meta.url),La=()=>le__default.dirname(Da()),R=La();});var f,ot=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 zo(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 Ga(t,e){let n=zo(t),r=zo(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function st(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&Ga(t,join(Ko.homedir(),".crewx","crewx.db")))throw new Error(`${Wa}: ${t}. Set CREWX_DB or CREWX_TRACES_DB to an isolated temporary path or :memory:.`);return t}var Wa,ke,it=v(()=>{h();Wa="[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(Ko.homedir(),".crewx","crewx.db");return st(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=st(t),r=mt("better-sqlite3"),{drizzle:o}=mt("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 = ${Va}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),runRaw:(i,u=[])=>s.prepare(i).run(...u),close:()=>s.close()}}var Va,kt=v(()=>{h();it();Va=32*1024*1024;});function On(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Ja(t,e){if(e>0||!On(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(Ka))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function Ya(t,e,n){if(!On(t,"__drizzle_migrations")||!On(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(le__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let u=Xa[i.tag];if(!u)continue;let d=le__default.join(e,`${i.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(_=>_.name));for(let[_,m]of Object.entries(u))g.has(_)||(t.run(`ALTER TABLE tasks ADD COLUMN ${_} ${m}`),g.add(_));}}function Qa(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(le__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let u=le__default.join(e,`${i.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(w=>w.trim()).filter(Boolean).every(w=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(w)))continue;p.every(({table:w,column:k})=>t.all(`PRAGMA table_info("${w}")`).some(L=>L.name===k))&&t.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);}}function Za(t,e){let{sql:n}=mt("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(i=>{let u=r.entries.find(c=>c.tag===i);if(!u)throw new Error(`Missing release/App compatibility migration: ${i}`);let d=readFileSync(le__default.join(e,`${i}.sql`),"utf-8");return {entry:u,content:d,hash:createHash("sha256").update(d).digest("hex")}});t.transaction(i=>{let u=new Set(i.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()))i.run(n.raw(c));i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${d.hash}, ${d.entry.when})`);}}},{behavior:"immediate"});}function td(t,e,n,r){let s=JSON.parse(readFileSync(le__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===ed);if(!s)return;let i=le__default.join(e,`${s.tag}.sql`);if(!existsSync(i))return;let u=createHash("sha256").update(readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.hash===u))return;if(!On(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 nd(t){let{migrate:e}=mt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=mt("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'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ja(t,i),s?.cnt&&(Za(t,o),Qa(t,o,n),Ya(t,o,n));let u=td(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let c=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;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){Jo.has(e)||(nd(t),Jo.add(e));}var Jo,Ka,Xa,ed,Tt=v(()=>{h();Jo=new Set,Ka={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"};Xa={"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"}};ed="0027_task_stop_scope_cleanup";});var wt,Rr=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 a,Vt=v(()=>{h();a=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),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,Qo=v(()=>{h();Vt();De=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},t=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var pd,fd,T,Dn=v(()=>{h();Rr();pd="json_extract(metadata, '$.threadTitle.state')",fd="json_extract(metadata, '$.threadTitle.priority')",T=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(pd)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(fd))}));});var md,ts=v(()=>{h();Vt();md=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>md.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 ns=v(()=>{h();Vt();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},t=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(t.timestamp)}));});var os=v(()=>{h();Dn();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>T.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 is=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 us=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 cs=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 ps=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 gs=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 hs=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 _s=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 Ts,ws=v(()=>{h();Ts=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(()=>Ts.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(()=>Ts.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 xr,Cr,I,Nr=v(()=>{h();xr=["THREAD_STATE","THREAD_PRIORITY"],Cr=["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 ys,Es,Rs,Ss,Is,q,$,P,As=v(()=>{h();Dn();ys=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Es=["user","agent","system"],Rs=["auto","manual"],Ss=["decision","judgment","issue","result","pivot"],Is=["queued","running","completed","failed"],q=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>T.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)})),$=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>T.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(()=>T.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 bs=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();Rr();Vt();Qo();Dn();ts();ns();os();is();us();cs();ps();gs();hs();_s();ws();Nr();As();bs();});var Rt,Dr,Os,Lr=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}},Dr=new Set(["gpt-5.3-codex-spark"]),Os=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 Mr(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 Wd(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Yt;let e=Mr(t),n=jd[e];if(n)return Fn[n]??Rt[n]??Yt;if(Fn[e])return Fn[e];if(Rt[e])return Rt[e];if(Dr.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Yt;if(Os.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Yt;let r={...Rt,...Fn};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Yt}function Gd(t,e,n,r=0,o){let s=Wd(n),i=Math.min(r,t),d=(t-i)*s.input/1e6,c=i*s.cachedInput/1e6,l=e*s.output/1e6;return d+c+l}function xs(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:Gd(e??0,n??0,o,r??0)}var jd,Yt,Fn,Bn=v(()=>{h();Lr();Lr();jd={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"},Yt={input:0,cachedInput:0,output:0},Fn={};});function Ds(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Ns(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Ls(t){return Number.isSafeInteger(t)&&t>0}function Xd(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:Ds(c)});return}let o="",s="",i=false,u,d=setTimeout(()=>{try{r.kill();}catch{}u({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${Cs}ms`)});},Cs);u=c=>{i||(i=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 Ms(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Xd(t,e)}function Yd(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Qd(){return new Promise(t=>{setImmediate(t);})}function ut(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Ns(n)==="ESRCH"?"not_found":Ns(n)==="EPERM"?"alive":"unknown"}}function Zd(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 Hs(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??Kd),i=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 Qd();;){let l=Zd(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,Yd(Math.min(s,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function Ps(t,e,n,r,o){let s=await Hs(t,e,o.hardConfirmMs??Jd,{...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 jn(t,e,n={}){if(!Ls(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="],i;try{i=await Ms(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let u=i.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 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(!Ls(t))return o("Invalid process ID");let s=e.kill??process.kill,i=ut(t,s);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let g;try{g=await Ms("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){g={status:null,stdout:"",stderr:"",error:Ds(m)};}let _=ut(t,s);return _==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(_==="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 Ps(t,s,u,r,e);if(await Hs(t,s,e.graceMs??Vd,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 Ps(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 Cs,St,Vd,Kd,Jd,Wn=v(()=>{h();Cs=3e3,St="SIGINT",Vd=2e3,Kd=25,Jd=100;});function Bs(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 qs(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)=>Bs(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function js(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 Fs(t){return {taskId:t.id,source:js(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function su(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var Gn,Ws=v(()=>{h();it();kt();Tt();ot();Et();Gn=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?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{Ne(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new 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,i)=>Bs(s,i));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(i=>{let u=this.requireStateRowInTransaction(i,e),d=js(u);if(d==="blob"){let g=qs(e,u.logs);if(i.update(a).set({logs:JSON.stringify([...g,...r]),log_revision:sql`${a.log_revision} + 1`}).where(eq(a.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(i.insert(De).values(r.map((g,_)=>({task_id:e,seq:c+_,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:sql`${a.log_revision} + 1`}).where(eq(a.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?Fs(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 su(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=Fs(s);if(i.source==="blob"){let l=qs(e,s.logs);return {...i,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(),{...i,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 Gs=v(()=>{h();});var Z,At=v(()=>{h();Z=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};});var ze,Hr=v(()=>{h();At();ze=class extends Z{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function iu(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?gu[e]:void 0;return s?s(r,o):Object.values(Vs).some(i=>i(r,o))}function $e(t,e){let n=t.split(`
|
|
13
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>iu(r,e))}function we(t){return typeof t=="object"&&t!==null}function zs(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 au(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:zs(t,e)}function du(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 uu(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 cu(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||we(t.part)||e==="result"&&typeof t.result=="string")}function lu(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?we(t.data):e==="result"?typeof t.result=="string":false}function pu(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 fu(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 Vs,gu,vt=v(()=>{h();Vs={claude:zs,codex:du,opencode:uu,copilot:lu,gemini:pu},gu={...Vs,claude:au,opencode:cu,grok:fu,antigravity:()=>false};});function Ue(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function qe(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 bt=v(()=>{h();});function _u(t){let e=ku(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>wu(s.value)),r=Tu(e);return {result:n.length===1&&n[0].index===r?yu(n[0].line.value):null,resultPreview:Su(e,n),hasReservedLine:n.length>0}}function Ve(t,e){let n=_u(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function ku(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
8
14
|
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
9
15
|
`?`\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
|
|
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
|
|
16
|
+
`: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 Tu(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function wu(t){return t.trimStart().startsWith(hu)}function yu(t){let e=t.trim();if(!e.startsWith(Ks)||!e.endsWith("]]"))return null;let n=e.slice(Ks.length,-2);if(!n)return null;try{return Eu(JSON.parse(n))}catch{return null}}function Eu(t){return Ru(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Ru(t){if(!Iu(t)||Object.keys(t).some(r=>!mu.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?Js(t.taskId)&&Js(t.agentId):t.isError===true}function Su(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 Js(t){return typeof t=="string"&&t.trim().length>0}function Iu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ks,hu,mu,Zt=v(()=>{h();Ks="[[crewx:delegation-result ",hu="[[crewx:delegation-result",mu=new Set(["schema","taskId","agentId","isError"]);});function Fe(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 Ot=v(()=>{h();});var Xs,zn,$r,Vn=v(()=>{h();Xs=["none","minimal","low","medium","high","xhigh","max","ultra"],zn={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"]},$r={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($r).map(([t,e])=>[t,e.models]));});function Ur(t){return vu[t]??t}function Ou(t){return bu.get(t)??t}function qr(t){if(!t)return {};let e=Cu.get(t);return e?{...e}:{model:t}}function Fr(t,e){return t==="antigravity"||t==="cli/antigravity"?qr(e):e===void 0?{}:{model:Ou(e)}}var Au,vu,bu,xu,Cu,en=v(()=>{h();Au=[{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]"}],vu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};bu=new Map(Au.map(({baseModelId:t,catalogModelId:e})=>[t,e]));xu=[{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"}],Cu=new Map(xu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Pu(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function et(t){return Kn(t).models}function Kn(t){return Nu[t]??$r[t]??Pu()}function tn(t,e){let n=Kn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Fr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Ys(t){return Kn(t).modelOverrides}function Qs(){return et("claude")}function Zs(){return et("codex")}function ei(){return et("copilot")}function ti(){return et("antigravity")}var Nu,ct=v(()=>{h();Vn();Bn();en();Nu={};});function ni(t){return Du[t]??t}var Du,ri=v(()=>{h();ct();en();Du={auto:"default"};});function Jn(t,e){return (zn[t]??[]).includes(e)}function tt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Lu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function oi(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 si(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 ii(t){return !t||!Jn("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function ai(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=ni(t);return e.has(n)?["--permission-mode",n]:[]}function di(t){return t?Jn("claude",t)?["--effort",t]:[]:[]}function ui(t){return t==="default"?[]:t&&Mu.has(t)?["--permission-mode",t]:[]}function ci(t){return t===true?["--always-approve"]:[]}function li(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 pi(t){return t?Jn("grok",t)?["--effort",t]:[]:[]}function fi(t){if(!t)return [];switch(Ur(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function gi(t){return t?Jn("antigravity",t)?["--effort",t]:[]:[]}var Lu,Mu,nn=v(()=>{h();ri();en();Vn();Lu=new Set(Xs);Mu=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,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function $u(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,u="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:u??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:d}}function Uu(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function hi(t){let e=new Map,n;for(let s of t.split(`
|
|
17
|
+
`))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let u=i.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(`
|
|
18
|
+
`))if(r.trim())try{let o=JSON.parse(r),s=Uu(o);if(s){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedInputTokens+=s.cachedInputTokens;continue}let i=Hu(o)??$u(o);i&&(e=i);}catch{}return n||(e??void 0)}var rn=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 lt=v(()=>{h();});function mi(t){let e=t.split(`
|
|
19
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Bu(t){let e=t.split(`
|
|
20
|
+
`).filter(n=>n.trim());for(let n of e.reverse())try{let r=JSON.parse(n);if(typeof r=="object"&&r!==null&&r.type==="result")return r}catch{}}function ju(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
14
21
|
|
|
15
|
-
`):""}function
|
|
16
|
-
`):
|
|
17
|
-
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,
|
|
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
|
|
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`
|
|
22
|
+
`):""}function Wu(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function Gu(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),o=e.id,s=e.input,i=Fe(s);return r==="Bash"&&Ue(i)?qe(t,i,o):{timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(u=>u.type==="text"&&typeof u.text=="string").map(u=>u.text).join(`
|
|
23
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...Ve(i,r)}}return null}var qu,Fu,Xn,Br=v(()=>{h();Hr();At();vt();bt();Zt();Ot();nn();ct();rn();lt();qu=new Set(["tool_progress"]),Fu="cli/claude";Xn={command:"claude",meta:{displayName:"Claude",models:Qs(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=tt(e.model),s=e.effort??o,i=ai(e.mode),u=di(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,...i,...u,...d,...p],stdinMessage:t}:{args:["--output-format","stream-json","--verbose",...c,...i,...u,...d,...p],stdinMessage:t}}return {args:["-p","--output-format","stream-json","--verbose",...c,...i,...u,...d],stdinMessage:t}},extractText(t){let e=Bu(t);if(e?.is_error===true){let o=Xn.extractFailure(JSON.stringify(e));if(o)throw o;let s=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new Z(`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,Fu,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=mi(t);if(n)return n;let r=t.trim();return $e(r,"claude")?"":r},extractPartialText(t){return mi(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 ze(`Claude rate limit: ${n.rateLimitType??"unknown"} (status: ${n.status})`)}if(e.error==="rate_limit"){let n=ju(e);return new ze(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(Wu(n))return new ze(`Claude rate limit: ${n}`)}}catch{}return null},parseResultMeta(t){let e=t.split(`
|
|
24
|
+
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,u=o.modelUsage,d=u?Object.keys(u)[0]??null:null;return {usage:i,model:d}}}catch{}let n=hi(t);return n?{usage:{inputTokens:n.inputTokens,outputTokens:0,cachedInputTokens:n.cachedInputTokens,costUsd:0},model:n.model??null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(r!=="assistant"&&r!=="user")return [];let s=n.message?.content;if(!Array.isArray(s))return [];let i=Ae(n,e??new Date().toISOString()),u=[];for(let d of s){let c=Gu(i,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?qu.has(r):!1}catch{return false}}};});function _i(t){let e=t.split(`
|
|
25
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var zu,jr,Wr=v(()=>{h();vt();rn();bt();Ot();Zt();ct();Vn();lt();zu=new Set(["interactive","plan","autopilot"]);jr={command:"copilot",meta:{displayName:"Copilot",models:ei()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&zu.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(zn.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=_i(t);if(e)return e;let n=t.trim();return $e(n,"copilot")?"":n},extractPartialText(t){return _i(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()),i=o.toolCallId;if(r==="tool.execution_start"){let u=String(o.toolName||""),d=o.arguments,c=Fe(d);return (u==="bash"||u==="Bash")&&Ue(c)?[qe(s,c,i)]:[{timestamp:s,type:"tool_use",toolName:u,toolInput:c,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let u=o.error;if(u)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Ve(String(u.message||""),true)}];let d=o.result,c=String(d?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Ve(c,false)}]}if(r==="assistant.message"){let u=String(o.content||"");return u?[{timestamp:s,type:"text",content:u}]:[]}return []}};});function Ku(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 i=t.slice(s).trim();return i&&e.push(i),e}function Ju(t){return t[0]==="exec"?t.slice(1):t}function ki(t){let e=t.split(`
|
|
26
|
+
`).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Xu(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return Ue(r)?[qe(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function Yu(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",...Ve(r,o)}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=Fe(o);return r==="Bash"&&Ue(s)?qe(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",...Ve(o,r)}}if(n==="web_search"){let r=e.action,o;if(r?.type==="search"){let s=r.queries;o=String(r.query||"")||(s?.length?s.join(", "):"")||String(e.query||"");}else o=e.query?"open: "+String(e.query):"";return o?{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:o}:null}if(n==="file_change"){let r=e.changes;if(!Array.isArray(r)||r.length===0)return null;let o=r.map(i=>String(i.path||"")).filter(Boolean);if(o.length===0)return null;let s=o.length===1?o[0]:`${o.slice(0,2).join(", ")}${o.length>2?` (+${o.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:s}}return null}function 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=Fe(o);return r==="Bash"&&Ue(s)?qe(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var Vu,Gr,zr=v(()=>{h();vt();rn();bt();Ot();Zt();nn();ct();lt();Vu=new Set(["turn.started","turn.completed","item.updated"]);Gr={command:"codex",meta:{displayName:"Codex",models:Zs(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=tt(e.model),s=e.effort??o,i=e.resumeSessionId?si(e.mode):oi(e.mode),u=ii(s),d=r?["-m",r]:[],c=Ju(e.additionalArgs??[]),p=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...i,...u,...d,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...i,...u,...d,...c],stdinMessage:t}},extractText(t){let e=ki(t);if(e)return e;let n=t.trim();return $e(n,"codex")?"":n},extractPartialText(t){return ki(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=Ku(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let u=i.type;if(!u||!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread."))continue;let d=Ae(i,n),c=i.item;if(c){if(u==="item.started"){r.push(...Xu(d,c));continue}if(u==="item.completed"){let l=Yu(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?Vu.has(r):!1}catch{return false}}};});function tc(t){return t?ec[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Yn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ri(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 i=t.slice(s).trim();return i&&e.push(i),e}function Nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function nc(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let i=JSON.parse(o);Nt(i)?e.push(i):n=!0;continue}catch{}let s=Ri(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let u=JSON.parse(i);Nt(u)?e.push(u):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,Ei).trim()}function Si(t){let e=Nt(t.error)?t.error:void 0,n=e&&Nt(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),i=r&&o&&r!==o?`${r}: ${o}`:r??o??yi;return (s?`${i} (ref: ${s})`:i).slice(0,Ei)}function Ti(t){let e=nc(t),n=[],r=null,o=0,s=[],i,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(Si(d));continue}if(c==="step_finish"){u=true;let l=Nt(d.part)?d.part:void 0;i=typeof l?.reason=="string"?l.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorMessages:s,terminalReason:i,hasTerminal:u}}function Ii(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Qn(){return new Z("OpenCode returned no assistant output.",Ct,{code:"EMPTY_OUTPUT",kind:"transient"})}function rc(){return new Z("OpenCode emitted malformed JSON output.",Ct,{code:"PROVIDER_CRASHED",kind:"transient"})}function wi(t,e){switch(Ii(t)){case "length":return new Z("OpenCode stopped because the context window was exceeded.",Ct,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new Z("OpenCode stopped because the content filter blocked the response.",Ct,{code:"UNKNOWN",kind:"permanent"});case "error":return new Z(e?`OpenCode error: ${e}`:`${yi} while generating a response.`,Ct,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var Zu,Ct,yi,Ei,ec,Vr,Kr=v(()=>{h();At();rn();Ot();lt();Zu=new Set(["step_start","step_finish"]),Ct="cli/opencode",yi="OpenCode provider error",Ei=240,ec={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Vr={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Yn(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=tc(e.mode);Yn(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!Yn(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!Yn(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let u;return !n&&!i&&!e.env?.OPENCODE_PERMISSION&&(u={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:u}},extractText(t){let e=Ti(t),n=e.errorMessages[0];if(n){let i=wi("error",n);if(i)throw i}let r=wi(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 Qn();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Qn();return e.resultText}if(e.malformed)throw rc();if(!e.hasTerminal)throw Qn();let s=Ii(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Qn()},interpretExit(t,e,n=""){if(t===0)return null;let o=Ti(n).errorMessages[0];return o?new Z(`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=Ri(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let u=Ae(i,n),d=i.type;if(d){if(d==="text"){let l=i.part?.text;l&&r.push({timestamp:u,type:"text",content:l});continue}if(d==="tool_use"){let c=i.part;if(!c)continue;let l=String(c.tool||""),p=String(c.callID||""),g=c.state,_=String(g?.status||""),m=g?.input,w=Fe(m);if(r.push({timestamp:u,type:"tool_use",toolName:l,toolUseId:p,toolInput:w}),_==="completed"&&g?.output!==void 0){let k=g.output,C=typeof k=="string"?k:JSON.stringify(k);r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:C,isError:false});}else _==="error"&&r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(d==="error"){let c=Si(i);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?Zu.has(r):!1}catch{return false}}};});function on(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function oc(t,e){if(!(t?et(Jr).some(s=>s.id===t):false)||!t)return e;let r=tn(Jr,t),o=Ys(Jr)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var Jr,Xr,Yr=v(()=>{h();At();en();ct();nn();Jr="antigravity";Xr={command:"agy",meta:{displayName:"Antigravity",models:ti(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=tt(e.model),s=qr(r),i=s.model,u=e.effort??o??s.effort,d=oc(i,u),c=e.additionalArgs??[],l=i&&!on(c,"--model")?["--model",i]:[],p=on(c,"--effort")?[]:gi(d),g=on(c,"--mode")||on(c,"--dangerously-skip-permissions")?[]:fi(e.mode),_=on(c,"--print")?[]:["--print",t];return {args:[...l,...p,...g,...c,..._]}},extractText(t){let e=t.trim();if(!e)throw new Z("Antigravity CLI returned empty output with exit code 0. agy may have hidden an auth/quota/model error in its log file; inspect ~/.gemini/antigravity-cli/log for details.","cli/antigravity",{code:"EMPTY_OUTPUT",kind:"transient"});return e},parseResultMeta(t){return {usage:null,model:null}},parseEvent(t,e){return []}};});var Ai=v(()=>{h();bt();Ot();Zt();lt();});function Pt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function er(t){return Pt(t)?t:void 0}function ce(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 uc(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let u=t[i];if(n===-1){(u==="{"||u==="[")&&(n=i,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,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function sn(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Pt(n)?[n]:[]}catch{return uc(e).flatMap(n=>{try{let r=JSON.parse(n);return Pt(r)?[r]:[]}catch{return []}})}}function an(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function dn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(dn).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
27
|
+
`):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=dn(t[e]);if(n!==void 0)return n}}}function cc(t){if(t.rawOutput!==null&&t.rawOutput!==void 0)return dn(t.rawOutput)??an(t.rawOutput);if(t.content!==null&&t.content!==void 0)return dn(t.content)??an(t.content);if(t.result!==null&&t.result!==void 0)return dn(t.result)??an(t.result)}function Ci(t){let e=er(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?Ni(n):"Grok CLI reported an error."}function Ni(t){return (t.replace(dc,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function xi(t){return ac.test(t)}function lc(t){let e=er(t.modelUsage);return e?Object.keys(e)[0]??null:null}function pc(t){let e=er(t.usage);if(!e)return null;let n=ft(e.cache_read_input_tokens);return {inputTokens:ft(e.input_tokens)+n,cachedInputTokens:n,outputTokens:ft(e.output_tokens),costUsd:ft(t.total_cost_usd)}}function fc(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
28
|
+
`).flatMap(sn)){if(i.type!=="usage")continue;let u=er(i.usage);if(!u)continue;let d=ce(i.signature);if(d&&d.length>0){let l=`signature:${d}`;if(s.has(l))continue;s.add(l);}let c=ft(u.cache_read_input_tokens);e+=ft(u.input_tokens)+c,n+=c,r+=ft(u.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function gc(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,vi)){if(!Pt(s))continue;let i=ce(s.content)?.trim();if(!i)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(`- ${i}${l}`);}if(n.length===0)return [];e.entries.length>vi&&n.push(Oi);let r=n.join(`
|
|
29
|
+
`),o=r.length>bi?`${r.slice(0,bi-1)}${Oi}`:r;return [{timestamp:t,type:"info",content:o}]}function hc(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 gc(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:an(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:cc(e),isError:r!=="completed"||e.isError===true}]}if(n==="error"){let r=Ci(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var Zn,ic,ac,dc,vi,bi,Oi,Qr,Zr=v(()=>{h();At();Hr();ct();nn();lt();Zn="cli/grok",ic=new Set(["available_commands","usage","end"]),ac=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,dc=/\u001b\[[0-?]*[ -/]*[@-~]/g,vi=20,bi=4e3,Oi="\u2026";Qr={command:"grok",createSessionId:()=>randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=tt(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],u=n?et("grok").some(D=>D.id===n):false,d=n&&u?tn("grok",n):[],c=!o||d.length===0||d.includes(o)?o:void 0,l=pi(c),p=e.additionalArgs??[],g=D=>p.some(E=>E===D||E.startsWith(`${D}=`)),_=e.providerOptions,m=_?.alwaysApprove,w=_?.sandbox,k=g("--permission-mode")?[]:ui(e.mode),C=g("--always-approve")?[]:ci(m),L=g("--sandbox")?[]:li(w);return {args:["--no-auto-update",...s,"--single",t,"--output-format","streaming-json","--no-alt-screen",...i,...l,...k,...C,...L,...p]}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
30
|
+
`).flatMap(sn))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 sn(t))if(e.type==="error"){let n=Ci(e);return xi(an(e))?new ze(n,Zn):new Z(n,Zn)}return null},interpretExit(t,e){if(t===0)return null;let n=Ni(e)||`Grok CLI exited with code ${t}.`;return xi(e)?new ze(n,Zn):new Z(n,Zn)},parseResultMeta(t){let n=t.split(`
|
|
31
|
+
`).flatMap(sn).find(r=>r.type==="end");return n?{usage:pc(n),model:lc(n)}:{usage:fc(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return sn(t).flatMap(r=>hc(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"?ic.has(n.type):!1}catch{return false}}};});var Pi,Di=v(()=>{h();Br();Wr();zr();Kr();Yr();Ai();Zr();Br();Wr();zr();Kr();Yr();Zr();bt();Pi={codex:Gr,claude:Xn,opencode:Vr,antigravity:Xr,copilot:jr,grok:Qr};});function Li(t){if(t.startsWith("cli/"))return Pi[t.slice(4)]}var Mi=v(()=>{h();Gs();Di();});function tr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function mc(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function nr(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(`
|
|
32
|
+
`)??"";if(!n.trim())return;let r=Li(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=mc(o?.model,t.model),i=o?.usage;if(!i)return {stdout:n,adapter:r};let u=tr(i.inputTokens),d=tr(i.outputTokens),c=tr(i.cachedInputTokens),l=xs(tr(i.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 eo=v(()=>{h();Mi();Bn();});function kc(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"&&_c.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=kc(t.metadata);return e==="user_stop"?"stopped":e==="runner_lost"?"runner_lost":e==="launch_failed"?"failed":typeof t.error=="string"&&Hi.stopped.test(t.error)?"stopped":typeof t.error=="string"&&Hi.runnerLost.test(t.error)?"runner_lost":"failed"}default:return t.status}}var $i,Hi,_c,rr=v(()=>{h();$i=["success","failed","stopped","runner_lost"],Hi={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},_c=new Set(["user_stop","runner_lost","launch_failed"]);});function to(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 no(){return to("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Lt(){return to("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function sr(){return to("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Dt(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function or(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 Tc(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 Ui(t,e){return !!t.stop_requested_at&&Dt(t.stop_requested_epoch)===Dt(e)}function qi(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=Tc(t.getTask(e.taskId));return !o||o.status!=="running"||Dt(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function Wi(t,e){let n=un.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),un.delete(t),true)}function cn(t,e){let n=un.get(t);return !n||e!==void 0&&n.runEpoch!==Dt(e)?false:Wi(t,n)}function Gi(t,e){let n=Dt(e.runEpoch);cn(e.taskId);let r=true,o=null;try{let c=qi(t,{...e,runEpoch:n});r=c.accepted,o=c.row;}catch(c){or(c);}if(!r)return false;let s=no(),i=Math.min(s,1e3),u=setInterval(()=>{let c=un.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=i;let l=c.heartbeatElapsedMs>=s,p=qi(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){Wi(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=s,c.lastHeartbeatAt=Date.now()),p.row&&Ui(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(or));}catch(l){or(l);}},i),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return un.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),o&&Ui(o,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(or)),true}var Fi,Bi,ji,un,ln=v(()=>{h();Fi=1e4,Bi=3e4,ji=18e5;un=new Map;});function ir(t,e=Date.now(),n=io){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=co(n,io,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function co(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function Xi(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function vc(t){if(!t)return;let e=Xi(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=vc(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function go(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 so(t,e){return z(t,Ec,e)}function bc(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Lt():false}function Oc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function xc(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=Xi(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 Cc(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return ge(r,n)}async function Nc(t,e,n,r){let o=Date.now()+n;for(;;){let s=Cc(t,e);if(s)return s;let i=o-Date.now();if(i<=0)return;await new Promise(u=>{setTimeout(u,Math.min(r,i));});}}async function Ji(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}),i=t.getTask(e);if(!s.accepted){if(s.status==="pending"){let D=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),E=t.getTask(e);if(D||!E||E.status!=="running")return ge(E);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(i)}let u=s.runEpoch,d=co(n.graceMs,io,0),c=co(n.pollMs,wc,1),l=await Nc(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return ge(p);let g=xc(p),_=g[0];if(!_){let D=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),E=t.getTask(e);return D||E?.status!=="running"?ge(E):z(E,"Failed to finalize task stop")}let m=Oc(n),w="unknown";if(!bc(p,Date.now())){let D=n.processControl?.checkProcessOwnershipAsync??jn;try{w=await D(_,n.ownershipMarkers??fo,m);}catch{w="unknown";}if(w!=="owned")return go(p)}let k=n.processControl?.terminateProcessTree??It;for(let D of g){let E;try{E=await k(D,{...m,signal:St});}catch(x){E={status:"failed",pid:D,method:m.platform==="win32"?"taskkill":"process-group",error:x instanceof Error?x.message:String(x)};}if(E.status==="failed")return z(t.getTask(e),E.error??"Failed to terminate process tree")}let C=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),L=t.getTask(e);return C||L?.status!=="running"?ge(L,_):z(L,"Task changed before stop was finalized")}function lo(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function po(t){return Number.isSafeInteger(t)&&t>=0}function pn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Pc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Dc(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 Mc(t){switch(t){case "epoch_mismatch":return ao;case "workspace_mismatch":return uo;default:return}}async function Yi(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return so(n,lo(e.targetPid)?e.targetPid:void 0);if(!po(e.sourceRunEpoch)||!po(e.settleRunEpoch)||pn(n.run_epoch)!==e.settleRunEpoch)return z(n,ro,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,oo,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,Rc,e.targetPid)}let s=t.getTask(e.taskId);if(!s||s.status!=="running")return so(s,e.targetPid);if(o.runEpoch!==e.settleRunEpoch||pn(s.run_epoch)!==e.settleRunEpoch)return z(s,ro,e.targetPid);if(e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId)return z(s,oo,e.targetPid);if(!lo(e.targetPid))return z(s,yc);let i=Pc(e),u=e.processControl?.checkProcessOwnershipAsync??jn,d="unknown";try{d=await u(e.targetPid,e.ownershipMarkers??fo,i);}catch{d="unknown";}if(d!=="owned")return go(s,e.targetPid);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return so(c,e.targetPid);if(pn(c.run_epoch)!==e.settleRunEpoch)return z(c,ro,e.targetPid);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,oo,e.targetPid);let l=e.processControl?.terminateProcessTree??It,p;try{p=await l(e.targetPid,{...i,signal:St});}catch{return z(t.getTask(e.taskId),zi,e.targetPid)}if(p.status==="failed")return z(t.getTask(e.taskId),zi,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return z(t.getTask(e.taskId),Vi,e.targetPid)}return g?ge(t.getTask(e.taskId),e.targetPid):z(t.getTask(e.taskId),Vi,e.targetPid)}async function Qi(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return ge(n);if(!po(e.expectedRunEpoch)||pn(n.run_epoch)!==e.expectedRunEpoch)return z(n,ao);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,uo);let r=n.pid;if(!lo(r))return z(n,Sc);let o=Dc(e),s=e.processControl?.checkProcessOwnershipAsync??jn,i="unknown";try{i=await s(r,e.ownershipMarkers??fo,o);}catch{i="unknown";}if(i!=="owned")return go(n,r,Ic);let u=e.processControl?.terminateProcessTree??It,d;try{d=await u(r,{...o,signal:St});}catch{return z(t.getTask(e.taskId),Ki,r)}if(d.status==="failed")return z(t.getTask(e.taskId),Ki,r);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return ge(c,r);if(pn(c.run_epoch)!==e.expectedRunEpoch)return z(c,ao,r);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,uo,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),Ac,r)}let p=Mc(l);return p?z(t.getTask(e.taskId),p,r):l!=="settled"?ge(t.getTask(e.taskId),r):Lc(t.getTask(e.taskId),r)}function Zi(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(mo(),ea)).then(({TaskRepository:s})=>Ji(new s,r,o))}return Ji(t,e,n)}var io,wc,fo,yc,ro,oo,Ec,zi,Vi,Rc,ao,uo,Sc,Ic,Ki,Ac,ho=v(()=>{h();Wn();ln();io=5e3,wc=250;fo=["crewx","claude","codex","opencode","grok","node"],yc="INSTRUCTION_STOP_TARGET_PID_MISSING",ro="INSTRUCTION_STOP_EPOCH_MISMATCH",oo="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Ec="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",zi="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Vi="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Rc="INSTRUCTION_STOP_REQUEST_FAILED",ao="HOST_SHUTDOWN_EPOCH_MISMATCH",uo="HOST_SHUTDOWN_WORKSPACE_MISMATCH",Sc="HOST_SHUTDOWN_TARGET_PID_MISSING",Ic="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",Ki="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",Ac="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var ea={};Ca(ea,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>da,HOST_SHUTDOWN_TERMINAL_ERROR:()=>sa,PENDING_ADOPT_GRACE_MS:()=>aa,PID_NULL_REAP_GRACE_MS:()=>Io,TASK_HEARTBEAT_HARD_STALE_MS:()=>ji,TASK_HEARTBEAT_INTERVAL_MS:()=>Fi,TASK_HEARTBEAT_STALE_MS:()=>Bi,TaskRepository:()=>_n,hasRecordedUsage:()=>So,mergeTerminalReason:()=>Ro,resolveTaskHeartbeatHardStaleMs:()=>sr,resolveTaskHeartbeatIntervalMs:()=>no,resolveTaskHeartbeatStaleMs:()=>Lt});function be(t){return {...t,status:gt(t)}}function ta(t){return {...t,status:gt(t)}}function To(t=a.model,e=a.metadata){let n=sql`
|
|
26
33
|
CASE
|
|
27
|
-
WHEN ${
|
|
28
|
-
WHEN ${
|
|
29
|
-
WHEN ${
|
|
30
|
-
WHEN ${
|
|
31
|
-
WHEN ${
|
|
32
|
-
WHEN ${
|
|
33
|
-
WHEN ${
|
|
34
|
+
WHEN ${t} LIKE 'claude-%' OR ${t} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
35
|
+
WHEN ${t} LIKE 'gpt-%' OR ${t} LIKE 'codex-%' THEN 'codex'
|
|
36
|
+
WHEN ${t} LIKE 'gemini-%' THEN 'gemini'
|
|
37
|
+
WHEN ${t} LIKE 'grok-%' THEN 'grok'
|
|
38
|
+
WHEN ${t} LIKE 'zai-%' OR ${t} LIKE 'openrouter/z-ai/%' THEN 'opencode'
|
|
39
|
+
WHEN ${t} LIKE 'minimax/%' THEN 'minimax'
|
|
40
|
+
WHEN ${t} LIKE 'qwen%' THEN 'qwen'
|
|
34
41
|
ELSE 'unknown'
|
|
35
42
|
END
|
|
36
|
-
`,
|
|
43
|
+
`,r=sql`json_extract(${e}, '$.provider')`,o=sql`trim(${r})`,s=sql`substr(${o}, 1, instr(${o}, '/') - 1)`,i=sql`
|
|
37
44
|
CASE
|
|
38
|
-
WHEN instr(${
|
|
39
|
-
AND ${
|
|
40
|
-
THEN substr(${
|
|
41
|
-
ELSE ${
|
|
45
|
+
WHEN instr(${o}, '/') > 0
|
|
46
|
+
AND ${s} IN ('cli', 'acp', 'api', 'plugin', 'remote')
|
|
47
|
+
THEN substr(${o}, instr(${o}, '/') + 1)
|
|
48
|
+
ELSE ${o}
|
|
42
49
|
END
|
|
43
50
|
`;return sql`
|
|
44
51
|
CASE
|
|
45
|
-
WHEN ${
|
|
46
|
-
WHEN json_valid(${
|
|
47
|
-
WHEN json_type(${
|
|
48
|
-
WHEN json_type(${
|
|
49
|
-
WHEN json_type(${
|
|
50
|
-
WHEN ${
|
|
51
|
-
WHEN trim(${
|
|
52
|
-
ELSE ${
|
|
52
|
+
WHEN ${e} IS NULL THEN ${n}
|
|
53
|
+
WHEN json_valid(${e}) = 0 THEN 'unknown'
|
|
54
|
+
WHEN json_type(${e}, '$') IS NOT 'object' THEN 'unknown'
|
|
55
|
+
WHEN json_type(${e}, '$.provider') IS NULL THEN ${n}
|
|
56
|
+
WHEN json_type(${e}, '$.provider') IS NOT 'text' THEN 'unknown'
|
|
57
|
+
WHEN ${o} = '' THEN 'unknown'
|
|
58
|
+
WHEN trim(${i}) = '' THEN 'unknown'
|
|
59
|
+
ELSE ${i}
|
|
53
60
|
END
|
|
54
|
-
`}function
|
|
61
|
+
`}function mn(t){return sql`${t} NOT IN (${sql.join(Gc.map(e=>sql`${e}`),sql`, `)})`}function ar(t){let e=sql`
|
|
55
62
|
CASE
|
|
56
63
|
WHEN json_valid(${t}) = 1
|
|
57
64
|
THEN json_extract(${t}, '$.usageAccounting')
|
|
@@ -61,29 +68,27 @@ ${r.join(`
|
|
|
61
68
|
COALESCE(SUM(
|
|
62
69
|
CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
|
|
63
70
|
), 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?`,
|
|
71
|
+
`}function qt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ee(t){if(!t)return {};try{let e=JSON.parse(t);return qt(e)?{...e}:{}}catch{return {}}}function dr(t,e){let n=t.origin&&ia.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 zc(t){let e=ee(t).stopRequest;if(qt(e)&&!(typeof e.origin!="string"||!ia.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function ra(){return or$1(isNull(a.stop_requested_at),ne(sql`COALESCE(${a.stop_requested_epoch}, 0)`,sql`COALESCE(${a.run_epoch}, 0)`))}function Ro(t,e){let n=ee(t??null);return n.terminalReason=e,JSON.stringify(n)}function yo(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==na&&(n[jc]=e),{error:na,metadata:n}}function re(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function So(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 oa(t){return {inputTokens:re(t.inputTokens??0),outputTokens:re(t.outputTokens??0),cachedInputTokens:re(t.cachedInputTokens??0),costUsd:re(t.costUsd??0)}}function Vc(t){if(qt(t))return {inputTokens:re(t.inputTokens),outputTokens:re(t.outputTokens),cachedInputTokens:re(t.cachedInputTokens),costUsd:re(t.costUsd)}}function Kc(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=Vc(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function ur(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}var ko,Ht,Fc,$t,Ut,Bc,wo,hn,Oe,na,sa,jc,Wc,Gc,ia,Io,aa,da,_n,mo=v(()=>{h();it();kt();Tt();ot();Et();Bn();Wn();Ws();eo();rr();ln();ho();ln();ko=40,Ht="2026-05-09",Fc="0.8.9-rc.13",$t=10,Ut=parseInt(Fc.split("rc.")[1]);Bc=new Set(["workflow","mcp"]),wo="usageByEpoch",hn="lateUsage",Oe="usageAccounting",na="Stopped by user",sa="Stopped by app shutdown",jc="terminalErrorOriginal",Wc=new Set(["stopped","runner_lost"]),Gc=["pending","running"];ia=new Set(["http","cli","instruction","workflow","internal"]);Io=600*1e3,aa=600*1e3,da=300*1e3,_n=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 Gn({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{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(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(and(eq(a.id,e.id),o,eq(a.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:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!s)return;let i=V(s.run_epoch);if(s.status!=="running"){r={accepted:!1,status:s.status,runEpoch:i};return}let u=s.stop_requested_at!==null&&V(s.stop_requested_epoch)===i,d=u?s.stop_requested_at:e.requestedAt,c=ee(s.metadata),l=u?zc(s.metadata)??dr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):dr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(and(eq(a.id,e.id),eq(a.status,"running"),ra())).run().changes===0){let m=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(eq(a.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}r={accepted:!1,status:m.status,runEpoch:V(m.run_epoch),...m.stop_requested_at&&V(m.stop_requested_epoch)===V(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:s.status,runEpoch:i};let g=new Set([e.id]),_=(m,w)=>{if(w>=8)return;let k=o.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(and(eq(a.parent_task_id,m),eq(a.status,"running"))).all();for(let C of k)g.has(C.id)||(g.add(C.id),o.update(a).set({stop_requested_at:d,stop_requested_epoch:sql`${a.run_epoch}`,metadata:JSON.stringify({...ee(C.metadata),stopRequest:l})}).where(and(eq(a.id,C.id),eq(a.status,"running"),ra())).run(),_(C.id,w+1));};_(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:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!s)return;let i=V(s.run_epoch),u=V(e.sourceRunEpoch),d=V(e.settleRunEpoch);if(s.status!=="running"||i!==d||e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId){r={accepted:!1,status:s.status,runEpoch:i};return}let c=d===0?or$1(eq(a.run_epoch,0),isNull(a.run_epoch)):eq(a.run_epoch,d),l=or$1(isNull(a.stop_requested_at),isNull(a.stop_requested_epoch),ne(a.stop_requested_epoch,u)),p=dr({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),g=k=>o.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:JSON.stringify({...ee(s.metadata),stopRequest:p})}).where(and(eq(a.id,e.id),eq(a.status,"running"),c,k,l)).run();if((e.workspaceId===void 0?g():e.workspaceId===null?g(isNull(a.workspace_id)):g(eq(a.workspace_id,e.workspaceId))).changes>0){r={accepted:!0,status:s.status,runEpoch:d};return}let m=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(eq(a.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 w=V(m.run_epoch);r={accepted:!1,status:m.status,runEpoch:w,...m.stop_requested_at&&V(m.stop_requested_epoch)===u?{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 i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||V(i.run_epoch)!==V(e.runEpoch))return;let u=i.stop_requested_at!==null&&V(i.stop_requested_epoch)===V(e.runEpoch),d=ee(i.metadata),c=u?yo(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...c.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??ur(i.started_at,r,void 0),g=i.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,i.run_epoch);o=s.update(a).set({status:"stopped",error:c.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(and(eq(a.id,e.id),eq(a.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(i=>{let u=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(eq(a.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(a.run_epoch):eq(a.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?isNull(a.workspace_id):eq(a.workspace_id,e.workspaceId),p={...ee(u.metadata),terminalReason:"runner_lost"},g=u.duration_ms??ur(u.started_at,r,void 0);s=i.update(a).set({status:"runner_lost",error:sa,completed_at:r,duration_ms:g,metadata:JSON.stringify(p)}).where(and(eq(a.id,e.id),eq(a.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 Zi(this,e,n)}async stopTaskGenerationForInstruction(e){return Yi({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(a).values(s).onConflictDoUpdate({target:a.id,set:{status:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:sql`COALESCE(excluded.pid, ${a.pid})`,command:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workspace_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.workspace_id}, excluded.workspace_id) ELSE ${a.workspace_id} END`,cwd:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.project_id}, excluded.project_id) ELSE ${a.project_id} END`,crewx_version:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,coding_agent_command:sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:or$1(eq(a.status,"running"),and(eq(a.status,"pending"),isNull(a.pid)))}).run();};try{o(r);}catch(s){let i=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|cwd/i.test(i)||!/no such column|no column named/i.test(i))throw s;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(k=>k.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":"",_=c?", log_storage":"",m=c?", ?":"",w=c?`,
|
|
67
72
|
log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
|
|
68
73
|
id, agent_id, prompt, mode, status, started_at, pid,
|
|
69
74
|
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${
|
|
75
|
+
workspace_id${l}, project_id, platform, crewx_version, thread_id,
|
|
76
|
+
model, rendered_prompt, coding_agent_command${_}
|
|
77
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${p}${m})
|
|
73
78
|
ON CONFLICT(id) DO UPDATE SET
|
|
74
79
|
status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
|
|
75
80
|
pid = COALESCE(excluded.pid, tasks.pid),
|
|
76
81
|
command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.command ELSE tasks.command END,
|
|
77
82
|
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,
|
|
83
|
+
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
84
|
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
85
|
crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
|
|
81
86
|
model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
|
|
82
87
|
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(${
|
|
86
|
-
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=and(eq(
|
|
88
|
+
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${w}
|
|
89
|
+
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:a.status,run_epoch:a.run_epoch,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||V(r.run_epoch)!==V(e.runEpoch))return !1;let o=ee(r.metadata);o.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0&&(o.providerPid=e.providerPid);let s=r.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,r.run_epoch),i=n.db.update(a).set({metadata:JSON.stringify(o)}).where(and(eq(a.id,e.id),eq(a.status,"running"),s)).run();return i.changes>0&&V(e.runEpoch)>0&&n.db.update(a).set({stop_requested_at:null,stop_requested_epoch:null}).where(and(eq(a.id,e.id),eq(a.status,"running"),s,sql`${a.stop_requested_at} IS NOT NULL
|
|
90
|
+
AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.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(a).set({status:"running"}).where(and(eq(a.id,e),eq(a.status,"pending"),isNull(a.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(a).set({status:"failed",error:n,completed_at:r}).where(and(eq(a.id,e),eq(a.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 i=!1;return s.db.transaction(u=>{let d=u.select({metadata:a.metadata}).from(a).where(and(eq(a.id,e),eq(a.status,"pending"))).limit(1).get();if(!d)return;let c=yo(ee(d.metadata),n),l={...c.metadata,stopMethod:"cooperative",stopRequest:dr(o,r)};i=u.update(a).set({status:"stopped",error:c.error,completed_at:r,metadata:JSON.stringify(l)}).where(and(eq(a.id,e),eq(a.status,"pending"))).run().changes===1;},{behavior:"immediate"}),i}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to stop pending task",i)}finally{s.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(a).where(eq(a.project_id,e)).orderBy(desc(a.started_at)).all().map(be)}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 i=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,result:a.result,exit_code:a.exit_code,error:a.error,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!i)return;let u=V(i.run_epoch),d=V(e.runEpoch),c=i.status==="running"&&u===d,l=i.stop_requested_at!==null&&V(i.stop_requested_epoch)===u,p=c&&l,g=i.status==="stopped"&&u===d&&l,_=ee(i.metadata),m=qt(_[hn])?_[hn]:{},w=String(d),k=Wc.has(i.status),C=k&&u===d&&!So(i)&&!Object.prototype.hasOwnProperty.call(m,w),L=k&&u===d&&!Object.prototype.hasOwnProperty.call(m,w),D=u>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||u!==d,E={},x;if(i.status!=="running"&&(r=i.status,o=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),D&&(i.status==="running"||L)){x=ee(i.metadata);let b=qt(x[wo])?{...x[wo]}:{};b[String(d)]=oa(e),x[wo]=b;let Q=Kc(b),_e=Q.inputTokens!==0||Q.outputTokens!==0||Q.cachedInputTokens!==0||Q.costUsd!==0;_e&&_[Oe]==="unavailable"?x[Oe]="recorded":i.status!=="running"&&!_e&&_[Oe]===void 0&&(x[Oe]="unavailable"),E.metadata=JSON.stringify(x),E.input_tokens=Q.inputTokens,E.output_tokens=Q.outputTokens,E.cached_input_tokens=Q.cachedInputTokens,E.cost_usd=Q.costUsd;}else if(c||C)if(c)E.input_tokens=re(e.inputTokens??0),E.output_tokens=re(e.outputTokens??0),E.cached_input_tokens=re(e.cachedInputTokens??0),E.cost_usd=re(e.costUsd??0);else {let b=oa(e),Q=b.inputTokens!==0||b.outputTokens!==0||b.cachedInputTokens!==0||b.costUsd!==0;Q&&(E.input_tokens=b.inputTokens,E.output_tokens=b.outputTokens,E.cached_input_tokens=b.cachedInputTokens,E.cost_usd=b.costUsd),x={..._};let _e=qt(_[hn])?{..._[hn]}:{};_e[w]={at:e.completedAt},x[hn]=_e,x[Oe]===void 0?x[Oe]=Q?"recorded":"unavailable":Q&&x[Oe]==="unavailable"&&(x[Oe]="recorded"),E.metadata=JSON.stringify(x);}if((c||C)&&e.model!==void 0&&e.model!==null&&(!C||i.model===null)&&(E.model=e.model),p){x??=ee(i.metadata);let b=yo(x,e.error);x={...b.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:ir(i.stop_requested_at,e.completedAt)},E.status="stopped",E.result=e.result??i.result,E.error=b.error,E.completed_at=e.completedAt,E.duration_ms=i.duration_ms??e.durationMs??ur(i.started_at,e.completedAt,void 0),E.exit_code=e.exitCode??i.exit_code,E.metadata=JSON.stringify(x);}else if(c)e.partialResultRecovered===!0&&(x??=ee(i.metadata),x.partialResultRecovered=!0,E.metadata=JSON.stringify(x)),E.status=e.status,E.result=e.result??null,E.error=e.error??null,E.completed_at=e.completedAt,E.duration_ms=u>0?ur(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,E.exit_code=e.exitCode??null;else if(g){let b=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(E.result=e.result,b=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(E.exit_code=e.exitCode),e.partialResultRecovered===!0&&(x??=ee(i.metadata),x.partialResultRecovered=!0,E.metadata=JSON.stringify(x)),b&&(r=void 0,o=void 0);}Object.keys(E).length>0&&s.update(a).set(E).where(eq(a.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
|
|
91
|
+
`);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=and(eq(a.id,e.id),eq(a.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:a.metadata}).from(a).where(r).limit(1).get(),i=ee(s?.metadata??null);i.terminalReason=e.terminalReason,o.metadata=JSON.stringify(i);}n.db.update(a).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(a).where(eq(a.status,"running")).orderBy(desc(a.started_at)).all().map(be)}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(a).where(inArray(a.status,["pending","running"])).orderBy(desc(a.started_at)).all().map(be)}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(a).orderBy(desc(a.started_at)).limit(100).all().map(be)}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(a).where(eq(a.id,e)).limit(1).get();return r?be(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:a.id,status:a.status,pid:a.pid,platform:a.platform,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at,started_at:a.started_at,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(or$1(eq(a.status,"running"),eq(a.status,"pending"))).all(),o=this.clock(),s=Math.max(1,Math.trunc(e.tickIntervalMs??da)),i=this.lastReaperTickAt,u=i===void 0?Number.POSITIVE_INFINITY:o-i,d=i!==void 0&&u>=0&&u<=s*2;this.lastReaperTickAt=o;let c=Lt(),l=sr(),p=new Date(o-aa).toISOString(),g=new Date(o).toISOString(),_=new Set,m=0,w=(k,C)=>{let L=ee(Ro(k.metadata,"runner_lost")),D=typeof L.provider=="string"?L.provider:void 0,E;try{E=nr({taskLogRepository:this.taskLogRepository,taskId:k.id,provider:D,model:k.model})?.usage;}catch{}let x={status:"runner_lost",error:C,completed_at:g};E?(x.input_tokens=E.inputTokens,x.output_tokens=E.outputTokens,x.cached_input_tokens=E.cachedInputTokens,x.cost_usd=E.costUsd,k.model===null&&E.model!==null&&(x.model=E.model),L[Oe]="recorded"):!So(k)&&L[Oe]!=="recorded"&&(L[Oe]="unavailable"),x.metadata=JSON.stringify(L);let b=k.run_epoch===null?isNull(a.run_epoch):eq(a.run_epoch,k.run_epoch),Q=k.heartbeat_at===null?isNull(a.heartbeat_at):eq(a.heartbeat_at,k.heartbeat_at),_e=n.db.update(a).set(x).where(and(eq(a.id,k.id),eq(a.status,"running"),b,Q)).run();return _e.changes>0&&m++,_e.changes>0};for(let k of r){if(k.status==="pending"){if(k.pid!==null||k.started_at>=p)continue;let E=Ro(k.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:g,metadata:E}).where(and(eq(a.id,k.id),eq(a.status,"pending"),isNull(a.pid),lt$1(a.started_at,p))).run().changes>0&&m++;continue}if(Bc.has(k.platform??"cli"))continue;if(k.pid===null){let E=`${k.id}:${k.run_epoch??0}`;_.add(E);let x=this.pidNullObservedSince.get(E);if(x===void 0){this.pidNullObservedSince.set(E,o);continue}o-x>=Io&&w(k,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(E);continue}if(k.heartbeat_at===null){ut(k.pid)==="not_found"&&w(k,"Reaped: process not found (orphaned task)");continue}let C=Date.parse(k.heartbeat_at),L=Number.isFinite(C)?o-C:Number.POSITIVE_INFINITY;if(L<=c)continue;ut(k.pid)==="not_found"?w(k,"Reaped: process not found (orphaned task)"):L>l&&d&&w(k,"Reaped: heartbeat stale beyond hard limit (orphaned task)");}for(let k of Array.from(this.pidNullObservedSince.keys()))_.has(k)||this.pidNullObservedSince.delete(k);return m}finally{n.close();}}reapRunningWorkflowTasks(e=Io){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),o=and(eq(a.status,"running"),eq(a.platform,"workflow"),isNull(a.pid),lt$1(a.started_at,r),or$1(isNull(a.metadata),and(notLike(a.metadata,'%"kind":"workflow_card"%'),notLike(a.metadata,'%"kind":"workflow_ui_instance"%')))),s=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(o).all(),i=new Date().toISOString(),u=0;for(let d of s){let c=ee(d.metadata);c.terminalReason="runner_lost";let l=n.db.update(a).set({status:"runner_lost",error:"Reaped: stale workflow run (finally not executed)",completed_at:i,metadata:JSON.stringify(c)}).where(and(eq(a.id,d.id),eq(a.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 i=n?eq(a.workspace_id,n):void 0,u=i?and(eq(a.id,e),i):eq(a.id,e),d=s.db.select().from(a).where(u).limit(1).get()??void 0;if(!d){let c=i?and(eq(a.thread_id,e),i):eq(a.thread_id,e);d=s.db.select().from(a).where(c).orderBy(desc(a.started_at)).limit(1).get()??void 0;}if(d)return be(d)}catch(i){throw new f("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let u=W(i);try{let d=n?and(eq(a.parent_task_id,e),eq(a.workspace_id,n)):eq(a.parent_task_id,e),c=u.db.select().from(a).where(d).orderBy(asc(a.started_at)).all();for(let l of c)o.has(l.id)||(o.add(l.id),s.push(be(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
92
|
SELECT
|
|
88
93
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
89
94
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -104,106 +109,45 @@ ${r.join(`
|
|
|
104
109
|
FROM tasks
|
|
105
110
|
GROUP BY workspace_id
|
|
106
111
|
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,
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
t.
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
GROUP BY t.agent_id, t.workspace_id
|
|
135
|
-
ORDER BY (
|
|
136
|
-
COALESCE(SUM(
|
|
137
|
-
COALESCE(t.input_tokens, 0)
|
|
138
|
-
+ CASE
|
|
139
|
-
WHEN t.started_at >= ${Ve}
|
|
140
|
-
AND (
|
|
141
|
-
t.crewx_version IS NULL
|
|
142
|
-
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, ${Ke}) AS INTEGER) < ${Je})
|
|
144
|
-
)
|
|
145
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
146
|
-
ELSE 0
|
|
147
|
-
END
|
|
148
|
-
), 0)
|
|
149
|
-
+ COALESCE(SUM(t.output_tokens), 0)
|
|
150
|
-
) DESC
|
|
151
|
-
`:sql`
|
|
152
|
-
SELECT
|
|
153
|
-
t.agent_id,
|
|
154
|
-
t.workspace_id,
|
|
155
|
-
COUNT(*) AS total_tasks,
|
|
156
|
-
${a} AS unavailable_task_count,
|
|
157
|
-
COALESCE(SUM(
|
|
158
|
-
COALESCE(t.input_tokens, 0)
|
|
159
|
-
+ CASE
|
|
160
|
-
WHEN t.started_at >= ${Ve}
|
|
161
|
-
AND (
|
|
162
|
-
t.crewx_version IS NULL
|
|
163
|
-
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, ${Ke}) AS INTEGER) < ${Je})
|
|
165
|
-
)
|
|
166
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
167
|
-
ELSE 0
|
|
168
|
-
END
|
|
169
|
-
), 0) AS input_tokens,
|
|
170
|
-
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
171
|
-
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
172
|
-
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
173
|
-
FROM tasks t
|
|
174
|
-
WHERE ${s}
|
|
175
|
-
AND t.started_at >= ${e}
|
|
176
|
-
AND t.started_at < ${n}
|
|
177
|
-
GROUP BY t.agent_id, t.workspace_id
|
|
178
|
-
ORDER BY (
|
|
179
|
-
COALESCE(SUM(
|
|
180
|
-
COALESCE(t.input_tokens, 0)
|
|
181
|
-
+ CASE
|
|
182
|
-
WHEN t.started_at >= ${Ve}
|
|
183
|
-
AND (
|
|
184
|
-
t.crewx_version IS NULL
|
|
185
|
-
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, ${Ke}) AS INTEGER) < ${Je})
|
|
187
|
-
)
|
|
188
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
189
|
-
ELSE 0
|
|
190
|
-
END
|
|
191
|
-
), 0)
|
|
192
|
-
+ COALESCE(SUM(t.output_tokens), 0)
|
|
193
|
-
) DESC
|
|
194
|
-
`).map(u=>({agentId:u.agent_id,workspaceId:u.workspace_id??null,totalTasks:u.total_tasks,unavailableTaskCount:u.unavailable_task_count,inputTokens:u.input_tokens,outputTokens:u.output_tokens,cachedInputTokens:u.cached_input_tokens,costUsd:u.cost_usd,totalTokens:u.input_tokens+u.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=ln(sql.raw("t.status")),a=Qn(sql.raw("t.metadata"));return o.db.all(r?sql`
|
|
112
|
+
`)}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,i=0,u=0;for(let d of r){if(!existsSync(d))continue;let c=W(d);try{let l=eq(a.thread_id,e),p=n?and(l,eq(a.workspace_id,n)):l,g=c.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(p).all();for(let _ of g)o.has(_.id)||(o.add(_.id),s+=_.input_tokens??0,i+=_.output_tokens??0,u+=_.cost_usd??0);}catch(l){throw new f("DB_ERROR","Failed to get thread token usage",l)}finally{c.close();}}return {inputTokens:s,outputTokens:i,costUsd:u}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],u=r?.projection==="activity-log";for(let d of o){if(!existsSync(d))continue;let c=W(d);try{let l=eq(a.thread_id,e),p=n?and(l,eq(a.workspace_id,n)):l,g=u?c.db.select({id:a.id,thread_id:a.thread_id,agent_id:a.agent_id,parent_task_id:a.parent_task_id,started_at:a.started_at,completed_at:a.completed_at}).from(a).where(p).orderBy(asc(a.started_at)).all():c.db.select().from(a).where(p).orderBy(asc(a.started_at)).all().map(be);for(let _ of g)s.has(_.id)||(s.add(_.id),i.push(_));}catch(l){throw new f("DB_ERROR","Failed to find tasks by thread",l)}finally{c.close();}}return i}parseWorkflowCardMetadata(e){if(!e)return {};try{let n=JSON.parse(e);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=W(n);try{e.push(...r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(a.started_at)).all().map(ta));}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:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),eq(a.workspace_id,e.workspaceId))).orderBy(desc(a.started_at),desc(a.id)).all();for(let s of o){let i=this.parseWorkflowCardMetadata(s.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return ta(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,i=n?eq(a.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(a.thread_id,e),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%'))),p=c.db.select({id:a.id,thread_id:a.thread_id,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(l,i):l).all();for(let m of p)u(m.thread_id,m);let g=and(isNull(a.thread_id),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%'))),_=c.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(g,i):g).all();for(let m of _){let w=this.extractThreadIdFromCommand(m.command);!w||!o.has(w)||u(w,m);}}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(a.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(inArray(a.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(inArray(a.status,s));let i=e.q??e.search;i&&r.push(like(a.prompt,`%${i}%`)),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt$1(a.started_at,e.to));let u=r.length>0?and(...r):void 0,d=n.db.select({count:sql`count(*)`}).from(a).where(u).get(),c=(e.sortDir??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at);return {rows:n.db.select().from(a).where(u).orderBy(c).limit(e.limit).offset(e.offset).all().map(be),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=To(sql.raw("t.model"),sql.raw("t.metadata")),i=mn(sql.raw("t.status")),u=ar(sql.raw("t.metadata")),d=sql`
|
|
113
|
+
COALESCE(t.input_tokens, 0)
|
|
114
|
+
+ CASE
|
|
115
|
+
WHEN t.started_at >= ${Ht}
|
|
116
|
+
AND (
|
|
117
|
+
t.crewx_version IS NULL
|
|
118
|
+
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
119
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${$t}) AS INTEGER) < ${Ut})
|
|
120
|
+
)
|
|
121
|
+
THEN COALESCE(t.cached_input_tokens, 0)
|
|
122
|
+
ELSE 0
|
|
123
|
+
END
|
|
124
|
+
`,c=r?sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n} AND t.workspace_id = ${r}`:sql`WHERE ${i} AND t.started_at >= ${e} AND t.started_at < ${n}`,l=o.db.all(sql`
|
|
125
|
+
SELECT
|
|
126
|
+
t.agent_id,
|
|
127
|
+
t.workspace_id,
|
|
128
|
+
${s} AS provider,
|
|
129
|
+
COUNT(*) AS total_tasks,
|
|
130
|
+
${u} AS unavailable_task_count,
|
|
131
|
+
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
132
|
+
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
133
|
+
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
134
|
+
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
135
|
+
FROM tasks t
|
|
136
|
+
${c}
|
|
137
|
+
GROUP BY t.agent_id, t.workspace_id, ${s}
|
|
138
|
+
`),p=new Map;for(let m of l){let w=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",k={provider:w,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,totalTokens:m.input_tokens+m.output_tokens,costUsd:m.cost_usd,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count},C=m.workspace_id??null,L=JSON.stringify([m.agent_id,C]),D=p.get(L);if(!D){p.set(L,{agentId:m.agent_id,workspaceId:C,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,costUsd:m.cost_usd,totalTokens:m.input_tokens+m.output_tokens,providers:[k]});continue}D.totalTasks+=m.total_tasks,D.unavailableTaskCount=(D.unavailableTaskCount??0)+m.unavailable_task_count,D.inputTokens+=m.input_tokens,D.outputTokens+=m.output_tokens,D.cachedInputTokens+=m.cached_input_tokens,D.costUsd+=m.cost_usd,D.totalTokens+=m.input_tokens+m.output_tokens;let E=D.providers.find(x=>x.provider===w);E?(E.inputTokens+=k.inputTokens,E.outputTokens+=k.outputTokens,E.cachedInputTokens+=k.cachedInputTokens,E.totalTokens+=k.totalTokens,E.costUsd+=k.costUsd,E.totalTasks+=k.totalTasks,E.unavailableTaskCount+=k.unavailableTaskCount):D.providers.push(k);}let g=[...p.values()];for(let m of g)m.providers.sort((w,k)=>w.provider===k.provider?0:w.provider==="unknown"?1:k.provider==="unknown"?-1:w.totalTokens!==k.totalTokens?k.totalTokens-w.totalTokens:w.provider<k.provider?-1:1);let _=(m,w)=>m===w?0:m<w?-1:1;return g.sort((m,w)=>{if(m.totalTokens!==w.totalTokens)return w.totalTokens-m.totalTokens;let k=_(m.agentId,w.agentId);return k!==0?k:m.workspaceId===w.workspaceId?0:m.workspaceId===null?1:w.workspaceId===null?-1:_(m.workspaceId,w.workspaceId)}),g}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=mn(sql.raw("t.status")),i=ar(sql.raw("t.metadata"));return o.db.all(r?sql`
|
|
195
139
|
SELECT
|
|
196
140
|
date(t.started_at) AS date,
|
|
197
141
|
t.agent_id,
|
|
198
|
-
${
|
|
142
|
+
${i} AS unavailable_task_count,
|
|
199
143
|
COALESCE(SUM(
|
|
200
144
|
COALESCE(t.input_tokens, 0)
|
|
201
145
|
+ CASE
|
|
202
|
-
WHEN t.started_at >= ${
|
|
146
|
+
WHEN t.started_at >= ${Ht}
|
|
203
147
|
AND (
|
|
204
148
|
t.crewx_version IS NULL
|
|
205
149
|
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, ${
|
|
150
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${$t}) AS INTEGER) < ${Ut})
|
|
207
151
|
)
|
|
208
152
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
209
153
|
ELSE 0
|
|
@@ -223,15 +167,15 @@ ${r.join(`
|
|
|
223
167
|
SELECT
|
|
224
168
|
date(t.started_at) AS date,
|
|
225
169
|
t.agent_id,
|
|
226
|
-
${
|
|
170
|
+
${i} AS unavailable_task_count,
|
|
227
171
|
COALESCE(SUM(
|
|
228
172
|
COALESCE(t.input_tokens, 0)
|
|
229
173
|
+ CASE
|
|
230
|
-
WHEN t.started_at >= ${
|
|
174
|
+
WHEN t.started_at >= ${Ht}
|
|
231
175
|
AND (
|
|
232
176
|
t.crewx_version IS NULL
|
|
233
177
|
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, ${
|
|
178
|
+
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${$t}) AS INTEGER) < ${Ut})
|
|
235
179
|
)
|
|
236
180
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
237
181
|
ELSE 0
|
|
@@ -246,111 +190,110 @@ ${r.join(`
|
|
|
246
190
|
AND t.started_at < ${n}
|
|
247
191
|
GROUP BY date(t.started_at), t.agent_id
|
|
248
192
|
ORDER BY date(t.started_at) ASC
|
|
249
|
-
`).map(
|
|
250
|
-
COALESCE(${
|
|
193
|
+
`).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(a).where(and(eq(a.id,e),eq(a.workspace_id,n))).limit(1).get();return o?be(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:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(and(eq(a.agent_id,e.agentId),eq(a.workspace_id,e.workspaceId),sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(a.started_at)).limit(1).get()??null}catch(r){throw new 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 i=this.openHandle(true);try{let u=new Date().toISOString(),d=r?and(eq(a.id,e),eq(a.status,"running"),eq(a.workspace_id,r)):and(eq(a.id,e),eq(a.status,"running")),c=i.db.select({metadata:a.metadata}).from(a).where(d).limit(1).get();if(!c)return;let l={status:o,error:n,completed_at:u};if(s){let p=ee(c.metadata);p.terminalReason=s,l.metadata=JSON.stringify(p);}i.db.update(a).set(l).where(d).run();}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to mark task failed",u)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let u=W(i);try{let d=n?and(like(a.prompt,`%${e}%`),eq(a.workspace_id,n)):like(a.prompt,`%${e}%`),c=u.db.select().from(a).where(d).orderBy(asc(a.started_at)).all();for(let l of c)o.has(l.id)||(o.add(l.id),s.push(be(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=To(),i=mn(a.status),u=ar(a.metadata),d=sql`
|
|
194
|
+
COALESCE(${a.input_tokens}, 0)
|
|
251
195
|
+ CASE
|
|
252
|
-
WHEN ${
|
|
196
|
+
WHEN ${a.started_at} >= ${Ht}
|
|
253
197
|
AND (
|
|
254
|
-
${
|
|
255
|
-
OR (${
|
|
256
|
-
OR (${
|
|
198
|
+
${a.crewx_version} IS NULL
|
|
199
|
+
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
200
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${$t}) AS INTEGER) < ${Ut})
|
|
257
201
|
)
|
|
258
|
-
THEN COALESCE(${
|
|
202
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
259
203
|
ELSE 0
|
|
260
204
|
END
|
|
261
|
-
`,c=r?sql`WHERE ${
|
|
205
|
+
`,c=r?sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return o.db.all(sql`
|
|
262
206
|
SELECT
|
|
263
207
|
${s} AS provider,
|
|
264
208
|
COUNT(*) AS total_tasks,
|
|
265
|
-
${
|
|
266
|
-
COALESCE(SUM(${
|
|
267
|
-
COALESCE(SUM(${
|
|
268
|
-
COALESCE(SUM(${
|
|
269
|
-
COALESCE(SUM(${
|
|
270
|
-
COALESCE(SUM(${
|
|
271
|
-
MAX(${
|
|
272
|
-
FROM ${
|
|
209
|
+
${u} AS unavailable_task_count,
|
|
210
|
+
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
211
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
212
|
+
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
213
|
+
COALESCE(SUM(${a.cost_usd}), 0) AS cost_usd,
|
|
214
|
+
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
215
|
+
MAX(${a.completed_at}) AS last_active_at
|
|
216
|
+
FROM ${a}
|
|
273
217
|
${c}
|
|
274
218
|
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=
|
|
277
|
-
COALESCE(${
|
|
219
|
+
ORDER BY (COALESCE(SUM(${d}), 0) + COALESCE(SUM(${a.output_tokens}), 0)) DESC
|
|
220
|
+
`).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=To(),i=mn(a.status),u=ar(a.metadata),d=sql`
|
|
221
|
+
COALESCE(${a.input_tokens}, 0)
|
|
278
222
|
+ CASE
|
|
279
|
-
WHEN ${
|
|
223
|
+
WHEN ${a.started_at} >= ${Ht}
|
|
280
224
|
AND (
|
|
281
|
-
${
|
|
282
|
-
OR (${
|
|
283
|
-
OR (${
|
|
225
|
+
${a.crewx_version} IS NULL
|
|
226
|
+
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
227
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${$t}) AS INTEGER) < ${Ut})
|
|
284
228
|
)
|
|
285
|
-
THEN COALESCE(${
|
|
229
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
286
230
|
ELSE 0
|
|
287
231
|
END
|
|
288
|
-
`,c=r?sql`WHERE ${
|
|
232
|
+
`,c=r?sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,l=o.db.all(sql`
|
|
289
233
|
SELECT
|
|
290
|
-
${
|
|
234
|
+
${a.model} AS model,
|
|
291
235
|
${s} AS provider,
|
|
292
236
|
COUNT(*) AS total_tasks,
|
|
293
|
-
${
|
|
294
|
-
COALESCE(SUM(${
|
|
295
|
-
COALESCE(SUM(${
|
|
296
|
-
COALESCE(SUM(${
|
|
297
|
-
COALESCE(SUM(${
|
|
298
|
-
COALESCE(SUM(${
|
|
299
|
-
MAX(${
|
|
300
|
-
FROM ${
|
|
237
|
+
${u} AS unavailable_task_count,
|
|
238
|
+
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
239
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens,
|
|
240
|
+
COALESCE(SUM(${a.cached_input_tokens}), 0) AS cached_input_tokens,
|
|
241
|
+
COALESCE(SUM(${a.cost_usd}), 0) AS cost_usd,
|
|
242
|
+
COALESCE(SUM(${a.duration_ms}), 0) AS active_duration_ms,
|
|
243
|
+
MAX(${a.completed_at}) AS last_active_at
|
|
244
|
+
FROM ${a}
|
|
301
245
|
${c}
|
|
302
|
-
GROUP BY ${
|
|
303
|
-
`),p=new Map;for(let g of l){let
|
|
246
|
+
GROUP BY ${a.model}, ${s}
|
|
247
|
+
`),p=new Map;for(let g of l){let _=Mr(g.model??""),m=JSON.stringify([g.provider,_]),w=p.get(m);w?(w.totalTasks+=g.total_tasks,w.unavailableTaskCount=(w.unavailableTaskCount??0)+g.unavailable_task_count,w.inputTokens+=g.input_tokens,w.outputTokens+=g.output_tokens,w.cachedInputTokens+=g.cached_input_tokens,w.costUsd+=g.cost_usd,w.totalTokens+=g.input_tokens+g.output_tokens,w.activeDurationMs+=g.active_duration_ms??0,g.last_active_at&&(!w.lastActiveAt||g.last_active_at>w.lastActiveAt)&&(w.lastActiveAt=g.last_active_at)):p.set(m,{model:_,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,_)=>_.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 ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return o.db.all(sql`
|
|
304
248
|
SELECT
|
|
305
|
-
${
|
|
306
|
-
${
|
|
307
|
-
${
|
|
308
|
-
${
|
|
309
|
-
${
|
|
310
|
-
${
|
|
311
|
-
FROM ${
|
|
249
|
+
${a.thread_id} AS thread_id,
|
|
250
|
+
${a.agent_id} AS agent_id,
|
|
251
|
+
${a.started_at} AS started_at,
|
|
252
|
+
${a.status} AS status,
|
|
253
|
+
${a.error} AS error,
|
|
254
|
+
${a.exit_code} AS exit_code
|
|
255
|
+
FROM ${a}
|
|
312
256
|
${s}
|
|
313
|
-
ORDER BY ${
|
|
314
|
-
`).map(
|
|
315
|
-
COALESCE(${
|
|
257
|
+
ORDER BY ${a.started_at} ASC
|
|
258
|
+
`).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`
|
|
259
|
+
COALESCE(${a.input_tokens}, 0)
|
|
316
260
|
+ CASE
|
|
317
|
-
WHEN ${
|
|
261
|
+
WHEN ${a.started_at} >= ${Ht}
|
|
318
262
|
AND (
|
|
319
|
-
${
|
|
320
|
-
OR (${
|
|
321
|
-
OR (${
|
|
263
|
+
${a.crewx_version} IS NULL
|
|
264
|
+
OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
|
|
265
|
+
OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${$t}) AS INTEGER) < ${Ut})
|
|
322
266
|
)
|
|
323
|
-
THEN COALESCE(${
|
|
267
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
324
268
|
ELSE 0
|
|
325
269
|
END
|
|
326
|
-
`,
|
|
270
|
+
`,i=mn(a.status),u=r?sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,d=o.db.all(sql`
|
|
327
271
|
SELECT
|
|
328
|
-
${
|
|
329
|
-
${
|
|
272
|
+
${a.caller_agent_id} AS caller_agent_id,
|
|
273
|
+
${a.agent_id} AS agent_id,
|
|
330
274
|
COUNT(*) AS task_count,
|
|
331
275
|
COALESCE(SUM(${s}), 0) AS input_tokens,
|
|
332
|
-
COALESCE(SUM(${
|
|
333
|
-
FROM ${
|
|
334
|
-
${
|
|
335
|
-
GROUP BY ${
|
|
336
|
-
ORDER BY task_count DESC, ${
|
|
337
|
-
LIMIT ${
|
|
338
|
-
`),c=
|
|
276
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens
|
|
277
|
+
FROM ${a}
|
|
278
|
+
${u}
|
|
279
|
+
GROUP BY ${a.caller_agent_id}, ${a.agent_id}
|
|
280
|
+
ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
|
|
281
|
+
LIMIT ${ko+1}
|
|
282
|
+
`),c=d.length>ko;return {edges:d.slice(0,ko).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(a.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(inArray(a.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(inArray(a.status,e.statuses)),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt$1(a.started_at,e.to));let o=r.length>0?and(...r):void 0,s=(e.order??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at),i={id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id,error:a.error,metadata:a.metadata};return (e.limit?n.db.select(i).from(a).where(o).orderBy(s).limit(e.limit).all():n.db.select(i).from(a).where(o).orderBy(s).all()).map(({error:d,metadata:c,...l})=>({...l,status:gt({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(a.thread_id),isNull(a.parent_task_id),isNull(a.caller_agent_id),or$1(isNull(a.platform),ne(a.platform,"workflow")),or$1(isNull(a.metadata),and(notLike(a.metadata,'%"kind":"workflow_card"%'),notLike(a.metadata,'%"kind":"workflow_ui_instance"%'))),or$1(isNull(a.metadata),notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(a.workspace_id,e.workspaceId)),e.from&&s.push(gte(a.started_at,e.from)),e.to&&s.push(lt$1(a.started_at,e.to));let i=n.db.select({id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id}).from(a).where(and(...s)).orderBy(asc(a.started_at),asc(a.id)).all(),u=new Map;for(let c of i){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 Xe=class{detach(e){}};h();function $o(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 wr(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var yr=class extends Xe{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=$o(n.timestamp),o=join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,o);let s=`=== TASK LOG: ${n.traceId} ===
|
|
339
283
|
CrewX Version: ${this.version}
|
|
340
284
|
Mode: ${n.mode}
|
|
341
285
|
Agent: ${n.agentRef}
|
|
342
|
-
Started: ${
|
|
286
|
+
Started: ${wr(n.timestamp)}
|
|
343
287
|
Message: ${n.message}
|
|
344
288
|
|
|
345
289
|
`;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=
|
|
290
|
+
`,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let o=wr(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
|
|
347
291
|
[${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 xa(t){let e=we.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 Lo(t){let e=xa(t);return createHash("sha256").update(e).digest("hex")}ot();lo();h();function Sc(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?Nc[e]:void 0;return s?s(r,o):Object.values(Zi).some(a=>a(r,o))}function er(t,e){let n=t.split(`
|
|
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 (
|
|
292
|
+
`;appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};h();h();var _t=new Map;function bn(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 jo(t){let e=bn(t);return createHash("sha256").update(e).digest("hex")}function Wo(t){let e=bn(t),n=_t.get(e);if(n!==void 0)return n;let r=e;try{let o=le.join(e,".git");if(!lstatSync(o).isFile())return _t.set(e,r),r;let s=/^gitdir:\s*(.+?)\s*$/i.exec(readFileSync(o,"utf8").trim());if(!s)return _t.set(e,r),r;let i=s[1],u=le.isAbsolute(i)?i:le.resolve(le.dirname(o),i),d=readFileSync(le.join(u,"commondir"),"utf8").trim();if(!d)return _t.set(e,r),r;let c=le.isAbsolute(d)?d:le.resolve(u,d);if(le.basename(c)!==".git"||!statSync(c).isDirectory())return _t.set(e,r),r;let l=bn(realpathSync.native(e)),p=bn(realpathSync.native(le.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return _t.set(e,r),r}ot();mo();vt();eo();ln();ho();Wn();var Xc=200,Yc=200;function Qc(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 Zc(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=Qc(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function ca(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function el(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function la(t){if(!t)return {};try{let e=JSON.parse(t);return el(e)?e:{}}catch{return {}}}function kn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var tl=new Set(["workflow","mcp"]),Ao=class extends Xe{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 _n({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?Wo(r):r,i=o?jo(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:_}=this.runnerIdentity,m=_??d.traceId,w=kn(d.metadata?.runEpoch),k=g?"runner":"caller",C=d.workspaceId??i,L=g?n.getTask(m):void 0,D=d.pid??null,E={...d.metadata??{provider:d.provider??"cli/claude"},ownership:k,...g&&D!==null?{providerPid:D}:{}},x=JSON.stringify(E);if(g&&L?.status==="running"&&L.pid!==null&&w===0){this.ignoredDetachedTaskIds.add(m);return}n.startTask({id:m,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:g?process.pid:D,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:m,runEpoch:w,ownership:k,...g?{providerPid:D}:{}})&&this.recordOwnedTaskRun({taskId:m,runEpoch:w,workspaceId:C,ownership:k}),tl.has(d.platform??"cli")||Gi(n,{taskId:m,runEpoch:w,onStopRequested:Oa=>this.handleStopRequested(n,Oa)})&&this.heartbeatTaskIds.add(m);}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],ca(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,kn(l)),cn(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,_=d.result??null,m=!1;if(d.error&&(!_||_.trim()==="")){let w=this.recoverPartialResult(c,d,l);w&&(_=w,m=!0);}n.finishTask({id:c,status:d.error?"failed":"success",result:_,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:m});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)cn(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+=ca(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>=Xc){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));},Yc);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"||kn(s.run_epoch)!==kn(r))return;let i=la(s.metadata),u=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=nr({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()||$e(c,u)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let o=kn(n.run_epoch),s=la(n.metadata??null),i=s.ownership==="runner"?"runner":"caller";if(i==="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=i==="runner"?u:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(d!==void 0){let c;try{c=await It(d,{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:ir(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&cn(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(i){this.recordAppendFailure(i,r,o);}let s=this.queues.get(e);s&&s.entries.length===0&&(s.timer&&clearTimeout(s.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let o=Zc(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();kt();Tt();ot();Et();rr();function lr(t){return {...t,status:gt(t)}}function il({metadata:t,...e}){return {...e,status:gt({...e,metadata:t})}}var Ft=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function Tn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function al(t){let n=Tn(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 pr=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:wt.id}).from(wt).where(eq(wt.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
350
293
|
SELECT 1 FROM tasks parent
|
|
351
294
|
WHERE parent.id = ${e}.parent_task_id
|
|
352
295
|
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
|
|
296
|
+
)`)}findAllThreads(e){let n=this.resolveDbPaths(),r=new Set,o=[];for(let s of n){if(!existsSync(s))continue;let i=W(s);try{let u=e?eq(T.workspace_id,e):void 0,d=i.db.select().from(T).where(u).orderBy(desc(T.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{i.close();}}return o}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let u=W(i);try{let d=or$1(inArray(T.id,e),inArray(T.title,e)),c=n?and(d,eq(T.workspace_id,n)):d,l=u.db.select().from(T).where(c).orderBy(desc(T.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 i=eq(T.id,e),u=n?and(i,eq(T.workspace_id,n)):i,d=s.db.select().from(T).where(u).limit(1).get()??void 0;if(d)return d}catch(i){throw new f("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(e,n){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=W(o);try{let i=eq(T.id,e),u=n?and(i,eq(T.workspace_id,n)):i;if(s.db.select({id:T.id}).from(T).where(u).limit(1).get())return !0}catch(i){throw new f("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),o=0,s=0,i=0,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
297
|
SELECT
|
|
355
298
|
count(*) AS cnt,
|
|
356
299
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -361,13 +304,13 @@ Message: ${n.message}
|
|
|
361
304
|
WHERE child.thread_id = ${e}
|
|
362
305
|
AND ${this.topLevelTaskPredicateSql()}
|
|
363
306
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
364
|
-
`);g&&(o+=g.cnt,s+=g.total_input,
|
|
307
|
+
`);g&&(o+=g.cnt,s+=g.total_input,i+=g.total_output,u+=g.total_cached,d+=g.total_cost);let _=p.db.all(sql`
|
|
365
308
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
366
309
|
WHERE child.thread_id = ${e}
|
|
367
310
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
368
311
|
AND ${this.topLevelTaskPredicateSql()}
|
|
369
312
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
370
|
-
`);for(let
|
|
313
|
+
`);for(let m of _)c.add(m.agent_id);}catch(g){throw new f("DB_ERROR","Failed to aggregate task stats",g)}finally{p.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:u,costUsd:d,agentIds:Array.from(c)}}findTopLevelTasks(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[];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
314
|
SELECT * FROM (
|
|
372
315
|
SELECT child.*,
|
|
373
316
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -378,13 +321,13 @@ Message: ${n.message}
|
|
|
378
321
|
) ranked
|
|
379
322
|
WHERE rn <= ${r}
|
|
380
323
|
ORDER BY started_at ASC
|
|
381
|
-
`):c=
|
|
324
|
+
`):c=d.db.all(sql`
|
|
382
325
|
SELECT child.* FROM tasks child
|
|
383
326
|
WHERE child.thread_id = ${e}
|
|
384
327
|
AND ${this.topLevelTaskPredicateSql()}
|
|
385
328
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
386
329
|
ORDER BY child.started_at ASC
|
|
387
|
-
`);for(let l of c)s.has(l.id)||(s.add(l.id),
|
|
330
|
+
`);for(let l of c)s.has(l.id)||(s.add(l.id),i.push(lr(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 i){let c=d.agent_id??"";u.has(c)||u.set(c,[]),u.get(c).push(d);}i=[];for(let d of u.values())d.sort((c,l)=>(l.started_at??"").localeCompare(c.started_at??"")),i.push(...d.slice(0,r));i.sort((d,c)=>(d.started_at??"").localeCompare(c.started_at??""));}return i}findAllTasks(e,n){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let u=W(i);try{let d=eq(a.thread_id,e),c=n?and(d,eq(a.workspace_id,n)):d,l=u.db.select().from(a).where(c).orderBy(asc(a.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(lr(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 i=W(s);try{let u=and(eq(a.id,n),eq(a.thread_id,e)),d=r?and(u,eq(a.workspace_id,r)):u,c=i.db.select().from(a).where(d).limit(1).get();if(!c)continue;let l=i.db.select().from(a).where(eq(a.parent_task_id,c.id)).orderBy(asc(a.started_at)).all().map(lr);return {task:lr(c),children:l}}catch(u){throw new f("DB_ERROR","Failed to find task by id",u)}finally{i.close();}}}batchFetchTasksQuery(e,n){return sql`
|
|
388
331
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
389
332
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
390
333
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -394,7 +337,7 @@ Message: ${n.message}
|
|
|
394
337
|
AND ${this.topLevelTaskPredicateSql()}
|
|
395
338
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
396
339
|
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
|
|
340
|
+
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=W(s);try{let u=i.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(il(d));}}catch(u){throw new f("DB_ERROR","Failed to batch fetch tasks",u)}finally{i.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(T.id,e),i=r?and(s,eq(T.workspace_id,r)):s;if(!o.db.select({id:T.id}).from(T).where(i).limit(1).get())return;o.db.update(T).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(eq(T.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:T.id,message_count:T.message_count}).from(T).where(eq(T.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(T).set(u).where(eq(T.id,e)).run();}else r.db.insert(T).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,i=o.db.select({id:T.id,platform:T.platform,workspace_id:T.workspace_id}).from(T).where(eq(T.id,e)).limit(1).get();if(i){s&&!i.workspace_id&&o.db.update(T).set({workspace_id:s}).where(eq(T.id,e)).run();return}let u=new Date().toISOString();o.db.insert(T).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:T.message_count}).from(T).where(eq(T.id,e)).limit(1).get()?.message_count===0;return u.run(sql`
|
|
398
341
|
UPDATE threads
|
|
399
342
|
SET first_message = COALESCE(first_message, ${n}),
|
|
400
343
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
@@ -402,11 +345,11 @@ Message: ${n.message}
|
|
|
402
345
|
message_count = message_count + 1,
|
|
403
346
|
updated_at = ${s}
|
|
404
347
|
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`
|
|
348
|
+
`),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(T).set({last_message:n,updated_at:s}).where(eq(T.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(T).set(o).where(eq(T.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 Ft("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(d=>d!=="priority"&&d!=="state"))return new Ft("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new Ft("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [i.priority,i.state])if(d!=null&&(typeof d!="string"||d.length===0))return new Ft("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(T.id,e),eq(T.workspace_id,r)):eq(T.id,e);return u.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(d).get();if(!l)return null;let p=Tn(l.metadata),g=p.threadTitle,_=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};i.priority===null?delete _.priority:i.priority!==void 0&&(_.priority=i.priority),i.state===null?delete _.state:i.state!==void 0&&(_.state=i.state),Object.keys(_).length>0?p.threadTitle=_:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,w=new Date().toISOString();c.update(T).set({metadata:m,updated_at:w}).where(d).run();let k=c.select({metadata:T.metadata}).from(T).where(d).get();if(!k)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let C=al(k.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(T.id,e),eq(T.workspace_id,n)):eq(T.id,e);return r.db.transaction(s=>{let i=s.select({pinned:T.pinned,metadata:T.metadata}).from(T).where(o).get();if(!i)return null;let u=i.pinned?0:1,d=Tn(i.metadata);if(u){let c=n?and(eq(T.pinned,1),eq(T.workspace_id,n)):eq(T.pinned,1),l=s.select({metadata:T.metadata}).from(T).where(c).all(),p=null;for(let g of l){let _=Tn(g.metadata);typeof _.pinOrder=="number"&&(p===null||_.pinOrder<p)&&(p=_.pinOrder);}d.pinOrder=p===null?0:p-1;}else delete d.pinOrder;return s.update(T).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 i=n?and(eq(T.id,e[s]),eq(T.workspace_id,n)):eq(T.id,e[s]),u=o.select({metadata:T.metadata}).from(T).where(i).get();if(!u)continue;let d=Tn(u.metadata);d.pinOrder=s+1,o.update(T).set({metadata:JSON.stringify(d)}).where(i).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(T.id,e),eq(T.workspace_id,n)):eq(T.id,e),s=r.db.select({starred:T.starred}).from(T).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(T).set({starred:i}).where(o).run(),{starred:!!i}}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 i=this.openHandle(true);try{let u=n?and(eq(T.id,e),eq(T.workspace_id,n)):eq(T.id,e);return i.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},g=p.overdrive??{},_=o?.defaultTurns??g.defaultTurns??3,m=o?.updatedBy??"ui",w=new Date().toISOString(),k,C,L,D;switch(r){case "enable-count":{let E=o?.turns??_,x=o?.consumeCurrent?Math.max(E-1,0):E;k=x>0?"count":"off",C=x,L=!0,D="count";break}case "enable-latch":{k="latch",C=0,L=!0,D="latch";break}case "disable":{k="off",C=0,L=!1;break}default:{let E=g.state??"off",x=typeof g.remaining=="number"?g.remaining:0;if(E==="count"&&x>0){let b=x-1;b<=0?(k="off",C=0):(k="count",C=b),L=!0,D="count";}else E==="latch"?(k="latch",C=0,L=!0,D="latch"):(k="off",C=0,L=!1);break}}return p.overdrive={state:k,remaining:C,defaultTurns:_,updatedAt:w,updatedBy:m},c.update(T).set({metadata:JSON.stringify(p),updated_at:w}).where(u).run(),{applied:L,appliedMode:D,state:k,remaining:C}},{behavior:"immediate"})}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to resolve overdrive",u)}finally{i.close();}}};h();it();kt();Tt();ot();h();var vo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function dl(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+=vo[o%62]);}for(;n.length<t;)n+=vo[randomBytes(1)[0]%62];return n}function wn(t){return `${t}_${dl(8)}`}function ma(t,e){let{createHash:n}=mt("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=vo[i%62];return `${t}_${s}`}Et();h();var ul=["urgent","high","medium","low"],cl=["investigating","in-progress","in-review","on-hold","done"],_a="custom:";var ll=new Set(ul),pl=new Set(cl);function bo(t){return typeof t=="string"&&ll.has(t)}function Oo(t){if(typeof t!="string")return false;if(pl.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(_a))return false;let e=t.slice(_a.length);return e.length>=1&&e.length<=20}function ka(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 xo(t){let e=ka(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return bo(r.priority)&&(o.priority=r.priority),Oo(r.state)&&(o.state=r.state),o}function Ta(t,e){let n=ka(t)??{},r={...xo(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)}rr();var _l="regeneration_replaced";var kl="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Tl="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Po=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;}},vn=class extends Po{},Do=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;}},wl=new Set(Es),yl=new Set(ys),El=new Set(Rs),Rl=new Set(Ss),Sl=50,ya=100,Ea=280,Ra=40,Il=new Set(Is),fr=["queued","running"];function No(t){return Il.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 En(t={}){let e=t.actor??t,n=e.actorType??"system";return wl.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 Al(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&&!bo(t.priority)&&B(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Oo(t.state)&&B(`invalid state: ${String(t.state)}`);}function vl(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??Sl;return (!Number.isInteger(e)||e<1||e>ya)&&B(`limit must be between 1 and ${ya}`),e}function Lo(t){typeof t!="string"&&B("text is required");let e=t.trim();return e.length===0&&B("text must not be empty"),e.length>Ea&&B(`text must be at most ${Ea} characters`),e}function Je(t,e){return N(t??"",e),t}function Mo(t){Rl.has(t)||B(`invalid highlight kind: ${String(t)}`);}function bl(t){El.has(t)||B(`invalid highlight source: ${String(t)}`);}function Ol(t){N(t.threadId,"threadId"),N(t.workspaceId,"workspaceId");let e=t.source??"manual";bl(e),Mo(t.kind);let n=Lo(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=Je(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=Je(r,"coversFromTaskId"),i=Je(o,"coversToTaskId"),u=t.sourceTaskId??s,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Je(u??void 0,"sourceTaskId"),Je(d??void 0,"detectorVersion"),Je(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:u,detectorVersion:d,contentFingerprint:c}}function xl(t,e){(!t||typeof t!="object")&&B(`candidates[${e}] is required`),Mo(t.kind);let n=Lo(t.text),r=Je(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Je(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Je(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||ma("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return N(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function Cl(t){Array.isArray(t)||B("candidates must be an array"),t.length>Ra&&B(`candidates must contain at most ${Ra} items`);let e=new Map;for(let[n,r]of t.entries()){let o=xl(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function An(t){let e=xo(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 Nl(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 Rn(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${q.seq}), 0)`}).from(q).where(eq(q.thread_id,e)).get()?.maxSeq??0}function Sn(t,e){return !!t.select({id:q.id}).from(q).where(eq(q.thread_id,e)).limit(1).get()}function ht(t,e){yl.has(e.type)||B(`invalid thread event type: ${String(e.type)}`);let n=wn("the");t.insert(q).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:Nl(e.payload),created_at:e.createdAt}).run();let r=t.select().from(q).where(eq(q.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function In(t,e,n,r,o){let s=An(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 hr(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 gr(t,e,n,r,o,s,i){let u=o==="thread.highlight.created"?hr(e):{before:i?hr({...e,...i,id:e.id}):void 0,after:hr(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:u})}function Pl(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:hr(e),...s??{}}})}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");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(T.id,n),s=r===void 0?o:r===null?and(o,isNull(T.workspace_id)):and(o,eq(T.workspace_id,r));return e.select().from(T).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from($).where(eq($.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:T.workspace_id}).from(T).where(eq(T.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?An(o):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Al(e);let n=En(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||Ce(`Thread ${e.threadId} not found`);let u=An(i),d=e.title!==void 0,c=d&&e.title!==u.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==u.priority,g=e.state!==void 0&&e.state!==u.state,_=c||p||g;if(!_&&!l)return u;let m=i.metadata;(p||g)&&(m=Ta(i.metadata,{priority:e.priority,state:e.state}));let w={};if(_&&(w.metadata=m,w.updated_at=r),c&&(w.title=e.title),d&&(w.title_locked=1),s.update(T).set(w).where(e.workspaceId===void 0?eq(T.id,e.threadId):e.workspaceId===null?and(eq(T.id,e.threadId),isNull(T.workspace_id)):and(eq(T.id,e.threadId),eq(T.workspace_id,e.workspaceId))).run(),!_){let L={...i,title_locked:1};return An(L)}let k=Rn(s,i.id)+1;Sn(s,i.id)||(In(s,i,n,r,k),k+=1),c&&(ht(s,{threadId:i.id,seq:k,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),k+=1),p&&(ht(s,{threadId:i.id,seq:k,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),k+=1),g&&ht(s,{threadId:i.id,seq:k,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let C={...i,title:c?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return An(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(${q.seq}), 0)`}).from(q).where(eq(q.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:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(and(eq(a.thread_id,e),eq(a.workspace_id,n),inArray(a.status,[...$i,"completed","done","error"]),or$1(isNull(a.parent_task_id),eq(a.parent_task_id,"")),sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(asc(a.started_at),asc(a.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(o){throw o instanceof 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 i=o.select().from($).where(and(eq($.thread_id,s.id),eq($.request_id,e.requestId))).orderBy(desc($.requested_at),desc($.id)).limit(1).get();if(i)return {run:i,created:!1};let u=o.select().from($).where(and(eq($.thread_id,s.id),inArray($.status,fr))).orderBy(asc($.requested_at),asc($.id)).limit(1).get();if(u)throw new Do(u);let d=e.runId??wn("thr");o.insert($).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($).where(eq($.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($).where(and(eq($.thread_id,e),eq($.request_id,r))).orderBy(desc($.requested_at),desc($.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 i=this.findRegenerationRun(s,e,n);if(i||Ce(`Highlight regeneration run ${e} not found`),No(i.status)||B(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update($).set({status:"running",started_at:r}).where(and(eq($.id,i.id),eq($.status,"queued"))).run();let u=s.select().from($).where(eq($.id,i.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`),No(s.status)||B(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update($).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq($.id,s.id),inArray($.status,fr))).run();let i=o.select().from($).where(eq($.id,s.id)).get();if(!i)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{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=kl){N(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update($).set({status:"failed",completed_at:n,error_code:e}).where(inArray($.status,fr)).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=Cl(e.candidates),r=En(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let u=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!u||u.thread_id!==e.threadId)&&Ce(`Highlight regeneration run ${e.runId} not found`),No(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(i,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=i.select().from(P).where(eq(P.thread_id,d.id)).orderBy(asc(P.created_at),asc(P.id)).all(),l=new Set(n.map(b=>b.contentFingerprint)),p=c.filter(b=>b.source==="auto"&&b.status==="active"&&b.revision===0&&!l.has(b.content_fingerprint??"")),g=c.filter(b=>b.source==="auto"&&b.status==="active").length,_=new Set(c.filter(b=>!p.includes(b)&&b.content_fingerprint).map(b=>b.content_fingerprint)),m=n.filter(b=>!_.has(b.contentFingerprint)),w=new Date().toISOString(),k=Rn(i,d.id)+1;Sn(i,d.id)||(In(i,d,r,w,k),k+=1);for(let b of p)i.delete(P).where(eq(P.id,b.id)).run(),Pl(i,b,r,w,k,{runId:e.runId,reason:_l}),k+=1;let C=0,L=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let b of m){let Q=wn("thl");i.insert(P).values({id:Q,thread_id:d.id,source:"auto",kind:b.kind,status:"active",text:b.text,covers_from_task_id:b.coversFromTaskId,covers_to_task_id:b.coversToTaskId,revision:0,created_at:w,updated_at:w,agent_id:L,source_task_id:b.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:b.contentFingerprint,dismissed_at:null}).run();let _e=i.select().from(P).where(eq(P.id,Q)).get();if(!_e)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");gr(i,_e,r,w,"thread.highlight.created",k),k+=1,C+=1;}let E=i.select().from(P).where(eq(P.thread_id,d.id)).all().filter(b=>b.source==="auto"&&b.status==="active").length;ht(i,{threadId:d.id,seq:k,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:w,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:E,deletedCount:p.length,createdCount:C}}),i.update($).set({status:"completed",started_at:u.started_at??w,completed_at:w,error_code:null,previous_auto_count:g,new_auto_count:E}).where(and(eq($.id,u.id),inArray($.status,fr))).run();let x=i.select().from($).where(eq($.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:E}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Tl});}catch{}throw i instanceof f?i:new f("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;N(o.threadId,"threadId"),N(o.workspaceId,"workspaceId");let s=vl(o);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let u=i.db.select({maxSeq:sql`COALESCE(MAX(${q.seq}), 0)`}).from(q).where(eq(q.thread_id,o.threadId)).get()?.maxSeq??0,d;o.beforeSeq!==void 0?d=i.db.select().from(q).where(and(eq(q.thread_id,o.threadId),lt$1(q.seq,o.beforeSeq))).orderBy(desc(q.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?d=i.db.select().from(q).where(and(eq(q.thread_id,o.threadId),sql`${q.seq} > ${o.afterSeq}`)).orderBy(asc(q.seq)).limit(s+1).all():d=i.db.select().from(q).where(eq(q.thread_id,o.threadId)).orderBy(desc(q.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=!!i.db.select({id:q.id}).from(q).where(and(eq(q.thread_id,o.threadId),lt$1(q.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{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=Ol(e),r=En(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);if(u||Ce(`Thread ${e.threadId} not found`),n.source==="auto"){let g=i.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??wn("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};i.insert(P).values(c).run();let l=i.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=Rn(i,u.id)+1;return Sn(i,u.id)||(In(i,u,r,o,p),p+=1),gr(i,l,r,o,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to create thread highlight",i)}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&&Mo(e.kind);let n=e.text===void 0?void 0:Lo(e.text),r=En(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);u||Ce(`Thread ${e.threadId} not found`);let d=i.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 vn(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new vn(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 _=c!==d.kind||l!==d.text||p!==d.covers_from_task_id||g!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&_?"manual":d.source;if(!(_||m!==d.source))return d;let k=d.revision+1;i.update(P).set({source:m,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:g,revision:k,updated_at:o}).where(and(eq(P.id,d.id),eq(P.revision,d.revision))).run();let C=i.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 L=Rn(i,u.id)+1;return Sn(i,u.id)||(In(i,u,r,o,L),L+=1),gr(i,C,r,o,"thread.highlight.updated",L,d),C},{behavior:"immediate"})}catch(i){throw i instanceof f?i:new f("DB_ERROR","Failed to update thread highlight",i)}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=En(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||Ce(`Thread ${e.threadId} not found`);let u=s.select().from(P).where(and(eq(P.id,e.highlightId),eq(P.thread_id,i.id))).limit(1).get();if(u||Ce(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new vn(i.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=Rn(s,i.id)+1;return Sn(s,i.id)||(In(s,i,n,r,l),l+=1),gr(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 i=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 i;let u=o.db.all(sql`
|
|
406
349
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
407
350
|
ORDER BY started_at ASC, id ASC
|
|
408
|
-
`),
|
|
351
|
+
`),d=new Map(u.map((g,_)=>[g.id,_])),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 i.filter(g=>{let _=d.get(g.covers_from_task_id),m=d.get(g.covers_to_task_id);if(_===void 0||m===void 0)return !1;let w=Math.min(_,m),k=Math.max(_,m);return !(c!==void 0&&(c<w||c>k)||l!==void 0&&k<l||p!==void 0&&w>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();it();kt();Tt();ot();Et();Nr();var J=class extends f{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Ia="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Bl(){let t=randomBytes(16),e="";for(let n of t)e+=Ia[n%Ia.length];return e.slice(0,12)}function Aa(){return `c_${Bl()}`}function jl(t){return typeof t=="string"&&xr.includes(t)}function Wl(t){return typeof t=="string"&&Cr.includes(t)}function Gt(t){if(!jl(t))throw new J("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function va(t){if(!Wl(t))throw new J("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function ba(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 zt(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 _r(t){if(typeof t!="string"||t.trim().length===0)throw new J("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function rt(t,e){return and(eq(I.code_group,t),or$1(isNull(I.workspace_id),eq(I.workspace_id,e)))}var kr=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(Gt(e),zt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(I).where(and(rt(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(Gt(e),zt(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(I).where(rt(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(Gt(n),zt(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)_r(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(rt(n,e.workspaceId)).all(),i=s.filter(_=>_.is_archived===0),u=new Set(s.map(_=>_.code)),d=new Set(i.map(_=>_.code)),c=e.codes.find(_=>!u.has(_));if(c)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(_=>!d.has(_)))throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let l=new Map(i.map(_=>[_.code,_])),p=e.codes.map(_=>{let m=l.get(_);if(!m)throw new J("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${_}`);return m}),g;for(let[_,m]of p.entries())m.sort_order!==_&&(g??=new Date().toISOString(),o.update(I).set({sort_order:_,updated_at:g}).where(and(eq(I.code_group,n),eq(I.code,m.code))).run());return o.select().from(I).where(rt(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(Gt(e),_r(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){zt(e.workspaceId);let n=ba(e.name);va(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:I.code}).from(I).where(and(rt("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 i=o.select({maxSortOrder:sql`max(${I.sort_order})`}).from(I).where(rt("THREAD_STATE",e.workspaceId)).get(),u=new Date().toISOString(),d=Aa();for(;o.select({code:I.code}).from(I).where(and(eq(I.code_group,"THREAD_STATE"),eq(I.code,d))).limit(1).get();)d=Aa();o.insert(I).values({code_group:"THREAD_STATE",code:d,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at: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(Gt(e.group),_r(e.code),zt(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:ba(e.name);e.color!==void 0&&va(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(rt(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 i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=n??null),e.color!==void 0&&(i.color=e.color),o.update(I).set(i).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(Gt(e),_r(n),zt(r),typeof o!="boolean")throw new J("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let u=i.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&&i.select({code:I.code}).from(I).where(and(rt(e,r),eq(I.is_archived,0),eq(I.code_name,u.code_name),ne(I.code,n))).limit(1).get())throw new J("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${u.code_name}`);i.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=i.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(i){throw i instanceof f?i:new f("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new J("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};vt();function Vl(t){return t.replace(/<crewx_thread_context[^>]*>[\s\S]*?<\/crewx_thread_context>/g,"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
409
352
|
`).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:
|
|
353
|
+
`).trim()}function Kl(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 Jl(t,e,n){if(!t||e==="failed"&&$e(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(`
|
|
354
|
+
`):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=Vl(r);}return r}var Tr=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new pr({dbPath:this.dbPath})}getThreadHistoryRepo(){return new mr({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r){let o=this.getThreadRepo(),s=o.findThreadById(e);if(s){if(s.platform!==n)throw new Error(`Thread '${e}' already exists with platform '${s.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return {created:false}}return o.ensureThread(e,n,r),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,o=this.getThreadRepo(),s=o.findThreadById(e),i=o.findTopLevelTasks(e,void 0,r),u=new Set(["queued","cancelled"]);i=i.filter(p=>(!p.status||!u.has(p.status))&&(!n?.currentTraceId||p.trace_id!==n.currentTraceId));let d=s?.platform??"cli",c=this.rowsToMessages(i),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 kr({dbPath:this.dbPath}),o=(s,i)=>{try{return r.resolve(s,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:o("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:o("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,o){let{firstMessage:s}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:s}}async saveAssistantMessage(e,n,r,o){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}normalizeStatus(e){if(e&&!["success","completed","done"].includes(e)){if(["failed","error"].includes(e))return "failed";if(e==="running")return "running"}}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(o=>typeof o.text=="string"&&o.text.length>0).map(o=>({id:o.id,text:o.text,kind:o.kind,source:o.source,coversFromTaskId:o.covers_from_task_id,coversToTaskId:o.covers_to_task_id,createdAt:o.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let o=this.normalizeStatus(r.status),s=Kl(r.metadata),i=Jl(r.result,o??r.status??null,s);if(i||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(`
|
|
355
|
+
`)[0].slice(0,200)),n.push({id:`${r.id}-assistant`,text:i,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:u});}}return n}};var Ho=class extends Xe{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Tr(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{Ho as ConversationPlugin,yr as FileLoggerPlugin,Ao as SqliteTracingPlugin};
|