@crewx/sdk 0.9.0-rc.105 → 0.9.0-rc.107
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 +205 -248
- package/dist/esm/plugins/index.js +150 -210
- package/dist/esm/repository/index.js +116 -175
- package/dist/facade/Crewx.d.ts +2 -0
- package/dist/index.browser.d.ts +2 -0
- package/dist/index.browser.js +4 -4
- package/dist/index.d.ts +7 -3
- package/dist/index.js +205 -248
- package/dist/layout/types.d.ts +1 -0
- package/dist/mcp-app/apps-context.d.ts +5 -0
- package/dist/mcp-app/index.d.ts +3 -1
- package/dist/mcp-app/projection.d.ts +1 -0
- package/dist/plugins/index.js +150 -210
- package/dist/prompt/tag-names.d.ts +2 -0
- package/dist/repository/index.d.ts +1 -1
- package/dist/repository/index.js +116 -175
- package/dist/repository/task.repository.d.ts +11 -0
- package/package.json +1 -1
- package/templates/agents/default.yaml +3 -0
|
@@ -1,62 +1,64 @@
|
|
|
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
|
|
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 Jo,{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 Ca=Object.defineProperty;var _t=(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 Na=(t,e)=>{for(var n in e)Ca(t,n,{get:e[n],enumerable:true});};var La,Ma,R,h=v(()=>{La=()=>fileURLToPath(import.meta.url),Ma=()=>le__default.dirname(La()),R=Ma();});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 Vo(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 za(t,e){let n=Vo(t),r=Vo(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)&&za(t,join(Jo.homedir(),".crewx","crewx.db")))throw new Error(`${Ga}: ${t}. Set CREWX_DB or CREWX_TRACES_DB to an isolated temporary path or :memory:.`);return t}var Ga,ke,it=v(()=>{h();Ga="[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(Jo.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=_t("better-sqlite3"),{drizzle:o}=_t("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 = ${Ka}`),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 Ka,Tt=v(()=>{h();it();Ka=32*1024*1024;});function xn(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Xa(t,e){if(e>0||!xn(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(Ja))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function Qa(t,e,n){if(!xn(t,"__drizzle_migrations")||!xn(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=Ya[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 Za(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 ed(t,e){let{sql:n}=_t("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 nd(t,e,n,r){let s=JSON.parse(readFileSync(le__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===td);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(!xn(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
2
|
SELECT count(*) AS count
|
|
3
3
|
FROM tasks
|
|
4
4
|
WHERE status IN ('success', 'failed')
|
|
5
5
|
AND (stop_requested_at IS NOT NULL OR stop_requested_epoch IS NOT NULL)
|
|
6
|
-
`);return {hash:u,affectedRows:l?.count??0}}function
|
|
6
|
+
`);return {hash:u,affectedRows:l?.count??0}}function rd(t){let{migrate:e}=_t("drizzle-orm/better-sqlite3/migrator"),{sql:n}=_t("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:
|
|
7
7
|
${r.join(`
|
|
8
|
-
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;s?.cnt&&(a=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Ka(t,a),s?.cnt&&(Qa(t,o),Ya(t,o,n),Xa(t,o,n));let u=ed(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let c=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(c>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${c} migration${c>1?"s":""} applied).`);}u&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(p=>p.hash===u.hash)&&console.error(`[crewx] Task stop-marker cleanup (${u.affectedRows} success/failed row(s) affected).`);}function Ne(t,e){Vo.has(e)||(td(t),Vo.add(e));}var Vo,Va,Ja,Za,yt=v(()=>{h();Vo=new Set,Va={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT"};Ja={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"},"0024_storage_metadata":{prompt:"TEXT",rendered_prompt:"TEXT",result:"TEXT",input_tokens:"INTEGER DEFAULT 0",output_tokens:"INTEGER DEFAULT 0",cost_usd:"REAL DEFAULT 0"}};Za="0027_task_stop_scope_cleanup";});var Et,yr=v(()=>{h();Et=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),starred:integer("starred").notNull().default(0)});});var i,Wt=v(()=>{h();i=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),heartbeat_at:text("heartbeat_at"),stop_requested_at:text("stop_requested_at"),stop_requested_epoch:integer("stop_requested_epoch"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),cwd:text("cwd"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},t=>({log_storage_check:check("tasks_log_storage_ck",sql`${t.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:index("idx_tasks_status").on(t.status),idx_tasks_started_at:index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(t.workspace_id,t.started_at)}));});var De,Xo=v(()=>{h();Wt();De=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>i.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},t=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var ld,pd,_,Nn=v(()=>{h();yr();ld="json_extract(metadata, '$.threadTitle.state')",pd="json_extract(metadata, '$.threadTitle.priority')",_=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>Et.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_title:index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(t.workspace_id,sql.raw(ld)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(pd))}));});var hd,Zo=v(()=>{h();Wt();hd=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>hd.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},t=>({idx_spans_task_id:index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var es=v(()=>{h();Wt();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},t=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(t.timestamp)}));});var ns=v(()=>{h();Nn();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:unique().on(t.thread_id,t.seq)}));});var os=v(()=>{h();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},t=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(t.partition_key)}));});var as=v(()=>{h();sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var ds=v(()=>{h();sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},t=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var cs=v(()=>{h();sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},t=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(t.workspace_id,sql`${t.created_at} DESC`)})),sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},t=>({pk:primaryKey({columns:[t.notification_id,t.user_id]})}));});var ps=v(()=>{h();sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var fs=v(()=>{h();sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),app_id:text("app_id"),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({idCheck:check("ui_instances_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${t.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:check("ui_instances_app_id_ck",sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${t.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(sql`${t.status} = 'active'`)}));});var hs=v(()=>{h();sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},t=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${t.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${t.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${t.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
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),Xa(t,i),s?.cnt&&(ed(t,o),Za(t,o,n),Qa(t,o,n));let u=nd(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){Xo.has(e)||(rd(t),Xo.add(e));}var Xo,Ja,Ya,td,wt=v(()=>{h();Xo=new Set,Ja={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"};Ya={"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"}};td="0027_task_stop_scope_cleanup";});var yt,Sr=v(()=>{h();yt=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,Kt=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,Zo=v(()=>{h();Kt();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 fd,gd,T,Ln=v(()=>{h();Sr();fd="json_extract(metadata, '$.threadTitle.state')",gd="json_extract(metadata, '$.threadTitle.priority')",T=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>yt.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(fd)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(gd))}));});var _d,ns=v(()=>{h();Kt();_d=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(()=>_d.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 rs=v(()=>{h();Kt();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 ss=v(()=>{h();Ln();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 as=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 cs=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 ls=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 fs=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 hs=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 ms=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 ks=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`(
|
|
9
9
|
(${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
|
|
10
10
|
OR
|
|
11
11
|
(${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
|
|
12
|
-
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var _s,ks=v(()=>{h();_s=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},t=>({idCheck:check("projects_id_ck",sql`${t.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${t.stage_index} >= 1`)})),sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>_s.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idCheck:check("project_criteria_id_ck",sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>_s.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},t=>({idCheck:check("project_events_id_ck",sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var Or,br,I,xr=v(()=>{h();Or=["THREAD_STATE","THREAD_PRIORITY"],br=["gray","blue","violet","green","amber","orange","red","pink"],I=sqliteTable("common_codes",{code_group:text("code_group").notNull(),code:text("code").notNull(),code_name:text("code_name"),color:text("color").notNull().default("gray"),sort_order:integer("sort_order").notNull(),workspace_id:text("workspace_id"),is_builtin:integer("is_builtin").notNull().default(0),is_archived:integer("is_archived").notNull().default(0),metadata:text("metadata"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({pk:primaryKey({columns:[t.code_group,t.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${t.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var Ts,ws,ys,Es,Rs,U,H,P,Ss=v(()=>{h();Nn();Ts=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],ws=["user","agent","system"],ys=["auto","manual"],Es=["decision","judgment","issue","result","pivot"],Rs=["queued","running","completed","failed"],U=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},t=>({typeCheck:check("thread_events_type_ck",sql`${t.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:check("thread_events_actor_type_ck",sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),H=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),request_id:text("request_id").notNull(),status:text("status").notNull(),detector_version:text("detector_version").notNull(),requested_at:text("requested_at").notNull(),started_at:text("started_at"),completed_at:text("completed_at"),error_code:text("error_code"),previous_auto_count:integer("previous_auto_count"),new_auto_count:integer("new_auto_count")},t=>({statusCheck:check("thread_highlight_runs_status_ck",sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:check("thread_highlight_runs_counts_ck",sql`(${t.previous_auto_count} IS NULL OR ${t.previous_auto_count} >= 0) AND (${t.new_auto_count} IS NULL OR ${t.new_auto_count} >= 0)`),threadRequestUnique:uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),P=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},t=>({sourceCheck:check("thread_highlights_source_ck",sql`${t.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${t.source} = 'manual' OR (${t.source} = 'auto' AND ${t.source_task_id} IS NOT NULL AND ${t.detector_version} IS NOT NULL AND ${t.content_fingerprint} IS NOT NULL AND length(${t.source_task_id}) > 0 AND length(${t.detector_version}) > 0 AND length(${t.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(sql`${t.source} = 'auto'`)}));});var As=v(()=>{h();sqliteTable("storage_metadata",{source_kind:text("source_kind").notNull(),source_id:text("source_id").notNull(),utc_ts:text("utc_ts"),bytes:integer("bytes").notNull()},t=>({pk:primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteTable("storage_metadata_state",{unit:text("unit").primaryKey().notNull(),cursor_rowid:integer("cursor_rowid").notNull().default(0),end_rowid:integer("end_rowid"),complete:integer("complete").notNull().default(0),updated_at:text("updated_at").notNull()});});var St=v(()=>{h();yr();Wt();Xo();Nn();Zo();es();ns();os();as();ds();cs();ps();fs();hs();ks();xr();Ss();As();});var It,Nr,vs,Pr=v(()=>{h();It={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5":{input:5,cachedInput:.5,output:25},"claude-opus-4-8":{input:5,cachedInput:.5,output:25},"claude-opus-4-7":{input:5,cachedInput:.5,output:25},"claude-opus-4-6":{input:5,cachedInput:.5,output:25},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-5.6-sol":{input:5,cachedInput:.5,output:30},"gpt-5.6-terra":{input:2,cachedInput:.2,output:12},"gpt-5.6-luna":{input:.2,cachedInput:.02,output:1.2},"gpt-5.5":{input:5,cachedInput:.5,output:30},"gpt-5.4":{input:2.5,cachedInput:.25,output:15},"gpt-5.4-mini":{input:.75,cachedInput:.075,output:4.5},"gpt-5.3-codex":{input:1.75,cachedInput:.175,output:14},"gpt-5-mini":{input:.4,cachedInput:.1,output:1.6},"gpt-4.1":{input:2,cachedInput:.5,output:8},"gpt-4o":{input:2.5,cachedInput:1.25,output:10},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"gemini-3.7-flash":{input:1.5,cachedInput:.15,output:7.5},"gemini-3.6-flash":{input:1.5,cachedInput:.15,output:7.5},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},Nr=new Set(["gpt-5.3-codex-spark"]),vs=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7[1m]","claude-opus-4-8[1m]","claude-opus-5","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","gemini-3.1-pro","gemini-3.5-flash","gemini-3.6-flash","gemini-3.7-flash","gpt-5.3-codex","gpt-5.3-codex-spark","gpt-5.4","gpt-5.4-mini","gpt-5.5","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra","gpt-oss-120b","grok-4.5","grok-4.6"]);});function Dr(t){let e=t.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let n=e.lastIndexOf("/");return n>=0&&(e=e.slice(n+1)),e=e.replace(/-\d{8}$/,""),e}function jd(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Kt;let e=Dr(t),n=Bd[e];if(n)return Un[n]??It[n]??Kt;if(Un[e])return Un[e];if(It[e])return It[e];if(Nr.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Kt;if(vs.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Kt;let r={...It,...Un};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Kt}function Wd(t,e,n,r=0,o){let s=jd(n),a=Math.min(r,t),d=(t-a)*s.input/1e6,c=a*s.cachedInput/1e6,l=e*s.output/1e6;return d+c+l}function Os(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:Wd(e??0,n??0,o,r??0)}var Bd,Kt,Un,qn=v(()=>{h();Pr();Pr();Bd={opus:"claude-opus-4-8",sonnet:"claude-sonnet-4-6",haiku:"claude-haiku-4-5","codex-mini":"gpt-5.3-codex",codex:"gpt-5.3-codex"},Kt={input:0,cachedInput:0,output:0},Un={};});function Ns(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function xs(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Ps(t){return Number.isSafeInteger(t)&&t>0}function Jd(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:Ns(c)});return}let o="",s="",a=false,u,d=setTimeout(()=>{try{r.kill();}catch{}u({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${bs}ms`)});},bs);u=c=>{a||(a=true,clearTimeout(d),n(c));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",c=>{o+=String(c);}),r.stderr?.on("data",c=>{s+=String(c);}),r.once("error",c=>{u({status:null,stdout:o,stderr:s,error:c});}),r.once("close",c=>{u({status:c,stdout:o,stderr:s});});})}async function Ds(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Jd(t,e)}function Xd(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Yd(){return new Promise(t=>{setImmediate(t);})}function lt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return xs(n)==="ESRCH"?"not_found":xs(n)==="EPERM"?"alive":"unknown"}}function Qd(t,e){let n=lt(-t,e),r=lt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function Ls(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??Vd),a=Date.now()+o,u,d=o===0,c=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(l=>{u=setTimeout(l,o);});c.then(()=>{d=true;});try{for(await Yd();;){let l=Qd(t,e);if(l==="not_found")return l;let p=a-Date.now();if(d||p<=0)return l;await Promise.race([c,Xd(Math.min(s,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function Cs(t,e,n,r,o){let s=await Ls(t,e,o.hardConfirmMs??Kd,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:s==="alive"?{status:"failed",pid:t,method:r,error:"Process is still running after termination attempt"}:{status:"failed",pid:t,method:r,error:"Unable to verify process termination"}}async function Fn(t,e,n={}){if(!Ps(t))return "unknown";let r=n.platform??process.platform,o=r==="win32"?"powershell.exe":"ps",s=r==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(t),"-o","command="],a;try{a=await Ds(o,s,n);}catch{return "unknown"}if(a.error||a.status!==0)return "unknown";let u=a.stdout.trim();if(!u)return "not_found";let d=r==="win32"?u.toLowerCase():u;return e.filter(l=>l.trim().length>0).some(l=>{let p=r==="win32"?l.toLowerCase():l;return d.includes(p)})?"owned":"not_owned"}async function vt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",o=g=>({status:"failed",pid:t,method:r,error:g});if(!Ps(t))return o("Invalid process ID");let s=e.kill??process.kill,a=lt(t,s);if(a==="not_found")return {status:"not_found",pid:t,method:r};if(a!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let g;try{g=await Ds("taskkill",["/PID",String(t),"/T","/F"],e);}catch(T){g={status:null,stdout:"",stderr:"",error:Ns(T)};}let m=lt(t,s);return m==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(m==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let u,d=e.signal??"SIGKILL";try{s(-t,d);}catch(g){u=g;}if(d==="SIGKILL")return Cs(t,s,u,r,e);if(await Ls(t,s,e.graceMs??zd,e)==="not_found")return u?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{s(-t,"SIGKILL");}catch(g){l=g;}let p=await Cs(t,s,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?u?p:{status:"terminated",pid:t,method:r}:o(p.error??"Process termination failed")}var bs,At,zd,Vd,Kd,Bn=v(()=>{h();bs=3e3,At="SIGINT",zd=2e3,Vd=25,Kd=100;});function qs(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new f("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new f("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function $s(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new f("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>qs(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Fs(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new f("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new f("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new f("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Us(t){return {taskId:t.id,source:Fs(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function ou(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var jn,Bs=v(()=>{h();dt();wt();yt();it();St();jn=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?at(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new f("NOT_FOUND","Database not found");let r=W(n);if(e)try{Ne(r.db,n);}catch(o){throw r.close(),o}return r}findStateRow(e,n){return e.db.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(eq(i.id,n)).limit(1).get()}findStateRowInTransaction(e,n){return e.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(eq(i.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new f("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((s,a)=>qs(s,a));if(r.length===0){let s=this.getLogState(e);if(!s)throw new f("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(a=>{let u=this.requireStateRowInTransaction(a,e),d=Fs(u);if(d==="blob"){let g=$s(e,u.logs);if(a.update(i).set({logs:JSON.stringify([...g,...r]),log_revision:sql`${i.log_revision} + 1`}).where(eq(i.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:u.last_log_seq}}let c=u.last_log_seq+1,l=u.last_log_seq+r.length;if(a.insert(De).values(r.map((g,m)=>({task_id:e,seq:c+m,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(i).set({last_log_seq:l,log_revision:sql`${i.log_revision} + 1`}).where(eq(i.id,e)).run().changes!==1)throw new f("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Us(r):void 0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return ou(n),this.readLogsInternal(e,n)}readTail(e,n){return this.readLogsTail(e,n)}readLogsInternal(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let a=Us(s);if(a.source==="blob"){let l=$s(e,s.logs);return {...a,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=o.select({seq:De.seq,timestamp:De.timestamp,level:De.level,message:De.message}).from(De).where(eq(De.task_id,e)).orderBy(n===void 0?asc(De.seq):desc(De.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({timestamp:l,level:p,message:g})=>({timestamp:l,level:p,message:g}));return n!==void 0&&c.reverse(),{...a,entries:c}},{behavior:"deferred"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var js=v(()=>{h();});var ne,Xt=v(()=>{h();ne=class extends Error{constructor(n,r,o){super(n);this.providerStr=r;this.name="ProviderError",this.code=o?.code??"UNKNOWN",this.kind=o?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=o?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};});var Ge,Lr=v(()=>{h();Xt();Ge=class extends ne{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function $e(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function Ue(t,e,n){let r=e.match(/@(\S+)/);return {timestamp:t,type:"agent_call",targetAgent:r?.[1]?.replace(/["']/g,""),toolInput:e,...typeof n=="string"&&n.length>0?{toolUseId:n}:{}}}var Ot=v(()=>{h();});function au(t){let e=du(t),n=e.map((s,a)=>({line:s,index:a})).filter(({line:s})=>cu(s.value)),r=uu(e);return {result:n.length===1&&n[0].index===r?lu(n[0].line.value):null,resultPreview:gu(e,n),hasReservedLine:n.length>0}}function ze(t,e){let n=au(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function du(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
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 ws,ys=v(()=>{h();ws=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(()=>ws.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(()=>ws.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 Cr,Nr,I,Pr=v(()=>{h();Cr=["THREAD_STATE","THREAD_PRIORITY"],Nr=["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 Es,Rs,Ss,Is,As,q,$,P,vs=v(()=>{h();Ln();Es=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Rs=["user","agent","system"],Ss=["auto","manual"],Is=["decision","judgment","issue","result","pivot"],As=["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 Os=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 Rt=v(()=>{h();Sr();Kt();Zo();Ln();ns();rs();ss();as();cs();ls();fs();hs();ms();ks();ys();Pr();vs();Os();});var St,Lr,xs,Mr=v(()=>{h();St={"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}},Lr=new Set(["gpt-5.3-codex-spark"]),xs=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 Hr(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 Gd(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Qt;let e=Hr(t),n=Wd[e];if(n)return Bn[n]??St[n]??Qt;if(Bn[e])return Bn[e];if(St[e])return St[e];if(Lr.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Qt;if(xs.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Qt;let r={...St,...Bn};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Qt}function zd(t,e,n,r=0,o){let s=Gd(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 Cs(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:zd(e??0,n??0,o,r??0)}var Wd,Qt,Bn,jn=v(()=>{h();Mr();Mr();Wd={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"},Qt={input:0,cachedInput:0,output:0},Bn={};});function Ls(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Ps(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Ms(t){return Number.isSafeInteger(t)&&t>0}function Yd(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:Ls(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 ${Ns}ms`)});},Ns);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 Hs(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Yd(t,e)}function Qd(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Zd(){return new Promise(t=>{setImmediate(t);})}function ut(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Ps(n)==="ESRCH"?"not_found":Ps(n)==="EPERM"?"alive":"unknown"}}function eu(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 $s(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??Jd),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 Zd();;){let l=eu(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,Qd(Math.min(s,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function Ds(t,e,n,r,o){let s=await $s(t,e,o.hardConfirmMs??Xd,{...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 Wn(t,e,n={}){if(!Ms(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 Hs(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 At(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(!Ms(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 Hs("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){g={status:null,stdout:"",stderr:"",error:Ls(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 Ds(t,s,u,r,e);if(await $s(t,s,e.graceMs??Kd,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 Ds(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 Ns,It,Kd,Jd,Xd,Gn=v(()=>{h();Ns=3e3,It="SIGINT",Kd=2e3,Jd=25,Xd=100;});function js(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 Fs(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)=>js(r,o))}catch(r){throw r instanceof f?new f("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Ws(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 Bs(t){return {taskId:t.id,source:Ws(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function iu(t){if(!Number.isInteger(t)||t<0)throw new f("VALIDATION","Task log tail limit must be a non-negative integer")}var zn,Gs=v(()=>{h();it();Tt();wt();ot();Rt();zn=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)=>js(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=Ws(u);if(d==="blob"){let g=Fs(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?Bs(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 iu(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=Bs(s);if(i.source==="blob"){let l=Fs(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 zs=v(()=>{h();});var Z,vt=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,$r=v(()=>{h();vt();ze=class extends Z{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function au(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?hu[e]:void 0;return s?s(r,o):Object.values(Ks).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=>au(r,e))}function we(t){return typeof t=="object"&&t!==null}function Vs(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 du(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Vs(t,e)}function uu(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 cu(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 lu(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||we(t.part)||e==="result"&&typeof t.result=="string")}function pu(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?we(t.data):e==="result"?typeof t.result=="string":false}function fu(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 gu(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 Ks,hu,bt=v(()=>{h();Ks={claude:Vs,codex:uu,opencode:cu,copilot:pu,gemini:fu},hu={...Ks,claude:du,opencode:lu,grok:gu,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 Ot=v(()=>{h();});function ku(t){let e=Tu(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>yu(s.value)),r=wu(e);return {result:n.length===1&&n[0].index===r?Eu(n[0].line.value):null,resultPreview:Iu(e,n),hasReservedLine:n.length>0}}function Ve(t,e){let n=ku(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function Tu(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
13
14
|
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
14
15
|
`?`\r
|
|
15
|
-
`:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function uu(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function cu(t){return t.trimStart().startsWith(su)}function lu(t){let e=t.trim();if(!e.startsWith(Ws)||!e.endsWith("]]"))return null;let n=e.slice(Ws.length,-2);if(!n)return null;try{return pu(JSON.parse(n))}catch{return null}}function pu(t){return fu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function fu(t){if(!hu(t)||Object.keys(t).some(r=>!iu.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?Gs(t.taskId)&&Gs(t.agentId):t.isError===true}function gu(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function Gs(t){return typeof t=="string"&&t.trim().length>0}function hu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ws,su,iu,Yt=v(()=>{h();Ws="[[crewx:delegation-result ",su="[[crewx:delegation-result",iu=new Set(["schema","taskId","agentId","isError"]);});function qe(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var bt=v(()=>{h();});var zs,Wn,Mr,Gn=v(()=>{h();zs=["none","minimal","low","medium","high","xhigh","max","ultra"],Wn={claude:["low","medium","high","xhigh","max"],codex:["minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},Mr={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship",recommended:true},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4-mini",name:"GPT-5.4 Mini",contextWindowTokens:4e5,tier:"speed"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",contextWindowTokens:4e5,tier:"flagship"},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",contextWindowTokens:128e3,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-6-astra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"gpt-5.5",name:"GPT-5.5",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.4",name:"GPT-5.4",contextWindowTokens:105e4,tier:"flagship"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-6-thinking",name:"Claude Opus 4.6 Thinking",contextWindowTokens:1e6,tier:"flagship"},{id:"gpt-oss-120b",name:"GPT-OSS 120B",contextWindowTokens:128e3,tier:"balanced"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}},Object.fromEntries(Object.entries(Mr).map(([t,e])=>[t,e.models]));});function Hr(t){return _u[t]??t}function Tu(t){return ku.get(t)??t}function $r(t){if(!t)return {};let e=yu.get(t);return e?{...e}:{model:t}}function Ur(t,e){return t==="antigravity"||t==="cli/antigravity"?$r(e):e===void 0?{}:{model:Tu(e)}}var mu,_u,ku,wu,yu,Qt=v(()=>{h();mu=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],_u={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};ku=new Map(mu.map(({baseModelId:t,catalogModelId:e})=>[t,e]));wu=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],yu=new Map(wu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Ru(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function nt(t){return zn(t).models}function zn(t){return Eu[t]??Mr[t]??Ru()}function Zt(t,e){let n=zn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Ur(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Vs(t){return zn(t).modelOverrides}function Ks(){return nt("claude")}function Js(){return nt("codex")}function Xs(){return nt("copilot")}function Ys(){return nt("antigravity")}var Eu,pt=v(()=>{h();Gn();qn();Qt();Eu={};});function Qs(t){return Su[t]??t}var Su,Zs=v(()=>{h();pt();Qt();Su={auto:"default"};});function Vn(t,e){return (Wn[t]??[]).includes(e)}function rt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Iu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function ei(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["--sandbox","workspace-write"];default:return []}}function ti(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function ni(t){return !t||!Vn("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function ri(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Qs(t);return e.has(n)?["--permission-mode",n]:[]}function oi(t){return t?Vn("claude",t)?["--effort",t]:[]:[]}function si(t){return t==="default"?[]:t&&Au.has(t)?["--permission-mode",t]:[]}function ii(t){return t===true?["--always-approve"]:[]}function ai(t,e=n=>console.warn(n)){return t===void 0?[]:t==="workspace"||t==="read-only"||t==="off"?["--sandbox",t]:(e(`[grok] Invalid sandbox value ${JSON.stringify(t)}; using workspace.`),["--sandbox","workspace"])}function di(t){return t?Vn("grok",t)?["--effort",t]:[]:[]}function ui(t){if(!t)return [];switch(Hr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function ci(t){return t?Vn("antigravity",t)?["--effort",t]:[]:[]}var Iu,Au,en=v(()=>{h();Zs();Qt();Gn();Iu=new Set(zs);Au=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function vu(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,a=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:a}}function Ou(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),a="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,u="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=a!==void 0?a:u??0;return {inputTokens:a!==void 0?r+a:r,outputTokens:o,cachedInputTokens:d}}function bu(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0),s=n.cache,a=s?Number(s.read??0):0;return {inputTokens:r+a,outputTokens:o,cachedInputTokens:a}}function li(t){let e=new Map,n;for(let s of t.split(`
|
|
16
|
-
`))if(s.trim())try{let
|
|
17
|
-
`))if(r.trim())try{let o=JSON.parse(r),s=
|
|
18
|
-
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let
|
|
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 wu(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function yu(t){return t.trimStart().startsWith(mu)}function Eu(t){let e=t.trim();if(!e.startsWith(Js)||!e.endsWith("]]"))return null;let n=e.slice(Js.length,-2);if(!n)return null;try{return Ru(JSON.parse(n))}catch{return null}}function Ru(t){return Su(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Su(t){if(!Au(t)||Object.keys(t).some(r=>!_u.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?Xs(t.taskId)&&Xs(t.agentId):t.isError===true}function Iu(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 Xs(t){return typeof t=="string"&&t.trim().length>0}function Au(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Js,mu,_u,en=v(()=>{h();Js="[[crewx:delegation-result ",mu="[[crewx:delegation-result",_u=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 xt=v(()=>{h();});var Ys,Vn,Ur,Kn=v(()=>{h();Ys=["none","minimal","low","medium","high","xhigh","max","ultra"],Vn={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"]},Ur={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(Ur).map(([t,e])=>[t,e.models]));});function qr(t){return bu[t]??t}function xu(t){return Ou.get(t)??t}function Fr(t){if(!t)return {};let e=Nu.get(t);return e?{...e}:{model:t}}function Br(t,e){return t==="antigravity"||t==="cli/antigravity"?Fr(e):e===void 0?{}:{model:xu(e)}}var vu,bu,Ou,Cu,Nu,tn=v(()=>{h();vu=[{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]"}],bu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Ou=new Map(vu.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Cu=[{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"}],Nu=new Map(Cu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Du(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function et(t){return Jn(t).models}function Jn(t){return Pu[t]??Ur[t]??Du()}function nn(t,e){let n=Jn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Br(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Qs(t){return Jn(t).modelOverrides}function Zs(){return et("claude")}function ei(){return et("codex")}function ti(){return et("copilot")}function ni(){return et("antigravity")}var Pu,ct=v(()=>{h();Kn();jn();tn();Pu={};});function ri(t){return Lu[t]??t}var Lu,oi=v(()=>{h();ct();tn();Lu={auto:"default"};});function Xn(t,e){return (Vn[t]??[]).includes(e)}function tt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Mu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function si(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 ii(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 ai(t){return !t||!Xn("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function di(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=ri(t);return e.has(n)?["--permission-mode",n]:[]}function ui(t){return t?Xn("claude",t)?["--effort",t]:[]:[]}function ci(t){return t==="default"?[]:t&&Hu.has(t)?["--permission-mode",t]:[]}function li(t){return t===true?["--always-approve"]:[]}function pi(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 fi(t){return t?Xn("grok",t)?["--effort",t]:[]:[]}function gi(t){if(!t)return [];switch(qr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function hi(t){return t?Xn("antigravity",t)?["--effort",t]:[]:[]}var Mu,Hu,rn=v(()=>{h();oi();tn();Kn();Mu=new Set(Ys);Hu=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function $u(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 Uu(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 qu(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 mi(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 Ct(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=qu(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=$u(o)??Uu(o);i&&(e=i);}catch{}return n||(e??void 0)}var on=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 _i(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 ju(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 Wu(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
19
21
|
|
|
20
|
-
`):""}function
|
|
21
|
-
`):
|
|
22
|
-
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,
|
|
23
|
-
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let
|
|
24
|
-
`).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let a=s.item.text;a.trim()&&n.push(a.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function $u(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return $e(r)?[Ue(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function Uu(t,e){let n=e.type;if(n==="message"||n==="text"){let r=e.content;if(Array.isArray(r))for(let o of r){let s=qu(t,o);if(s)return s}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(n==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(n==="reasoning"){let r=typeof e.text=="string"?e.text.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="command_execution"){let r=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:t,type:"tool_result",...ze(r,o)}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=qe(o);return r==="Bash"&&$e(s)?Ue(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}if(n==="tool_result"){let r=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...ze(o,r)}}if(n==="web_search"){let r=e.action,o;if(r?.type==="search"){let s=r.queries;o=String(r.query||"")||(s?.length?s.join(", "):"")||String(e.query||"");}else o=e.query?"open: "+String(e.query):"";return o?{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:o}:null}if(n==="file_change"){let r=e.changes;if(!Array.isArray(r)||r.length===0)return null;let o=r.map(a=>String(a.path||"")).filter(Boolean);if(o.length===0)return null;let s=o.length===1?o[0]:`${o.slice(0,2).join(", ")}${o.length>2?` (+${o.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:s}}return null}function qu(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=qe(o);return r==="Bash"&&$e(s)?Ue(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var Lu,Wr,Gr=v(()=>{h();tn();Ot();bt();Yt();en();pt();ft();Lu=new Set(["turn.started","turn.completed","item.updated"]);Wr={command:"codex",meta:{displayName:"Codex",models:Js(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=rt(e.model),s=e.effort??o,a=e.resumeSessionId?ti(e.mode):ei(e.mode),u=ni(s),d=r?["-m",r]:[],c=Hu(e.additionalArgs??[]),p=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...a,...u,...d,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...a,...u,...d,...c],stdinMessage:t}},extractText(t){return gi(t)??t.trim()},extractPartialText(t){return gi(t)},parseResultMeta(t){let e=xt(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=Mu(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let a;try{a=JSON.parse(s);}catch{continue}let u=a.type;if(!u||!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread."))continue;let d=Ae(a,n),c=a.item;if(c){if(u==="item.started"){r.push(...$u(d,c));continue}if(u==="item.completed"){let l=Uu(d,c);l&&r.push(l);continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Lu.has(r):!1}catch{return false}}};});function ju(t){return t?Bu[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Kn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ti(t){let e=[],n=0,r=false,o=false,s=0;for(let u=0;u<t.length;u++){let d=t[u];if(o){o=false;continue}if(d==="\\"&&r){o=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let c=t.slice(s,u+1).trim();c&&e.push(c),s=u+1;}}}let a=t.slice(s).trim();return a&&e.push(a),e}function Nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Wu(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let o=r.trim();if(!o)continue;try{let a=JSON.parse(o);Nt(a)?e.push(a):n=!0;continue}catch{}let s=Ti(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let a of s)try{let u=JSON.parse(a);Nt(u)?e.push(u):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function gt(t){if(typeof t!="string")return;let e=t.split(/\r?\n/).map(n=>n.trim()).find(n=>n&&!/^at\s+/.test(n));if(e)return e.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").replace(/(?:[A-Za-z]:[\\/]|\/)(?:[^\s"'`()\[\]{}]+[\\/])*[^\s"'`()\[\]{}]+/g,"[path]").slice(0,ki).trim()}function wi(t){let e=Nt(t.error)?t.error:void 0,n=e&&Nt(e.data)?e.data:void 0,r=gt(e?.name),o=gt(n?.message)??gt(e?.message)??gt(t.message)??gt(t.errorMessage)??gt(t.error),s=gt(t.ref),a=r&&o&&r!==o?`${r}: ${o}`:r??o??_i;return (s?`${a} (ref: ${s})`:a).slice(0,ki)}function hi(t){let e=Wu(t),n=[],r=null,o=0,s=[],a,u=false;for(let d of e.events){let c=typeof d.type=="string"?d.type:void 0;if(c){if(c==="text"){let l=Nt(d.part)?d.part:void 0,p=typeof l?.text=="string"?l.text:void 0;p?.trim()&&n.push(p.trim());continue}if(c==="result"){typeof d.result=="string"&&(r=d.result);continue}if(c==="tool_use"){o++;continue}if(c==="error"){s.push(wi(d));continue}if(c==="step_finish"){u=true;let l=Nt(d.part)?d.part:void 0;a=typeof l?.reason=="string"?l.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorMessages:s,terminalReason:a,hasTerminal:u}}function yi(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Jn(){return new ne("OpenCode returned no assistant output.",Ct,{code:"EMPTY_OUTPUT",kind:"transient"})}function Gu(){return new ne("OpenCode emitted malformed JSON output.",Ct,{code:"PROVIDER_CRASHED",kind:"transient"})}function mi(t,e){switch(yi(t)){case "length":return new ne("OpenCode stopped because the context window was exceeded.",Ct,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new ne("OpenCode stopped because the content filter blocked the response.",Ct,{code:"UNKNOWN",kind:"permanent"});case "error":return new ne(e?`OpenCode error: ${e}`:`${_i} while generating a response.`,Ct,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var Fu,Ct,_i,ki,Bu,zr,Vr=v(()=>{h();Xt();tn();bt();ft();Fu=new Set(["step_start","step_finish"]),Ct="cli/opencode",_i="OpenCode provider error",ki=240,Bu={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};zr={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Kn(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:a}=ju(e.mode);Kn(o,"--agent")||s!==void 0&&o.push("--agent",s),a&&!Kn(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!Kn(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let u;return !n&&!a&&!e.env?.OPENCODE_PERMISSION&&(u={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:u}},extractText(t){let e=hi(t),n=e.errorMessages[0];if(n){let a=mi("error",n);if(a)throw a}let r=mi(e.terminalReason??"",void 0);if(r)throw r;let o=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(o!==void 0){if(!e.hasTerminal)throw Jn();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Jn();return e.resultText}if(e.malformed)throw Gu();if(!e.hasTerminal)throw Jn();let s=yi(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Jn()},interpretExit(t,e,n=""){if(t===0)return null;let o=hi(n).errorMessages[0];return o?new ne(`OpenCode error: ${o}`,Ct,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=xt(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=Ti(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let a;try{a=JSON.parse(s);}catch{continue}let u=Ae(a,n),d=a.type;if(d){if(d==="text"){let l=a.part?.text;l&&r.push({timestamp:u,type:"text",content:l});continue}if(d==="tool_use"){let c=a.part;if(!c)continue;let l=String(c.tool||""),p=String(c.callID||""),g=c.state,m=String(g?.status||""),T=g?.input,E=qe(T);if(r.push({timestamp:u,type:"tool_use",toolName:l,toolUseId:p,toolInput:E}),m==="completed"&&g?.output!==void 0){let w=g.output,C=typeof w=="string"?w:JSON.stringify(w);r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:C,isError:false});}else m==="error"&&r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(d==="error"){let c=wi(a);r.push({timestamp:u,type:"error",content:c,errorMessage:c});continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Fu.has(r):!1}catch{return false}}};});function nn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function zu(t,e){if(!(t?nt(Kr).some(s=>s.id===t):false)||!t)return e;let r=Zt(Kr,t),o=Vs(Kr)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var Kr,Jr,Xr=v(()=>{h();Xt();Qt();pt();en();Kr="antigravity";Jr={command:"agy",meta:{displayName:"Antigravity",models:Ys(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=rt(e.model),s=$r(r),a=s.model,u=e.effort??o??s.effort,d=zu(a,u),c=e.additionalArgs??[],l=a&&!nn(c,"--model")?["--model",a]:[],p=nn(c,"--effort")?[]:ci(d),g=nn(c,"--mode")||nn(c,"--dangerously-skip-permissions")?[]:ui(e.mode),m=nn(c,"--print")?[]:["--print",t];return {args:[...l,...p,...g,...c,...m]}},extractText(t){let e=t.trim();if(!e)throw new ne("Antigravity CLI returned empty output with exit code 0. agy may have hidden an auth/quota/model error in its log file; inspect ~/.gemini/antigravity-cli/log for details.","cli/antigravity",{code:"EMPTY_OUTPUT",kind:"transient"});return e},parseResultMeta(t){return {usage:null,model:null}},parseEvent(t,e){return []}};});var Ei=v(()=>{h();Ot();bt();Yt();ft();});function Pt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yn(t){return Pt(t)?t:void 0}function ce(t){return typeof t=="string"?t:void 0}function ht(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Yu(t){let e=[],n=-1,r=0,o=false,s=false;for(let a=0;a<t.length;a+=1){let u=t[a];if(n===-1){(u==="{"||u==="[")&&(n=a,r=1);continue}if(s){s=false;continue}if(u==="\\"&&o){s=true;continue}if(u==='"'){o=!o;continue}o||(u==="{"||u==="["?r+=1:(u==="}"||u==="]")&&(r-=1,r===0&&(e.push(t.slice(n,a+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function rn(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Pt(n)?[n]:[]}catch{return Yu(e).flatMap(n=>{try{let r=JSON.parse(n);return Pt(r)?[r]:[]}catch{return []}})}}function on(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function sn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(sn).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
25
|
-
`):void 0}if(
|
|
26
|
-
`).flatMap(
|
|
27
|
-
`),o=r.length>
|
|
28
|
-
`).flatMap(
|
|
29
|
-
`).flatMap(
|
|
30
|
-
`)??"";if(!n.trim())return;let r=Ci(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=oc(o?.model,t.model),a=o?.usage;if(!a)return {stdout:n,adapter:r};let u=Qn(a.inputTokens),d=Qn(a.outputTokens),c=Qn(a.cachedInputTokens),l=Os(Qn(a.costUsd),u,d,c,s);return u!==0||d!==0||c!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:u,outputTokens:d,cachedInputTokens:c,costUsd:l,model:s}}:{stdout:n,adapter:r}}var Zr=v(()=>{h();Ni();qn();});function ic(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.terminalReason;return typeof n=="string"&&sc.has(n)?n:void 0}catch{return}}function mt(t){switch(t.status){case "stopped":case "runner_lost":case "pending":case "running":case "paused":case "success":return t.status;case "completed":case "done":return "success";case "error":return "failed";case "failed":{let e=ic(t.metadata);return e==="user_stop"?"stopped":e==="runner_lost"?"runner_lost":e==="launch_failed"?"failed":typeof t.error=="string"&&Pi.stopped.test(t.error)?"stopped":typeof t.error=="string"&&Pi.runnerLost.test(t.error)?"runner_lost":"failed"}default:return t.status}}var Di,Pi,sc,er=v(()=>{h();Di=["success","failed","stopped","runner_lost"],Pi={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},sc=new Set(["user_stop","runner_lost","launch_failed"]);});function eo(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let o=Number(r);return !Number.isFinite(o)||o<=0?e:Math.max(n,Math.trunc(o))}function to(){return eo("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Lt(){return eo("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function nr(){return eo("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Dt(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function tr(t){let e=typeof t=="object"&&t!==null&&"code"in t?String(t.code):t instanceof Error?t.name:typeof t;console.warn(`[crewx] task heartbeat write failed (${e}); execution continues`);}function ac(t){return t?{id:t.id,status:t.status,run_epoch:t.run_epoch,stop_requested_at:t.stop_requested_at,stop_requested_epoch:t.stop_requested_epoch,pid:t.pid,metadata:t.metadata,started_at:t.started_at,duration_ms:t.duration_ms}:null}function Li(t,e){return !!t.stop_requested_at&&Dt(t.stop_requested_epoch)===Dt(e)}function Mi(t,e){let n=Dt(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=ac(t.getTask(e.taskId));return !o||o.status!=="running"||Dt(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function qi(t,e){let n=an.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),an.delete(t),true)}function dn(t,e){let n=an.get(t);return !n||e!==void 0&&n.runEpoch!==Dt(e)?false:qi(t,n)}function Fi(t,e){let n=Dt(e.runEpoch);dn(e.taskId);let r=true,o=null;try{let c=Mi(t,{...e,runEpoch:n});r=c.accepted,o=c.row;}catch(c){tr(c);}if(!r)return false;let s=to(),a=Math.min(s,1e3),u=setInterval(()=>{let c=an.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=a;let l=c.heartbeatElapsedMs>=s,p=Mi(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){qi(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=s,c.lastHeartbeatAt=Date.now()),p.row&&Li(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(tr));}catch(l){tr(l);}},a),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return an.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),o&&Li(o,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(tr)),true}var Hi,$i,Ui,an,un=v(()=>{h();Hi=1e4,$i=3e4,Ui=18e5;an=new Map;});function rr(t,e=Date.now(),n=so){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=uo(n,so,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function uo(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function zi(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function hc(t){if(!t)return;let e=zi(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function ge(t,e){if(!t)return {status:"not_running",finalStatus:"not_running",...e?{pid:e}:{}};let n=typeof t.pid=="number"&&t.pid>0?t.pid:e;if(t.status==="stopped"){let r=hc(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function fo(t,e,n="Process owner could not be verified"){let r=e??(t.pid&&t.pid>0?t.pid:void 0);return {status:"ownership_unverified",finalStatus:t.status,...r?{pid:r}:{},error:n}}function z(t,e,n){let r=n??(t?.pid&&t.pid>0?t.pid:void 0);return {status:"failed",finalStatus:t?.status??null,...r?{pid:r}:{},error:e}}function oo(t,e){return z(t,cc,e)}function mc(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Lt():false}function _c(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function kc(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=zi(t.metadata),r=n.ownership==="runner"&&typeof n.providerPid=="number"&&Number.isSafeInteger(n.providerPid)&&n.providerPid>0?n.providerPid:void 0;return [...new Set([e,r].filter(o=>o!==void 0))]}function Tc(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return ge(r,n)}async function wc(t,e,n,r){let o=Date.now()+n;for(;;){let s=Tc(t,e);if(s)return s;let a=o-Date.now();if(a<=0)return;await new Promise(u=>{setTimeout(u,Math.min(r,a));});}}async function Gi(t,e,n){let r=new Date().toISOString(),o={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},s=t.requestTaskStop({id:e,requestedAt:r,...o}),a=t.getTask(e);if(!s.accepted){if(s.status==="pending"){let q=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),y=t.getTask(e);if(q||!y||y.status!=="running")return ge(y);if(s=t.requestTaskStop({id:e,requestedAt:r,...o}),!s.accepted&&s.status!=="running"||!s.accepted&&!s.alreadyRequestedAt)return ge(t.getTask(e))}else if(!(s.status==="running"&&s.alreadyRequestedAt))return ge(a)}let u=s.runEpoch,d=uo(n.graceMs,so,0),c=uo(n.pollMs,dc,1),l=await wc(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return ge(p);let g=kc(p),m=g[0];if(!m){let q=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),y=t.getTask(e);return q||y?.status!=="running"?ge(y):z(y,"Failed to finalize task stop")}let T=_c(n),E="unknown";if(!mc(p,Date.now())){let q=n.processControl?.checkProcessOwnershipAsync??Fn;try{E=await q(m,n.ownershipMarkers??po,T);}catch{E="unknown";}if(E!=="owned")return fo(p)}let w=n.processControl?.terminateProcessTree??vt;for(let q of g){let y;try{y=await w(q,{...T,signal:At});}catch(x){y={status:"failed",pid:q,method:T.platform==="win32"?"taskkill":"process-group",error:x instanceof Error?x.message:String(x)};}if(y.status==="failed")return z(t.getTask(e),y.error??"Failed to terminate process tree")}let C=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),M=t.getTask(e);return C||M?.status!=="running"?ge(M,m):z(M,"Task changed before stop was finalized")}function co(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function lo(t){return Number.isSafeInteger(t)&&t>=0}function cn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function yc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Ec(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Rc(t,e){let n=t?.pid&&t.pid>0?t.pid:e;return {status:"stopped",method:"forced",finalStatus:t?.status??"runner_lost",...n?{pid:n}:{}}}function Sc(t){switch(t){case "epoch_mismatch":return io;case "workspace_mismatch":return ao;default:return}}async function Vi(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return oo(n,co(e.targetPid)?e.targetPid:void 0);if(!lo(e.sourceRunEpoch)||!lo(e.settleRunEpoch)||cn(n.run_epoch)!==e.settleRunEpoch)return z(n,no,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,ro,e.targetPid);let r=new Date().toISOString(),o;try{o=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return z(n,lc,e.targetPid)}let s=t.getTask(e.taskId);if(!s||s.status!=="running")return oo(s,e.targetPid);if(o.runEpoch!==e.settleRunEpoch||cn(s.run_epoch)!==e.settleRunEpoch)return z(s,no,e.targetPid);if(e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId)return z(s,ro,e.targetPid);if(!co(e.targetPid))return z(s,uc);let a=yc(e),u=e.processControl?.checkProcessOwnershipAsync??Fn,d="unknown";try{d=await u(e.targetPid,e.ownershipMarkers??po,a);}catch{d="unknown";}if(d!=="owned")return fo(s,e.targetPid);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return oo(c,e.targetPid);if(cn(c.run_epoch)!==e.settleRunEpoch)return z(c,no,e.targetPid);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,ro,e.targetPid);let l=e.processControl?.terminateProcessTree??vt,p;try{p=await l(e.targetPid,{...a,signal:At});}catch{return z(t.getTask(e.taskId),Bi,e.targetPid)}if(p.status==="failed")return z(t.getTask(e.taskId),Bi,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return z(t.getTask(e.taskId),ji,e.targetPid)}return g?ge(t.getTask(e.taskId),e.targetPid):z(t.getTask(e.taskId),ji,e.targetPid)}async function Ki(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return ge(n);if(!lo(e.expectedRunEpoch)||cn(n.run_epoch)!==e.expectedRunEpoch)return z(n,io);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,ao);let r=n.pid;if(!co(r))return z(n,pc);let o=Ec(e),s=e.processControl?.checkProcessOwnershipAsync??Fn,a="unknown";try{a=await s(r,e.ownershipMarkers??po,o);}catch{a="unknown";}if(a!=="owned")return fo(n,r,fc);let u=e.processControl?.terminateProcessTree??vt,d;try{d=await u(r,{...o,signal:At});}catch{return z(t.getTask(e.taskId),Wi,r)}if(d.status==="failed")return z(t.getTask(e.taskId),Wi,r);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return ge(c,r);if(cn(c.run_epoch)!==e.expectedRunEpoch)return z(c,io,r);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,ao,r);let l;try{l=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return z(t.getTask(e.taskId),gc,r)}let p=Sc(l);return p?z(t.getTask(e.taskId),p,r):l!=="settled"?ge(t.getTask(e.taskId),r):Rc(t.getTask(e.taskId),r)}function Ji(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(ho(),Xi)).then(({TaskRepository:s})=>Gi(new s,r,o))}return Gi(t,e,n)}var so,dc,po,uc,no,ro,cc,Bi,ji,lc,io,ao,pc,fc,Wi,gc,go=v(()=>{h();Bn();un();so=5e3,dc=250;po=["crewx","claude","codex","opencode","grok","node"],uc="INSTRUCTION_STOP_TARGET_PID_MISSING",no="INSTRUCTION_STOP_EPOCH_MISMATCH",ro="INSTRUCTION_STOP_WORKSPACE_MISMATCH",cc="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",Bi="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",ji="INSTRUCTION_STOP_SETTLE_CAS_FAILED",lc="INSTRUCTION_STOP_REQUEST_FAILED",io="HOST_SHUTDOWN_EPOCH_MISMATCH",ao="HOST_SHUTDOWN_WORKSPACE_MISMATCH",pc="HOST_SHUTDOWN_TARGET_PID_MISSING",fc="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",Wi="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",gc="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var Xi={};xa(Xi,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>sa,HOST_SHUTDOWN_TERMINAL_ERROR:()=>na,PENDING_ADOPT_GRACE_MS:()=>oa,PID_NULL_REAP_GRACE_MS:()=>Ro,TASK_HEARTBEAT_HARD_STALE_MS:()=>Ui,TASK_HEARTBEAT_INTERVAL_MS:()=>Hi,TASK_HEARTBEAT_STALE_MS:()=>$i,TaskRepository:()=>hn,hasRecordedUsage:()=>Eo,mergeTerminalReason:()=>yo,resolveTaskHeartbeatHardStaleMs:()=>nr,resolveTaskHeartbeatIntervalMs:()=>to,resolveTaskHeartbeatStaleMs:()=>Lt});function Oe(t){return {...t,status:mt(t)}}function Yi(t){return {...t,status:mt(t)}}function Qi(){let t=sql`
|
|
22
|
+
`):""}function Gu(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function zu(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 Fu,Bu,Yn,jr=v(()=>{h();$r();vt();bt();Ot();en();xt();rn();ct();on();lt();Fu=new Set(["tool_progress"]),Bu="cli/claude";Yn={command:"claude",meta:{displayName:"Claude",models:Zs(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=tt(e.model),s=e.effort??o,i=di(e.mode),u=ui(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=ju(t);if(e?.is_error===true){let o=Yn.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})`,Bu,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=_i(t);if(n)return n;let r=t.trim();return $e(r,"claude")?"":r},extractPartialText(t){return _i(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=Wu(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(Gu(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=mi(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=zu(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?Fu.has(r):!1}catch{return false}}};});function ki(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 Vu,Wr,Gr=v(()=>{h();bt();on();Ot();xt();en();ct();Kn();lt();Vu=new Set(["interactive","plan","autopilot"]);Wr={command:"copilot",meta:{displayName:"Copilot",models:ti()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&Vu.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Vn.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=ki(t);if(e)return e;let n=t.trim();return $e(n,"copilot")?"":n},extractPartialText(t){return ki(t)},parseResultMeta(t){let e=Ct(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 Ju(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 Xu(t){return t[0]==="exec"?t.slice(1):t}function Ti(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 Yu(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 Qu(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=Zu(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 Zu(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 Ku,zr,Vr=v(()=>{h();bt();on();Ot();xt();en();rn();ct();lt();Ku=new Set(["turn.started","turn.completed","item.updated"]);zr={command:"codex",meta:{displayName:"Codex",models:ei(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=tt(e.model),s=e.effort??o,i=e.resumeSessionId?ii(e.mode):si(e.mode),u=ai(s),d=r?["-m",r]:[],c=Xu(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=Ti(t);if(e)return e;let n=t.trim();return $e(n,"codex")?"":n},extractPartialText(t){return Ti(t)},parseResultMeta(t){let e=Ct(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=Ju(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(...Yu(d,c));continue}if(u==="item.completed"){let l=Qu(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?Ku.has(r):!1}catch{return false}}};});function nc(t){return t?tc[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Qn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Si(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 Pt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function rc(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);Pt(i)?e.push(i):n=!0;continue}catch{}let s=Si(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);Pt(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,Ri).trim()}function Ii(t){let e=Pt(t.error)?t.error:void 0,n=e&&Pt(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??Ei;return (s?`${i} (ref: ${s})`:i).slice(0,Ri)}function wi(t){let e=rc(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=Pt(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(Ii(d));continue}if(c==="step_finish"){u=true;let l=Pt(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 Ai(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Zn(){return new Z("OpenCode returned no assistant output.",Nt,{code:"EMPTY_OUTPUT",kind:"transient"})}function oc(){return new Z("OpenCode emitted malformed JSON output.",Nt,{code:"PROVIDER_CRASHED",kind:"transient"})}function yi(t,e){switch(Ai(t)){case "length":return new Z("OpenCode stopped because the context window was exceeded.",Nt,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new Z("OpenCode stopped because the content filter blocked the response.",Nt,{code:"UNKNOWN",kind:"permanent"});case "error":return new Z(e?`OpenCode error: ${e}`:`${Ei} while generating a response.`,Nt,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var ec,Nt,Ei,Ri,tc,Kr,Jr=v(()=>{h();vt();on();xt();lt();ec=new Set(["step_start","step_finish"]),Nt="cli/opencode",Ei="OpenCode provider error",Ri=240,tc={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Kr={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];Qn(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=nc(e.mode);Qn(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!Qn(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!Qn(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=wi(t),n=e.errorMessages[0];if(n){let i=yi("error",n);if(i)throw i}let r=yi(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 Zn();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Zn();return e.resultText}if(e.malformed)throw oc();if(!e.hasTerminal)throw Zn();let s=Ai(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Zn()},interpretExit(t,e,n=""){if(t===0)return null;let o=wi(n).errorMessages[0];return o?new Z(`OpenCode error: ${o}`,Nt,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=Ct(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n=e??new Date().toISOString(),r=[],o;try{JSON.parse(t),o=[t];}catch{o=Si(t),o.length>1&&console.warn("[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=Ii(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?ec.has(r):!1}catch{return false}}};});function sn(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function sc(t,e){if(!(t?et(Xr).some(s=>s.id===t):false)||!t)return e;let r=nn(Xr,t),o=Qs(Xr)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var Xr,Yr,Qr=v(()=>{h();vt();tn();ct();rn();Xr="antigravity";Yr={command:"agy",meta:{displayName:"Antigravity",models:ni(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=tt(e.model),s=Fr(r),i=s.model,u=e.effort??o??s.effort,d=sc(i,u),c=e.additionalArgs??[],l=i&&!sn(c,"--model")?["--model",i]:[],p=sn(c,"--effort")?[]:hi(d),g=sn(c,"--mode")||sn(c,"--dangerously-skip-permissions")?[]:gi(e.mode),_=sn(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 vi=v(()=>{h();Ot();xt();en();lt();});function Dt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function tr(t){return Dt(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 cc(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 an(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Dt(n)?[n]:[]}catch{return cc(e).flatMap(n=>{try{let r=JSON.parse(n);return Dt(r)?[r]:[]}catch{return []}})}}function dn(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function un(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(un).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
27
|
+
`):void 0}if(Dt(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=un(t[e]);if(n!==void 0)return n}}}function lc(t){if(t.rawOutput!==null&&t.rawOutput!==void 0)return un(t.rawOutput)??dn(t.rawOutput);if(t.content!==null&&t.content!==void 0)return un(t.content)??dn(t.content);if(t.result!==null&&t.result!==void 0)return un(t.result)??dn(t.result)}function Ni(t){let e=tr(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?Pi(n):"Grok CLI reported an error."}function Pi(t){return (t.replace(uc,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Ci(t){return dc.test(t)}function pc(t){let e=tr(t.modelUsage);return e?Object.keys(e)[0]??null:null}function fc(t){let e=tr(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 gc(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
28
|
+
`).flatMap(an)){if(i.type!=="usage")continue;let u=tr(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 hc(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,bi)){if(!Dt(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>bi&&n.push(xi);let r=n.join(`
|
|
29
|
+
`),o=r.length>Oi?`${r.slice(0,Oi-1)}${xi}`:r;return [{timestamp:t,type:"info",content:o}]}function mc(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 hc(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:dn(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:lc(e),isError:r!=="completed"||e.isError===true}]}if(n==="error"){let r=Ni(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var er,ac,dc,uc,bi,Oi,xi,Zr,eo=v(()=>{h();vt();$r();ct();rn();lt();er="cli/grok",ac=new Set(["available_commands","usage","end"]),dc=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,uc=/\u001b\[[0-?]*[ -/]*[@-~]/g,bi=20,Oi=4e3,xi="\u2026";Zr={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?nn("grok",n):[],c=!o||d.length===0||d.includes(o)?o:void 0,l=fi(c),p=e.additionalArgs??[],g=D=>p.some(E=>E===D||E.startsWith(`${D}=`)),_=e.providerOptions,m=_?.alwaysApprove,w=_?.sandbox,k=g("--permission-mode")?[]:ci(e.mode),C=g("--always-approve")?[]:li(m),L=g("--sandbox")?[]:pi(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(an))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 an(t))if(e.type==="error"){let n=Ni(e);return Ci(dn(e))?new ze(n,er):new Z(n,er)}return null},interpretExit(t,e){if(t===0)return null;let n=Pi(e)||`Grok CLI exited with code ${t}.`;return Ci(e)?new ze(n,er):new Z(n,er)},parseResultMeta(t){let n=t.split(`
|
|
31
|
+
`).flatMap(an).find(r=>r.type==="end");return n?{usage:fc(n),model:pc(n)}:{usage:gc(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return an(t).flatMap(r=>mc(Ae(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return Dt(n)&&typeof n.type=="string"?ac.has(n.type):!1}catch{return false}}};});var Di,Li=v(()=>{h();jr();Gr();Vr();Jr();Qr();vi();eo();jr();Gr();Vr();Jr();Qr();eo();Ot();Di={codex:zr,claude:Yn,opencode:Kr,antigravity:Yr,copilot:Wr,grok:Zr};});function Mi(t){if(t.startsWith("cli/"))return Di[t.slice(4)]}var Hi=v(()=>{h();zs();Li();});function nr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function _c(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function rr(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=Mi(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=_c(o?.model,t.model),i=o?.usage;if(!i)return {stdout:n,adapter:r};let u=nr(i.inputTokens),d=nr(i.outputTokens),c=nr(i.cachedInputTokens),l=Cs(nr(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 to=v(()=>{h();Hi();jn();});function Tc(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"&&kc.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=Tc(t.metadata);return e==="user_stop"?"stopped":e==="runner_lost"?"runner_lost":e==="launch_failed"?"failed":typeof t.error=="string"&&$i.stopped.test(t.error)?"stopped":typeof t.error=="string"&&$i.runnerLost.test(t.error)?"runner_lost":"failed"}default:return t.status}}var Ui,$i,kc,or=v(()=>{h();Ui=["success","failed","stopped","runner_lost"],$i={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},kc=new Set(["user_stop","runner_lost","launch_failed"]);});function no(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 ro(){return no("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function Mt(){return no("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function ir(){return no("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function Lt(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function sr(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 wc(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 qi(t,e){return !!t.stop_requested_at&&Lt(t.stop_requested_epoch)===Lt(e)}function Fi(t,e){let n=Lt(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=wc(t.getTask(e.taskId));return !o||o.status!=="running"||Lt(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function Gi(t,e){let n=cn.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),cn.delete(t),true)}function ln(t,e){let n=cn.get(t);return !n||e!==void 0&&n.runEpoch!==Lt(e)?false:Gi(t,n)}function zi(t,e){let n=Lt(e.runEpoch);ln(e.taskId);let r=true,o=null;try{let c=Fi(t,{...e,runEpoch:n});r=c.accepted,o=c.row;}catch(c){sr(c);}if(!r)return false;let s=ro(),i=Math.min(s,1e3),u=setInterval(()=>{let c=cn.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=i;let l=c.heartbeatElapsedMs>=s,p=Fi(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){Gi(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=s,c.lastHeartbeatAt=Date.now()),p.row&&qi(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(sr));}catch(l){sr(l);}},i),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return cn.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),o&&qi(o,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(sr)),true}var Bi,ji,Wi,cn,pn=v(()=>{h();Bi=1e4,ji=3e4,Wi=18e5;cn=new Map;});function ar(t,e=Date.now(),n=ao){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=lo(n,ao,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function lo(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function Yi(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function bc(t){if(!t)return;let e=Yi(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=bc(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function ho(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 io(t,e){return z(t,Rc,e)}function Oc(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=Mt():false}function xc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Cc(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=Yi(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 Nc(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return ge(r,n)}async function Pc(t,e,n,r){let o=Date.now()+n;for(;;){let s=Nc(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 Xi(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=lo(n.graceMs,ao,0),c=lo(n.pollMs,yc,1),l=await Pc(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return ge(p);let g=Cc(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=xc(n),w="unknown";if(!Oc(p,Date.now())){let D=n.processControl?.checkProcessOwnershipAsync??Wn;try{w=await D(_,n.ownershipMarkers??go,m);}catch{w="unknown";}if(w!=="owned")return ho(p)}let k=n.processControl?.terminateProcessTree??At;for(let D of g){let E;try{E=await k(D,{...m,signal:It});}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 po(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function fo(t){return Number.isSafeInteger(t)&&t>=0}function fn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Dc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Lc(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Mc(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 Hc(t){switch(t){case "epoch_mismatch":return uo;case "workspace_mismatch":return co;default:return}}async function Qi(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return io(n,po(e.targetPid)?e.targetPid:void 0);if(!fo(e.sourceRunEpoch)||!fo(e.settleRunEpoch)||fn(n.run_epoch)!==e.settleRunEpoch)return z(n,oo,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,so,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,Sc,e.targetPid)}let s=t.getTask(e.taskId);if(!s||s.status!=="running")return io(s,e.targetPid);if(o.runEpoch!==e.settleRunEpoch||fn(s.run_epoch)!==e.settleRunEpoch)return z(s,oo,e.targetPid);if(e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId)return z(s,so,e.targetPid);if(!po(e.targetPid))return z(s,Ec);let i=Dc(e),u=e.processControl?.checkProcessOwnershipAsync??Wn,d="unknown";try{d=await u(e.targetPid,e.ownershipMarkers??go,i);}catch{d="unknown";}if(d!=="owned")return ho(s,e.targetPid);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return io(c,e.targetPid);if(fn(c.run_epoch)!==e.settleRunEpoch)return z(c,oo,e.targetPid);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,so,e.targetPid);let l=e.processControl?.terminateProcessTree??At,p;try{p=await l(e.targetPid,{...i,signal:It});}catch{return z(t.getTask(e.taskId),Vi,e.targetPid)}if(p.status==="failed")return z(t.getTask(e.taskId),Vi,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return z(t.getTask(e.taskId),Ki,e.targetPid)}return g?ge(t.getTask(e.taskId),e.targetPid):z(t.getTask(e.taskId),Ki,e.targetPid)}async function Zi(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return ge(n);if(!fo(e.expectedRunEpoch)||fn(n.run_epoch)!==e.expectedRunEpoch)return z(n,uo);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return z(n,co);let r=n.pid;if(!po(r))return z(n,Ic);let o=Lc(e),s=e.processControl?.checkProcessOwnershipAsync??Wn,i="unknown";try{i=await s(r,e.ownershipMarkers??go,o);}catch{i="unknown";}if(i!=="owned")return ho(n,r,Ac);let u=e.processControl?.terminateProcessTree??At,d;try{d=await u(r,{...o,signal:It});}catch{return z(t.getTask(e.taskId),Ji,r)}if(d.status==="failed")return z(t.getTask(e.taskId),Ji,r);let c=t.getTask(e.taskId);if(!c||c.status!=="running")return ge(c,r);if(fn(c.run_epoch)!==e.expectedRunEpoch)return z(c,uo,r);if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return z(c,co,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),vc,r)}let p=Hc(l);return p?z(t.getTask(e.taskId),p,r):l!=="settled"?ge(t.getTask(e.taskId),r):Mc(t.getTask(e.taskId),r)}function ea(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(_o(),ta)).then(({TaskRepository:s})=>Xi(new s,r,o))}return Xi(t,e,n)}var ao,yc,go,Ec,oo,so,Rc,Vi,Ki,Sc,uo,co,Ic,Ac,Ji,vc,mo=v(()=>{h();Gn();pn();ao=5e3,yc=250;go=["crewx","claude","codex","opencode","grok","node"],Ec="INSTRUCTION_STOP_TARGET_PID_MISSING",oo="INSTRUCTION_STOP_EPOCH_MISMATCH",so="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Rc="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",Vi="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Ki="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Sc="INSTRUCTION_STOP_REQUEST_FAILED",uo="HOST_SHUTDOWN_EPOCH_MISMATCH",co="HOST_SHUTDOWN_WORKSPACE_MISMATCH",Ic="HOST_SHUTDOWN_TARGET_PID_MISSING",Ac="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",Ji="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",vc="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var ta={};Na(ta,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>ua,HOST_SHUTDOWN_TERMINAL_ERROR:()=>ia,PENDING_ADOPT_GRACE_MS:()=>da,PID_NULL_REAP_GRACE_MS:()=>Ao,TASK_HEARTBEAT_HARD_STALE_MS:()=>Wi,TASK_HEARTBEAT_INTERVAL_MS:()=>Bi,TASK_HEARTBEAT_STALE_MS:()=>ji,TaskRepository:()=>kn,hasRecordedUsage:()=>Io,mergeTerminalReason:()=>So,resolveTaskHeartbeatHardStaleMs:()=>ir,resolveTaskHeartbeatIntervalMs:()=>ro,resolveTaskHeartbeatStaleMs:()=>Mt});function be(t){return {...t,status:gt(t)}}function na(t){return {...t,status:gt(t)}}function wo(t=a.model,e=a.metadata){let n=sql`
|
|
31
33
|
CASE
|
|
32
|
-
WHEN ${
|
|
33
|
-
WHEN ${
|
|
34
|
-
WHEN ${
|
|
35
|
-
WHEN ${
|
|
36
|
-
WHEN ${
|
|
37
|
-
WHEN ${
|
|
38
|
-
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'
|
|
39
41
|
ELSE 'unknown'
|
|
40
42
|
END
|
|
41
|
-
`,
|
|
43
|
+
`,r=sql`json_extract(${e}, '$.provider')`,o=sql`trim(${r})`,s=sql`substr(${o}, 1, instr(${o}, '/') - 1)`,i=sql`
|
|
42
44
|
CASE
|
|
43
|
-
WHEN instr(${
|
|
44
|
-
AND ${
|
|
45
|
-
THEN substr(${
|
|
46
|
-
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}
|
|
47
49
|
END
|
|
48
50
|
`;return sql`
|
|
49
51
|
CASE
|
|
50
|
-
WHEN ${
|
|
51
|
-
WHEN json_valid(${
|
|
52
|
-
WHEN json_type(${
|
|
53
|
-
WHEN json_type(${
|
|
54
|
-
WHEN json_type(${
|
|
55
|
-
WHEN ${
|
|
56
|
-
WHEN trim(${
|
|
57
|
-
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}
|
|
58
60
|
END
|
|
59
|
-
`}function
|
|
61
|
+
`}function _n(t){return sql`${t} NOT IN (${sql.join(zc.map(e=>sql`${e}`),sql`, `)})`}function dr(t){let e=sql`
|
|
60
62
|
CASE
|
|
61
63
|
WHEN json_valid(${t}) = 1
|
|
62
64
|
THEN json_extract(${t}, '$.usageAccounting')
|
|
@@ -66,13 +68,13 @@ ${r.join(`
|
|
|
66
68
|
COALESCE(SUM(
|
|
67
69
|
CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
|
|
68
70
|
), 0)
|
|
69
|
-
`}function Ht(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Z(t){if(!t)return {};try{let e=JSON.parse(t);return Ht(e)?{...e}:{}}catch{return {}}}function sr(t,e){let n=t.origin&&ra.has(t.origin)?t.origin:"internal",r=t.callerPid!==void 0&&Number.isInteger(t.callerPid)&&t.callerPid>0?t.callerPid:process.pid;return {origin:n,at:t.at??e,callerPid:r,...t.callerTaskId?{callerTaskId:t.callerTaskId}:{}}}function Dc(t){let e=Z(t).stopRequest;if(Ht(e)&&!(typeof e.origin!="string"||!ra.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function ea(){return or$1(isNull(i.stop_requested_at),ne$1(sql`COALESCE(${i.stop_requested_epoch}, 0)`,sql`COALESCE(${i.run_epoch}, 0)`))}function yo(t,e){let n=Z(t??null);return n.terminalReason=e,JSON.stringify(n)}function To(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==Zi&&(n[Cc]=e),{error:Zi,metadata:n}}function re(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Eo(t){return re(t.input_tokens)!==0||re(t.output_tokens)!==0||re(t.cached_input_tokens)!==0||re(t.cost_usd)!==0}function V(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function ta(t){return {inputTokens:re(t.inputTokens??0),outputTokens:re(t.outputTokens??0),cachedInputTokens:re(t.cachedInputTokens??0),costUsd:re(t.costUsd??0)}}function Lc(t){if(Ht(t))return {inputTokens:re(t.inputTokens),outputTokens:re(t.outputTokens),cachedInputTokens:re(t.cachedInputTokens),costUsd:re(t.costUsd)}}function Mc(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=Lc(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function ir(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}var _o,Ke,bc,Je,Xe,xc,ko,fn,be,Zi,na,Cc,Nc,Pc,ra,Ro,oa,sa,hn,ho=v(()=>{h();dt();wt();yt();it();St();qn();Bn();Bs();Zr();er();un();go();un();_o=40,Ke="2026-05-09",bc="0.8.9-rc.13",Je=10,Xe=parseInt(bc.split("rc.")[1]);xc=new Set(["workflow","mcp"]),ko="usageByEpoch",fn="lateUsage",be="usageAccounting",Zi="Stopped by user",na="Stopped by app shutdown",Cc="terminalErrorOriginal",Nc=new Set(["stopped","runner_lost"]),Pc=["pending","running"];ra=new Set(["http","cli","instruction","workflow","internal"]);Ro=600*1e3,oa=600*1e3,sa=300*1e3,hn=class extends ke{dbPath;clock;taskLogRepository;lastReaperTickAt;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new jn({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?at(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new f("NOT_FOUND","Database not found");let r=W(n);if(e)try{Ne(r.db,n);}catch(o){throw r.close(),o}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=V(e.runEpoch),o=r===0?or$1(eq(i.run_epoch,0),isNull(i.run_epoch)):eq(i.run_epoch,r);return n.db.update(i).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(and(eq(i.id,e.id),o,eq(i.status,"running"))).run().changes>0}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:i.id,status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!s)return;let a=V(s.run_epoch);if(s.status!=="running"){r={accepted:!1,status:s.status,runEpoch:a};return}let u=s.stop_requested_at!==null&&V(s.stop_requested_epoch)===a,d=u?s.stop_requested_at:e.requestedAt,c=Z(s.metadata),l=u?Dc(s.metadata)??sr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):sr({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(o.update(i).set({stop_requested_at:e.requestedAt,stop_requested_epoch:sql`${i.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(and(eq(i.id,e.id),eq(i.status,"running"),ea())).run().changes===0){let T=o.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!T||T.status!=="running"){r={accepted:!1,status:T?.status??"not_running",runEpoch:V(T?.run_epoch)};return}r={accepted:!1,status:T.status,runEpoch:V(T.run_epoch),...T.stop_requested_at&&V(T.stop_requested_epoch)===V(T.run_epoch)?{alreadyRequestedAt:T.stop_requested_at}:{}};}else r={accepted:!0,status:s.status,runEpoch:a};let g=new Set([e.id]),m=(T,E)=>{if(E>=8)return;let w=o.select({id:i.id,status:i.status,metadata:i.metadata}).from(i).where(and(eq(i.parent_task_id,T),eq(i.status,"running"))).all();for(let C of w)g.has(C.id)||(g.add(C.id),o.update(i).set({stop_requested_at:d,stop_requested_epoch:sql`${i.run_epoch}`,metadata:JSON.stringify({...Z(C.metadata),stopRequest:l})}).where(and(eq(i.id,C.id),eq(i.status,"running"),ea())).run(),m(C.id,E+1));};m(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(o=>{let s=o.select({id:i.id,status:i.status,run_epoch:i.run_epoch,workspace_id:i.workspace_id,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!s)return;let a=V(s.run_epoch),u=V(e.sourceRunEpoch),d=V(e.settleRunEpoch);if(s.status!=="running"||a!==d||e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId){r={accepted:!1,status:s.status,runEpoch:a};return}let c=d===0?or$1(eq(i.run_epoch,0),isNull(i.run_epoch)):eq(i.run_epoch,d),l=or$1(isNull(i.stop_requested_at),isNull(i.stop_requested_epoch),ne$1(i.stop_requested_epoch,u)),p=sr({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),g=w=>o.update(i).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:JSON.stringify({...Z(s.metadata),stopRequest:p})}).where(and(eq(i.id,e.id),eq(i.status,"running"),c,w,l)).run();if((e.workspaceId===void 0?g():e.workspaceId===null?g(isNull(i.workspace_id)):g(eq(i.workspace_id,e.workspaceId))).changes>0){r={accepted:!0,status:s.status,runEpoch:d};return}let T=o.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!T||T.status!=="running"){r={accepted:!1,status:T?.status??"not_running",runEpoch:V(T?.run_epoch)};return}let E=V(T.run_epoch);r={accepted:!1,status:T.status,runEpoch:E,...T.stop_requested_at&&V(T.stop_requested_epoch)===u?{alreadyRequestedAt:T.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=!1;return n.db.transaction(s=>{let a=s.select({status:i.status,run_epoch:i.run_epoch,stop_requested_at:i.stop_requested_at,stop_requested_epoch:i.stop_requested_epoch,started_at:i.started_at,duration_ms:i.duration_ms,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!a||a.status!=="running"||V(a.run_epoch)!==V(e.runEpoch))return;let u=a.stop_requested_at!==null&&V(a.stop_requested_epoch)===V(e.runEpoch),d=Z(a.metadata),c=u?To(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...c.metadata,stopMethod:e.method},p=a.duration_ms??e.durationMs??ir(a.started_at,r,void 0),g=a.run_epoch===null?isNull(i.run_epoch):eq(i.run_epoch,a.run_epoch);o=s.update(i).set({status:"stopped",error:c.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(and(eq(i.id,e.id),eq(i.status,"running"),g)).run().changes>0;},{behavior:"immediate"}),o}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),o=V(e.expectedRunEpoch),s="not_running";return n.db.transaction(a=>{let u=a.select({status:i.status,run_epoch:i.run_epoch,workspace_id:i.workspace_id,started_at:i.started_at,duration_ms:i.duration_ms,metadata:i.metadata}).from(i).where(eq(i.id,e.id)).limit(1).get();if(!u||u.status!=="running"){s="not_running";return}if(V(u.run_epoch)!==o){s="epoch_mismatch";return}if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId){s="workspace_mismatch";return}let c=u.run_epoch===null?isNull(i.run_epoch):eq(i.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?isNull(i.workspace_id):eq(i.workspace_id,e.workspaceId),p={...Z(u.metadata),terminalReason:"runner_lost"},g=u.duration_ms??ir(u.started_at,r,void 0);s=a.update(i).set({status:"runner_lost",error:na,completed_at:r,duration_ms:g,metadata:JSON.stringify(p)}).where(and(eq(i.id,e.id),eq(i.status,"running"),c,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),s}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return Ji(this,e,n)}async stopTaskGenerationForInstruction(e){return Vi({requestTaskStop:n=>this.requestTaskStopForInstruction(n),getTask:n=>this.getTask(n),finalizeTaskStop:n=>this.finalizeTaskStop(n)},e)}startTask(e){let n=this.openHandle(true);try{let r={id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,cwd:e.cwd??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},o=s=>{n.db.insert(i).values(s).onConflictDoUpdate({target:i.id,set:{status:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN 'running' ELSE ${i.status} END`,pid:sql`COALESCE(excluded.pid, ${i.pid})`,command:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.command ELSE ${i.command} END`,metadata:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.metadata ELSE ${i.metadata} END`,workspace_id:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN COALESCE(${i.workspace_id}, excluded.workspace_id) ELSE ${i.workspace_id} END`,cwd:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN COALESCE(${i.cwd}, excluded.cwd) ELSE ${i.cwd} END`,project_id:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN COALESCE(${i.project_id}, excluded.project_id) ELSE ${i.project_id} END`,crewx_version:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.crewx_version ELSE ${i.crewx_version} END`,model:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.model ELSE ${i.model} END`,rendered_prompt:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.rendered_prompt ELSE ${i.rendered_prompt} END`,coding_agent_command:sql`CASE WHEN ${i.status} = 'pending' AND ${i.pid} IS NULL THEN excluded.coding_agent_command ELSE ${i.coding_agent_command} END`},setWhere:or$1(eq(i.status,"running"),and(eq(i.status,"pending"),isNull(i.pid)))}).run();};try{o(r);}catch(s){let a=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|cwd/i.test(a)||!/no such column|no column named/i.test(a))throw s;let u=new Set(n.db.all("PRAGMA table_info(tasks)").map(w=>w.name)),d=u.has("cwd"),c=u.has("log_storage"),l=d?", cwd":"",p=d?", ?":"",g=d?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",m=c?", log_storage":"",T=c?", ?":"",E=c?`,
|
|
71
|
+
`}function Ft(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ee(t){if(!t)return {};try{let e=JSON.parse(t);return Ft(e)?{...e}:{}}catch{return {}}}function ur(t,e){let n=t.origin&&aa.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 Vc(t){let e=ee(t).stopRequest;if(Ft(e)&&!(typeof e.origin!="string"||!aa.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function oa(){return or$1(isNull(a.stop_requested_at),ne(sql`COALESCE(${a.stop_requested_epoch}, 0)`,sql`COALESCE(${a.run_epoch}, 0)`))}function So(t,e){let n=ee(t??null);return n.terminalReason=e,JSON.stringify(n)}function Eo(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==ra&&(n[Wc]=e),{error:ra,metadata:n}}function re(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Io(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 sa(t){return {inputTokens:re(t.inputTokens??0),outputTokens:re(t.outputTokens??0),cachedInputTokens:re(t.cachedInputTokens??0),costUsd:re(t.costUsd??0)}}function Kc(t){if(Ft(t))return {inputTokens:re(t.inputTokens),outputTokens:re(t.outputTokens),cachedInputTokens:re(t.cachedInputTokens),costUsd:re(t.costUsd)}}function Jc(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){let r=Kc(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function cr(t,e,n){let r=Date.parse(t),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:n??null}var To,$t,Bc,Ut,qt,jc,yo,mn,Oe,ra,ia,Wc,Gc,zc,aa,Ao,da,ua,kn,_o=v(()=>{h();it();Tt();wt();ot();Rt();jn();Gn();Gs();to();or();pn();mo();pn();To=40,$t="2026-05-09",Bc="0.8.9-rc.13",Ut=10,qt=parseInt(Bc.split("rc.")[1]);jc=new Set(["workflow","mcp"]),yo="usageByEpoch",mn="lateUsage",Oe="usageAccounting",ra="Stopped by user",ia="Stopped by app shutdown",Wc="terminalErrorOriginal",Gc=new Set(["stopped","runner_lost"]),zc=["pending","running"];aa=new Set(["http","cli","instruction","workflow","internal"]);Ao=600*1e3,da=600*1e3,ua=300*1e3,kn=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 zn({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?Vc(s.metadata)??ur({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):ur({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"),oa())).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"),oa())).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=ur({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?Eo(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??cr(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??cr(u.started_at,r,void 0);s=i.update(a).set({status:"runner_lost",error:ia,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 ea(this,e,n)}async stopTaskGenerationForInstruction(e){return Qi({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?`,
|
|
70
72
|
log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
|
|
71
73
|
id, agent_id, prompt, mode, status, started_at, pid,
|
|
72
74
|
parent_task_id, caller_agent_id, trace_id, command, metadata,
|
|
73
75
|
workspace_id${l}, project_id, platform, crewx_version, thread_id,
|
|
74
|
-
model, rendered_prompt, coding_agent_command${
|
|
75
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${p}${
|
|
76
|
+
model, rendered_prompt, coding_agent_command${_}
|
|
77
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${p}${m})
|
|
76
78
|
ON CONFLICT(id) DO UPDATE SET
|
|
77
79
|
status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
|
|
78
80
|
pid = COALESCE(excluded.pid, tasks.pid),
|
|
@@ -83,10 +85,10 @@ ${r.join(`
|
|
|
83
85
|
crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
|
|
84
86
|
model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
|
|
85
87
|
rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
|
|
86
|
-
coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${
|
|
87
|
-
WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[r.id,r.agent_id,r.prompt,r.mode,r.status,r.started_at,r.pid,r.parent_task_id,r.caller_agent_id,r.trace_id,r.command,r.metadata,r.workspace_id,...d?[r.cwd]:[],r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command,...c?[r.log_storage]:[]]);}}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to start task",r)}finally{n.close();}}updateTaskOwnership(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:
|
|
88
|
-
AND COALESCE(${
|
|
89
|
-
`);}}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=Eo(ee(d.metadata),n),l={...c.metadata,stopMethod:"cooperative",stopRequest:ur(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=Ft(_[mn])?_[mn]:{},w=String(d),k=Gc.has(i.status),C=k&&u===d&&!Io(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=Ft(x[yo])?{...x[yo]}:{};b[String(d)]=sa(e),x[yo]=b;let Q=Jc(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=sa(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=Ft(_[mn])?{..._[mn]}:{};_e[w]={at:e.completedAt},x[mn]=_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=Eo(x,e.error);x={...b.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:ar(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??cr(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?cr(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??ua)),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=Mt(),l=ir(),p=new Date(o-da).toISOString(),g=new Date(o).toISOString(),_=new Set,m=0,w=(k,C)=>{let L=ee(So(k.metadata,"runner_lost")),D=typeof L.provider=="string"?L.provider:void 0,E;try{E=rr({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"):!Io(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=So(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(jc.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>=Ao&&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=Ao){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`
|
|
90
92
|
SELECT
|
|
91
93
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
92
94
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -107,106 +109,45 @@ ${r.join(`
|
|
|
107
109
|
FROM tasks
|
|
108
110
|
GROUP BY workspace_id
|
|
109
111
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
110
|
-
`)}catch(r){throw new f("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
t.
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
GROUP BY t.agent_id, t.workspace_id
|
|
138
|
-
ORDER BY (
|
|
139
|
-
COALESCE(SUM(
|
|
140
|
-
COALESCE(t.input_tokens, 0)
|
|
141
|
-
+ CASE
|
|
142
|
-
WHEN t.started_at >= ${Ke}
|
|
143
|
-
AND (
|
|
144
|
-
t.crewx_version IS NULL
|
|
145
|
-
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
146
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Je}) AS INTEGER) < ${Xe})
|
|
147
|
-
)
|
|
148
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
149
|
-
ELSE 0
|
|
150
|
-
END
|
|
151
|
-
), 0)
|
|
152
|
-
+ COALESCE(SUM(t.output_tokens), 0)
|
|
153
|
-
) DESC
|
|
154
|
-
`:sql`
|
|
155
|
-
SELECT
|
|
156
|
-
t.agent_id,
|
|
157
|
-
t.workspace_id,
|
|
158
|
-
COUNT(*) AS total_tasks,
|
|
159
|
-
${a} AS unavailable_task_count,
|
|
160
|
-
COALESCE(SUM(
|
|
161
|
-
COALESCE(t.input_tokens, 0)
|
|
162
|
-
+ CASE
|
|
163
|
-
WHEN t.started_at >= ${Ke}
|
|
164
|
-
AND (
|
|
165
|
-
t.crewx_version IS NULL
|
|
166
|
-
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
167
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Je}) AS INTEGER) < ${Xe})
|
|
168
|
-
)
|
|
169
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
170
|
-
ELSE 0
|
|
171
|
-
END
|
|
172
|
-
), 0) AS input_tokens,
|
|
173
|
-
COALESCE(SUM(t.output_tokens), 0) AS output_tokens,
|
|
174
|
-
COALESCE(SUM(t.cached_input_tokens), 0) AS cached_input_tokens,
|
|
175
|
-
COALESCE(SUM(t.cost_usd), 0) AS cost_usd
|
|
176
|
-
FROM tasks t
|
|
177
|
-
WHERE ${s}
|
|
178
|
-
AND t.started_at >= ${e}
|
|
179
|
-
AND t.started_at < ${n}
|
|
180
|
-
GROUP BY t.agent_id, t.workspace_id
|
|
181
|
-
ORDER BY (
|
|
182
|
-
COALESCE(SUM(
|
|
183
|
-
COALESCE(t.input_tokens, 0)
|
|
184
|
-
+ CASE
|
|
185
|
-
WHEN t.started_at >= ${Ke}
|
|
186
|
-
AND (
|
|
187
|
-
t.crewx_version IS NULL
|
|
188
|
-
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
189
|
-
OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Je}) AS INTEGER) < ${Xe})
|
|
190
|
-
)
|
|
191
|
-
THEN COALESCE(t.cached_input_tokens, 0)
|
|
192
|
-
ELSE 0
|
|
193
|
-
END
|
|
194
|
-
), 0)
|
|
195
|
-
+ COALESCE(SUM(t.output_tokens), 0)
|
|
196
|
-
) DESC
|
|
197
|
-
`).map(d=>({agentId:d.agent_id,workspaceId:d.workspace_id??null,totalTasks:d.total_tasks,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(s){throw new f("DB_ERROR","Failed to get agent usage",s)}finally{o.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=gn(sql.raw("t.status")),a=or(sql.raw("t.metadata"));return o.db.all(r?sql`
|
|
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(na));}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 na(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=wo(sql.raw("t.model"),sql.raw("t.metadata")),i=_n(sql.raw("t.status")),u=dr(sql.raw("t.metadata")),d=sql`
|
|
113
|
+
COALESCE(t.input_tokens, 0)
|
|
114
|
+
+ CASE
|
|
115
|
+
WHEN t.started_at >= ${$t}
|
|
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, ${Ut}) AS INTEGER) < ${qt})
|
|
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=_n(sql.raw("t.status")),i=dr(sql.raw("t.metadata"));return o.db.all(r?sql`
|
|
198
139
|
SELECT
|
|
199
140
|
date(t.started_at) AS date,
|
|
200
141
|
t.agent_id,
|
|
201
|
-
${
|
|
142
|
+
${i} AS unavailable_task_count,
|
|
202
143
|
COALESCE(SUM(
|
|
203
144
|
COALESCE(t.input_tokens, 0)
|
|
204
145
|
+ CASE
|
|
205
|
-
WHEN t.started_at >= ${
|
|
146
|
+
WHEN t.started_at >= ${$t}
|
|
206
147
|
AND (
|
|
207
148
|
t.crewx_version IS NULL
|
|
208
149
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
209
|
-
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, ${Ut}) AS INTEGER) < ${qt})
|
|
210
151
|
)
|
|
211
152
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
212
153
|
ELSE 0
|
|
@@ -226,15 +167,15 @@ ${r.join(`
|
|
|
226
167
|
SELECT
|
|
227
168
|
date(t.started_at) AS date,
|
|
228
169
|
t.agent_id,
|
|
229
|
-
${
|
|
170
|
+
${i} AS unavailable_task_count,
|
|
230
171
|
COALESCE(SUM(
|
|
231
172
|
COALESCE(t.input_tokens, 0)
|
|
232
173
|
+ CASE
|
|
233
|
-
WHEN t.started_at >= ${
|
|
174
|
+
WHEN t.started_at >= ${$t}
|
|
234
175
|
AND (
|
|
235
176
|
t.crewx_version IS NULL
|
|
236
177
|
OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
|
|
237
|
-
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, ${Ut}) AS INTEGER) < ${qt})
|
|
238
179
|
)
|
|
239
180
|
THEN COALESCE(t.cached_input_tokens, 0)
|
|
240
181
|
ELSE 0
|
|
@@ -249,111 +190,110 @@ ${r.join(`
|
|
|
249
190
|
AND t.started_at < ${n}
|
|
250
191
|
GROUP BY date(t.started_at), t.agent_id
|
|
251
192
|
ORDER BY date(t.started_at) ASC
|
|
252
|
-
`).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(s){throw new f("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let o=r.db.select().from(
|
|
253
|
-
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=wo(),i=_n(a.status),u=dr(a.metadata),d=sql`
|
|
194
|
+
COALESCE(${a.input_tokens}, 0)
|
|
254
195
|
+ CASE
|
|
255
|
-
WHEN ${
|
|
196
|
+
WHEN ${a.started_at} >= ${$t}
|
|
256
197
|
AND (
|
|
257
|
-
${
|
|
258
|
-
OR (${
|
|
259
|
-
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}, ${Ut}) AS INTEGER) < ${qt})
|
|
260
201
|
)
|
|
261
|
-
THEN COALESCE(${
|
|
202
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
262
203
|
ELSE 0
|
|
263
204
|
END
|
|
264
|
-
`,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`
|
|
265
206
|
SELECT
|
|
266
207
|
${s} AS provider,
|
|
267
208
|
COUNT(*) AS total_tasks,
|
|
268
209
|
${u} AS unavailable_task_count,
|
|
269
210
|
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
270
|
-
COALESCE(SUM(${
|
|
271
|
-
COALESCE(SUM(${
|
|
272
|
-
COALESCE(SUM(${
|
|
273
|
-
COALESCE(SUM(${
|
|
274
|
-
MAX(${
|
|
275
|
-
FROM ${
|
|
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}
|
|
276
217
|
${c}
|
|
277
218
|
GROUP BY ${s}
|
|
278
|
-
ORDER BY (COALESCE(SUM(${d}), 0) + COALESCE(SUM(${
|
|
279
|
-
`).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(s){throw new f("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=
|
|
280
|
-
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=wo(),i=_n(a.status),u=dr(a.metadata),d=sql`
|
|
221
|
+
COALESCE(${a.input_tokens}, 0)
|
|
281
222
|
+ CASE
|
|
282
|
-
WHEN ${
|
|
223
|
+
WHEN ${a.started_at} >= ${$t}
|
|
283
224
|
AND (
|
|
284
|
-
${
|
|
285
|
-
OR (${
|
|
286
|
-
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}, ${Ut}) AS INTEGER) < ${qt})
|
|
287
228
|
)
|
|
288
|
-
THEN COALESCE(${
|
|
229
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
289
230
|
ELSE 0
|
|
290
231
|
END
|
|
291
|
-
`,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`
|
|
292
233
|
SELECT
|
|
293
|
-
${
|
|
234
|
+
${a.model} AS model,
|
|
294
235
|
${s} AS provider,
|
|
295
236
|
COUNT(*) AS total_tasks,
|
|
296
237
|
${u} AS unavailable_task_count,
|
|
297
238
|
COALESCE(SUM(${d}), 0) AS input_tokens,
|
|
298
|
-
COALESCE(SUM(${
|
|
299
|
-
COALESCE(SUM(${
|
|
300
|
-
COALESCE(SUM(${
|
|
301
|
-
COALESCE(SUM(${
|
|
302
|
-
MAX(${
|
|
303
|
-
FROM ${
|
|
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}
|
|
304
245
|
${c}
|
|
305
|
-
GROUP BY ${
|
|
306
|
-
`),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 _=Hr(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`
|
|
307
248
|
SELECT
|
|
308
|
-
${
|
|
309
|
-
${
|
|
310
|
-
${
|
|
311
|
-
${
|
|
312
|
-
${
|
|
313
|
-
${
|
|
314
|
-
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}
|
|
315
256
|
${s}
|
|
316
|
-
ORDER BY ${
|
|
257
|
+
ORDER BY ${a.started_at} ASC
|
|
317
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`
|
|
318
|
-
COALESCE(${
|
|
259
|
+
COALESCE(${a.input_tokens}, 0)
|
|
319
260
|
+ CASE
|
|
320
|
-
WHEN ${
|
|
261
|
+
WHEN ${a.started_at} >= ${$t}
|
|
321
262
|
AND (
|
|
322
|
-
${
|
|
323
|
-
OR (${
|
|
324
|
-
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}, ${Ut}) AS INTEGER) < ${qt})
|
|
325
266
|
)
|
|
326
|
-
THEN COALESCE(${
|
|
267
|
+
THEN COALESCE(${a.cached_input_tokens}, 0)
|
|
327
268
|
ELSE 0
|
|
328
269
|
END
|
|
329
|
-
`,
|
|
270
|
+
`,i=_n(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`
|
|
330
271
|
SELECT
|
|
331
|
-
${
|
|
332
|
-
${
|
|
272
|
+
${a.caller_agent_id} AS caller_agent_id,
|
|
273
|
+
${a.agent_id} AS agent_id,
|
|
333
274
|
COUNT(*) AS task_count,
|
|
334
275
|
COALESCE(SUM(${s}), 0) AS input_tokens,
|
|
335
|
-
COALESCE(SUM(${
|
|
336
|
-
FROM ${
|
|
276
|
+
COALESCE(SUM(${a.output_tokens}), 0) AS output_tokens
|
|
277
|
+
FROM ${a}
|
|
337
278
|
${u}
|
|
338
|
-
GROUP BY ${
|
|
339
|
-
ORDER BY task_count DESC, ${
|
|
340
|
-
LIMIT ${
|
|
341
|
-
`),c=d.length>
|
|
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 ${To+1}
|
|
282
|
+
`),c=d.length>To;return {edges:d.slice(0,To).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 Uo(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 yr(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var Er=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=Uo(n.timestamp),o=join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,o);let s=`=== TASK LOG: ${n.traceId} ===
|
|
342
283
|
CrewX Version: ${this.version}
|
|
343
284
|
Mode: ${n.mode}
|
|
344
285
|
Agent: ${n.agentRef}
|
|
345
|
-
Started: ${
|
|
286
|
+
Started: ${yr(n.timestamp)}
|
|
346
287
|
Message: ${n.message}
|
|
347
288
|
|
|
348
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}
|
|
349
|
-
`,"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=yr(new Date),s=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${o}] INFO: Task ${s} in ${n.durationMs}ms
|
|
350
291
|
[${o}] INFO: Process closed with exit code: ${n.error?1:0}
|
|
351
|
-
`;appendFileSync(r,a,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};h();h();var Tt=new Map;function An(t){let e=le.resolve(t);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(n,r)=>`${r.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function Fo(t){let e=An(t);return createHash("sha256").update(e).digest("hex")}function Bo(t){let e=An(t),n=Tt.get(e);if(n!==void 0)return n;let r=e;try{let o=le.join(e,".git");if(!lstatSync(o).isFile())return Tt.set(e,r),r;let s=/^gitdir:\s*(.+?)\s*$/i.exec(readFileSync(o,"utf8").trim());if(!s)return Tt.set(e,r),r;let a=s[1],u=le.isAbsolute(a)?a:le.resolve(le.dirname(o),a),d=readFileSync(le.join(u,"commondir"),"utf8").trim();if(!d)return Tt.set(e,r),r;let c=le.isAbsolute(d)?d:le.resolve(u,d);if(le.basename(c)!==".git"||!statSync(c).isDirectory())return Tt.set(e,r),r;let l=An(realpathSync.native(e)),p=An(realpathSync.native(le.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return Tt.set(e,r),r}it();ho();h();function Hc(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let o=r.type;if(typeof o!="string")return false;let s=e?Gc[e]:void 0;return s?s(r,o):Object.values(aa).some(a=>a(r,o))}function ar(t,e){let n=t.split(`
|
|
352
|
-
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>Hc(r,e))}function we(t){return typeof t=="object"&&t!==null}function ia(t,e){if(e==="assistant"||e==="user"){let n=t.message;return we(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||we(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?we(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function $c(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:ia(t,e)}function Uc(t,e){if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return we(n)&&typeof n.type=="string"}return false}function qc(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||we(t.part):e==="text"||e==="tool_use"?we(t.part):e==="result"?typeof t.result=="string":false}function Fc(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||we(t.part)||e==="result"&&typeof t.result=="string")}function Bc(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?we(t.data):e==="result"?typeof t.result=="string":false}function jc(t,e){return e==="message"?typeof t.role=="string":e==="tool_use"?typeof t.tool_name=="string"||typeof t.tool_id=="string":e==="tool_result"?typeof t.tool_id=="string"||typeof t.status=="string":false}function Wc(t,e){return e==="available_commands"?we(t.tools)||we(t.commands):e==="usage"?we(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||we(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var aa={claude:ia,codex:Uc,opencode:qc,copilot:Bc,gemini:jc},Gc={...aa,claude:$c,opencode:Fc,grok:Wc,antigravity:()=>false};Zr();un();go();Bn();var Vc=200,Kc=200;function Jc(t){if(typeof t!="object"||t===null||!("code"in t))return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function Xc(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=Jc(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function ua(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Yc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ca(t){if(!t)return {};try{let e=JSON.parse(t);return Yc(e)?e:{}}catch{return {}}}function mn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Qc=new Set(["workflow","mcp"]),So=class extends Qe{name="sqlite-tracing";unsubs=[];dbPath;version;inheritWorktreeOwner;runnerIdentity;taskRepo;heartbeatTaskIds=new Set;ownedTaskRuns=new Map;ignoredDetachedTaskIds=new Set;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super();let n=process.env.CREWX_DB||process.env.CREWX_TRACES_DB;this.dbPath=e?.dbRoot!==void 0?join(e.dbRoot,".crewx","crewx.db"):n??join(homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown",this.inheritWorktreeOwner=e?.inheritWorktreeOwner===true;let r=e?.runnerIdentity;this.runnerIdentity={detachedRunner:r?.detachedRunner===true,assignedTaskId:r?.detachedRunner===true&&r.assignedTaskId?.trim()||void 0};}attach(e){let n=new hn({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),o=existsSync(join(r,"crewx.yaml"))||existsSync(join(r,"crewx.yml")),s=this.inheritWorktreeOwner?Bo(r):r,a=o?Fo(s):null,u=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let c=d.callerAgentId??null,l=d.parentTaskId??null,p=d.rootTraceId??d.traceId,{detachedRunner:g,assignedTaskId:m}=this.runnerIdentity,T=m??d.traceId,E=mn(d.metadata?.runEpoch),w=g?"runner":"caller",C=d.workspaceId??a,M=g?n.getTask(T):void 0,q=d.pid??null,y={...d.metadata??{provider:d.provider??"cli/claude"},ownership:w,...g&&q!==null?{providerPid:q}:{}},x=JSON.stringify(y);if(g&&M?.status==="running"&&M.pid!==null&&E===0){this.ignoredDetachedTaskIds.add(T);return}n.startTask({id:T,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",pid:g?process.pid:q,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,command:u,codingAgentCommand:d.codingAgentCommand??null,workspaceId:C,projectId:d.projectId??null,callerAgentId:c,parentTaskId:l,traceId:p,metadata:x,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:T,runEpoch:E,ownership:w,...g?{providerPid:q}:{}})&&this.recordOwnedTaskRun({taskId:T,runEpoch:E,workspaceId:C,ownership:w}),Qc.has(d.platform??"cli")||Fi(n,{taskId:T,runEpoch:E,onStopRequested:Oa=>this.handleStopRequested(n,Oa)})&&this.heartbeatTaskIds.add(T);}catch{}}),e.on("task:output",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;this.enqueueLog(c,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(c){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(c,[l],ua(l));}}),e.on("task:end",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(c))return;let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(c,mn(l)),dn(c,l)&&this.heartbeatTaskIds.delete(c),this.flushTaskLogs(c);let g=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{},...d.error.mode?{mode:d.error.mode}:{}}):null,m=d.result??null,T=!1;if(d.error&&(!m||m.trim()==="")){let E=this.recoverPartialResult(c,d,l);E&&(m=E,T=!0);}n.finishTask({id:c,status:d.error?"failed":"success",result:m,error:g,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,model:d.model??null,runEpoch:l,partialResultRecovered:T});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)dn(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let o=await Ki(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(o.status==="failed"||o.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:o.status,...o.error?{error:o.error}:{}});}catch(o){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:o instanceof Error?o.name:typeof o});}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=ua(n),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=Vc){this.flushTaskLogs(e);return}if(!r.timer){let o=setTimeout(()=>{let s=this.queues.get(e);!s||s.timer!==o||(s.timer=void 0,this.flushTaskLogs(e));},Kc);r.timer=o;}}recoverPartialResult(e,n,r){try{let o=this.taskRepo;if(!o)return;let s=o.getTask(e);if(!s||s.status!=="running"||mn(s.run_epoch)!==mn(r))return;let a=ca(s.metadata),u=typeof a.provider=="string"?a.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=Zn({taskLogRepository:o,taskId:e,provider:u,model:s.model});if(!d?.adapter.extractPartialText)return;let c=d.adapter.extractPartialText(d.stdout);return !c||!c.trim()||ar(c,u)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let o=mn(n.run_epoch),s=ca(n.metadata??null),a=s.ownership==="runner"?"runner":"caller";if(a==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let u=typeof s.providerPid=="number"&&Number.isSafeInteger(s.providerPid)&&s.providerPid>0?s.providerPid:void 0,d=a==="runner"?u:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(d!==void 0){let c;try{c=await vt(d,{signal:At});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(c.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:c.error??"process termination failed"});return}}try{let c=e.finalizeTaskStop({id:r,runEpoch:o,method:rr(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&dn(r,o)&&this.heartbeatTaskIds.delete(r);}catch(c){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:c instanceof Error?c.name:typeof c});}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,o=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(a){this.recordAppendFailure(a,r,o);}let s=this.queues.get(e);s&&s.entries.length===0&&(s.timer&&clearTimeout(s.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let o=Xc(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[o.code]=(this.metrics.appendFailureByCode[o.code]??0)+1,this.metrics.appendFailureByCause[o.cause]=(this.metrics.appendFailureByCause[o.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:o.code,cause:o.cause,pendingEntries:n.length,pendingBytes:r});}};h();h();h();dt();wt();yt();it();St();er();function ur(t){return {...t,status:mt(t)}}function rl({metadata:t,...e}){return {...e,status:mt({...e,metadata:t})}}var $t=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function _n(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function ol(t){let n=_n(t).threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {priority:null,state:null};let r=n;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}var cr=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(n))throw new f("NOT_FOUND","Database not found");let r=W(n);if(e)try{Ne(r.db,n);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,n){return e.db.select({id:Et.id}).from(Et).where(eq(Et.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
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 kt=new Map;function On(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 Wo(t){let e=On(t);return createHash("sha256").update(e).digest("hex")}function Go(t){let e=On(t),n=kt.get(e);if(n!==void 0)return n;let r=e;try{let o=le.join(e,".git");if(!lstatSync(o).isFile())return kt.set(e,r),r;let s=/^gitdir:\s*(.+?)\s*$/i.exec(readFileSync(o,"utf8").trim());if(!s)return kt.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 kt.set(e,r),r;let c=le.isAbsolute(d)?d:le.resolve(u,d);if(le.basename(c)!==".git"||!statSync(c).isDirectory())return kt.set(e,r),r;let l=On(realpathSync.native(e)),p=On(realpathSync.native(le.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return kt.set(e,r),r}ot();_o();bt();to();pn();mo();Gn();var Yc=200,Qc=200;function Zc(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 el(t){let e=t instanceof f?t.code:void 0,n=t instanceof f?t.cause:t,r=Zc(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function la(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function tl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pa(t){if(!t)return {};try{let e=JSON.parse(t);return tl(e)?e:{}}catch{return {}}}function Tn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var nl=new Set(["workflow","mcp"]),vo=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 kn({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?Go(r):r,i=o?Wo(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=Tn(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}),nl.has(d.platform??"cli")||zi(n,{taskId:m,runEpoch:w,onStopRequested:xa=>this.handleStopRequested(n,xa)})&&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],la(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,Tn(l)),ln(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)ln(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 Zi(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+=la(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>=Yc){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));},Qc);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"||Tn(s.run_epoch)!==Tn(r))return;let i=pa(s.metadata),u=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=rr({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=Tn(n.run_epoch),s=pa(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 At(d,{signal:It});}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:ar(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&ln(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=el(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();Tt();wt();ot();Rt();or();function pr(t){return {...t,status:gt(t)}}function al({metadata:t,...e}){return {...e,status:gt({...e,metadata:t})}}var Bt=class extends f{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function wn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function dl(t){let n=wn(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 fr=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:yt.id}).from(yt).where(eq(yt.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
353
293
|
SELECT 1 FROM tasks parent
|
|
354
294
|
WHERE parent.id = ${e}.parent_task_id
|
|
355
295
|
AND parent.thread_id = ${e}.thread_id
|
|
356
|
-
)`)}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`
|
|
357
297
|
SELECT
|
|
358
298
|
count(*) AS cnt,
|
|
359
299
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -364,13 +304,13 @@ Message: ${n.message}
|
|
|
364
304
|
WHERE child.thread_id = ${e}
|
|
365
305
|
AND ${this.topLevelTaskPredicateSql()}
|
|
366
306
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
367
|
-
`);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`
|
|
368
308
|
SELECT DISTINCT child.agent_id FROM tasks child
|
|
369
309
|
WHERE child.thread_id = ${e}
|
|
370
310
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
371
311
|
AND ${this.topLevelTaskPredicateSql()}
|
|
372
312
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
373
|
-
`);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`
|
|
374
314
|
SELECT * FROM (
|
|
375
315
|
SELECT child.*,
|
|
376
316
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -387,7 +327,7 @@ Message: ${n.message}
|
|
|
387
327
|
AND ${this.topLevelTaskPredicateSql()}
|
|
388
328
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
389
329
|
ORDER BY child.started_at ASC
|
|
390
|
-
`);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(pr(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(pr(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(pr);return {task:pr(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`
|
|
391
331
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
392
332
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
393
333
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -397,7 +337,7 @@ Message: ${n.message}
|
|
|
397
337
|
AND ${this.topLevelTaskPredicateSql()}
|
|
398
338
|
${n?sql`AND child.workspace_id = ${n}`:sql``}
|
|
399
339
|
ORDER BY child.started_at ASC
|
|
400
|
-
`}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let
|
|
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(al(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`
|
|
401
341
|
UPDATE threads
|
|
402
342
|
SET first_message = COALESCE(first_message, ${n}),
|
|
403
343
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
|
|
@@ -405,11 +345,11 @@ Message: ${n.message}
|
|
|
405
345
|
message_count = message_count + 1,
|
|
406
346
|
updated_at = ${s}
|
|
407
347
|
WHERE id = ${e}
|
|
408
|
-
`),c},{behavior:"immediate"})}}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(_).set({last_message:n,updated_at:s}).where(eq(_.id,e)).run();}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};n.title!==void 0&&(o.title=n.title,o.title_locked=1),n.titleLocked!==void 0&&(o.title_locked=n.titleLocked?1:0),r.db.update(_).set(o).where(eq(_.id,e)).run();}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let o=n;if(!o||typeof o!="object"||Array.isArray(o))return new $t("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(d=>d!=="priority"&&d!=="state"))return new $t("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let a=o;if(a.priority===void 0&&a.state===void 0)return new $t("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [a.priority,a.state])if(d!=null&&(typeof d!="string"||d.length===0))return new $t("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let u=this.openHandle(true);try{let d=r?and(eq(_.id,e),eq(_.workspace_id,r)):eq(_.id,e);return u.db.transaction(c=>{let l=c.select({metadata:_.metadata}).from(_).where(d).get();if(!l)return null;let p=_n(l.metadata),g=p.threadTitle,m=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};a.priority===null?delete m.priority:a.priority!==void 0&&(m.priority=a.priority),a.state===null?delete m.state:a.state!==void 0&&(m.state=a.state),Object.keys(m).length>0?p.threadTitle=m:delete p.threadTitle;let T=Object.keys(p).length>0?JSON.stringify(p):null,E=new Date().toISOString();c.update(_).set({metadata:T,updated_at:E}).where(d).run();let w=c.select({metadata:_.metadata}).from(_).where(d).get();if(!w)throw new f("DB_ERROR","Thread-title metadata update could not be read back");let C=ol(w.metadata);return {threadId:e,priority:C.priority,state:C.state}},{behavior:"immediate"})}catch(d){throw d instanceof f?d:new f("DB_ERROR","Failed to patch thread-title metadata",d)}finally{u.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?and(eq(_.id,e),eq(_.workspace_id,n)):eq(_.id,e);return r.db.transaction(s=>{let a=s.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(o).get();if(!a)return null;let u=a.pinned?0:1,d=_n(a.metadata);if(u){let c=n?and(eq(_.pinned,1),eq(_.workspace_id,n)):eq(_.pinned,1),l=s.select({metadata:_.metadata}).from(_).where(c).all(),p=null;for(let g of l){let m=_n(g.metadata);typeof m.pinOrder=="number"&&(p===null||m.pinOrder<p)&&(p=m.pinOrder);}d.pinOrder=p===null?0:p-1;}else delete d.pinOrder;return s.update(_).set({pinned:u,metadata:Object.keys(d).length>0?JSON.stringify(d):null}).where(o).run(),{pinned:!!u}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(o=>{for(let s=0;s<e.length;s++){let a=n?and(eq(_.id,e[s]),eq(_.workspace_id,n)):eq(_.id,e[s]),u=o.select({metadata:_.metadata}).from(_).where(a).get();if(!u)continue;let d=_n(u.metadata);d.pinOrder=s+1,o.update(_).set({metadata:JSON.stringify(d)}).where(a).run();}},{behavior:"immediate"});}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?and(eq(_.id,e),eq(_.workspace_id,n)):eq(_.id,e),s=r.db.select({starred:_.starred}).from(_).where(o).get();if(!s)return null;let a=s.starred?0:1;return r.db.update(_).set({starred:a}).where(o).run(),{starred:!!a}}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let a=this.openHandle(true);try{let u=n?and(eq(_.id,e),eq(_.workspace_id,n)):eq(_.id,e);return a.db.transaction(c=>{let l=c.select({metadata:_.metadata}).from(_).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},g=p.overdrive??{},m=o?.defaultTurns??g.defaultTurns??3,T=o?.updatedBy??"ui",E=new Date().toISOString(),w,C,M,q;switch(r){case "enable-count":{let y=o?.turns??m,x=o?.consumeCurrent?Math.max(y-1,0):y;w=x>0?"count":"off",C=x,M=!0,q="count";break}case "enable-latch":{w="latch",C=0,M=!0,q="latch";break}case "disable":{w="off",C=0,M=!1;break}default:{let y=g.state??"off",x=typeof g.remaining=="number"?g.remaining:0;if(y==="count"&&x>0){let A=x-1;A<=0?(w="off",C=0):(w="count",C=A),M=!0,q="count";}else y==="latch"?(w="latch",C=0,M=!0,q="latch"):(w="off",C=0,M=!1);break}}return p.overdrive={state:w,remaining:C,defaultTurns:m,updatedAt:E,updatedBy:T},c.update(_).set({metadata:JSON.stringify(p),updated_at:E}).where(u).run(),{applied:M,appliedMode:q,state:w,remaining:C}},{behavior:"immediate"})}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to resolve overdrive",u)}finally{a.close();}}};h();dt();wt();yt();it();h();var Io="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function sl(t){let e=randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let o=e[r];o<248&&(n+=Io[o%62]);}for(;n.length<t;)n+=Io[randomBytes(1)[0]%62];return n}function kn(t){return `${t}_${sl(8)}`}function ha(t,e){let{createHash:n}=kt("crypto"),r=n("sha256").update(e).digest(),o=Buffer.alloc(8);for(let a=0;a<32;a++)o[a%8]^=r[a];let s="";for(let a of o)s+=Io[a%62];return `${t}_${s}`}St();h();var il=["urgent","high","medium","low"],al=["investigating","in-progress","in-review","on-hold","done"],ma="custom:";var dl=new Set(il),ul=new Set(al);function Ao(t){return typeof t=="string"&&dl.has(t)}function vo(t){if(typeof t!="string")return false;if(ul.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(ma))return false;let e=t.slice(ma.length);return e.length>=1&&e.length<=20}function _a(t){if(!t)return null;try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function Oo(t){let e=_a(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return Ao(r.priority)&&(o.priority=r.priority),vo(r.state)&&(o.state=r.state),o}function ka(t,e){let n=_a(t)??{},r={...Oo(t)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete n.threadTitle:n.threadTitle=r,Object.keys(n).length===0?null:JSON.stringify(n)}er();var gl="regeneration_replaced";var hl="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var ml="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Co=class extends f{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=o;}},In=class extends Co{},No=class extends f{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},_l=new Set(ws),kl=new Set(Ts),Tl=new Set(ys),wl=new Set(Es),yl=50,wa=100,ya=280,Ea=40,El=new Set(Rs),lr=["queued","running"];function xo(t){return El.has(t)}function B(t){throw new f("VALIDATION",t)}function Ce(t){throw new f("NOT_FOUND",t)}function N(t,e){(typeof t!="string"||t.trim().length===0)&&B(`${e} is required`);}function wn(t={}){let e=t.actor??t,n=e.actorType??"system";return _l.has(n)||B(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&B("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Rl(t){N(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&N(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&B("title must not be empty"),t.title.length>120&&B("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Ao(t.priority)&&B(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!vo(t.state)&&B(`invalid state: ${String(t.state)}`);}function Sl(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&B("beforeSeq and afterSeq cannot be used together");for(let[n,r]of [["beforeSeq",t.beforeSeq],["afterSeq",t.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&B(`${n} must be a non-negative integer`);let e=t.limit??yl;return (!Number.isInteger(e)||e<1||e>wa)&&B(`limit must be between 1 and ${wa}`),e}function Po(t){typeof t!="string"&&B("text is required");let e=t.trim();return e.length===0&&B("text must not be empty"),e.length>ya&&B(`text must be at most ${ya} characters`),e}function Ye(t,e){return N(t??"",e),t}function Do(t){wl.has(t)||B(`invalid highlight kind: ${String(t)}`);}function Il(t){Tl.has(t)||B(`invalid highlight source: ${String(t)}`);}function Al(t){N(t.threadId,"threadId"),N(t.workspaceId,"workspaceId");let e=t.source??"manual";Il(e),Do(t.kind);let n=Po(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&o&&r===o?r:void 0),p=Ye(l,"taskId");return (r!==p||o!==p)&&B("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Ye(r,"coversFromTaskId"),a=Ye(o,"coversToTaskId"),u=t.sourceTaskId??s,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return Ye(u??void 0,"sourceTaskId"),Ye(d??void 0,"detectorVersion"),Ye(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:a,agentId:t.agentId??null,sourceTaskId:u,detectorVersion:d,contentFingerprint:c}}function vl(t,e){(!t||typeof t!="object")&&B(`candidates[${e}] is required`),Do(t.kind);let n=Po(t.text),r=Ye(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Ye(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Ye(t.coversToTaskId,`candidates[${e}].coversToTaskId`),a=t.contentFingerprint?.trim()||ha("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return N(a,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:a}}function Ol(t){Array.isArray(t)||B("candidates must be an array"),t.length>Ea&&B(`candidates must contain at most ${Ea} items`);let e=new Map;for(let[n,r]of t.entries()){let o=vl(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function Sn(t){let e=Oo(t.metadata);return {threadId:t.id,workspaceId:t.workspace_id,title:t.title,priority:e.priority??null,state:e.state??null,metadata:t.metadata,titleLocked:t.title_locked===1,updatedAt:t.updated_at}}function bl(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&B("event payload must be a JSON object"),e}catch(e){throw new f("VALIDATION","event payload must be JSON serializable",e)}}function yn(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${U.seq}), 0)`}).from(U).where(eq(U.thread_id,e)).get()?.maxSeq??0}function En(t,e){return !!t.select({id:U.id}).from(U).where(eq(U.thread_id,e)).limit(1).get()}function _t(t,e){kl.has(e.type)||B(`invalid thread event type: ${String(e.type)}`);let n=kn("the");t.insert(U).values({id:n,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:bl(e.payload),created_at:e.createdAt}).run();let r=t.select().from(U).where(eq(U.id,n)).get();if(!r)throw new f("DB_ERROR","Thread event insert did not return a row");return r}function Rn(t,e,n,r,o){let s=Sn(e);_t(t,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function fr(t){return {highlightId:t.id,source:t.source,kind:t.kind,status:t.status,coversFromTaskId:t.covers_from_task_id,coversToTaskId:t.covers_to_task_id,revision:t.revision,...t.dismissed_at===null?{}:{dismissedAt:t.dismissed_at}}}function pr(t,e,n,r,o,s,a){let u=o==="thread.highlight.created"?fr(e):{before:a?fr({...e,...a,id:e.id}):void 0,after:fr(e)};return _t(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:u})}function xl(t,e,n,r,o,s){return _t(t,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:fr(e),...s??{}}})}var gr=class extends ke{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!existsSync(n))throw new f("NOT_FOUND","Database not found");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=W(n);if(e)try{Ne(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=eq(_.id,n),s=r===void 0?o:r===null?and(o,isNull(_.workspace_id)):and(o,eq(_.workspace_id,r));return e.select().from(_).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(H).where(eq(H.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(N(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:_.workspace_id}).from(_).where(eq(_.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof f?r:new f("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(N(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?Sn(o):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Rl(e);let n=wn(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.findThread(s,e.threadId,e.workspaceId);a||Ce(`Thread ${e.threadId} not found`);let u=Sn(a),d=e.title!==void 0,c=d&&e.title!==u.title,l=d&&a.title_locked!==1,p=e.priority!==void 0&&e.priority!==u.priority,g=e.state!==void 0&&e.state!==u.state,m=c||p||g;if(!m&&!l)return u;let T=a.metadata;(p||g)&&(T=ka(a.metadata,{priority:e.priority,state:e.state}));let E={};if(m&&(E.metadata=T,E.updated_at=r),c&&(E.title=e.title),d&&(E.title_locked=1),s.update(_).set(E).where(e.workspaceId===void 0?eq(_.id,e.threadId):e.workspaceId===null?and(eq(_.id,e.threadId),isNull(_.workspace_id)):and(eq(_.id,e.threadId),eq(_.workspace_id,e.workspaceId))).run(),!m){let M={...a,title_locked:1};return Sn(M)}let w=yn(s,a.id)+1;En(s,a.id)||(Rn(s,a,n,r,w),w+=1),c&&(_t(s,{threadId:a.id,seq:w,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),w+=1),p&&(_t(s,{threadId:a.id,seq:w,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),w+=1),g&&_t(s,{threadId:a.id,seq:w,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let C={...a,title:c?e.title:a.title,metadata:T,title_locked:d?1:a.title_locked,updated_at:r};return Sn(C)},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if(N(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:sql`COALESCE(MAX(${U.seq}), 0)`}).from(U).where(eq(U.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(N(e,"threadId"),N(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({taskId:i.id,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.started_at,completedAt:i.completed_at}).from(i).where(and(eq(i.thread_id,e),eq(i.workspace_id,n),inArray(i.status,[...Di,"completed","done","error"]),or$1(isNull(i.parent_task_id),eq(i.parent_task_id,"")),sql`${i.result} IS NOT NULL AND length(trim(${i.result})) > 0`)).orderBy(asc(i.started_at),asc(i.id)).all().map(a=>({taskId:a.taskId,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.startedAt,completedAt:a.completedAt})):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.requestId,"requestId"),N(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&N(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||Ce(`Thread ${e.threadId} not found`);let a=o.select().from(H).where(and(eq(H.thread_id,s.id),eq(H.request_id,e.requestId))).orderBy(desc(H.requested_at),desc(H.id)).limit(1).get();if(a)return {run:a,created:!1};let u=o.select().from(H).where(and(eq(H.thread_id,s.id),inArray(H.status,lr))).orderBy(asc(H.requested_at),asc(H.id)).limit(1).get();if(u)throw new No(u);let d=e.runId??kn("thr");o.insert(H).values({id:d,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let c=o.select().from(H).where(eq(H.id,d)).get();if(!c)throw new f("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if(N(e,"runId"),n!==void 0&&N(n,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(N(e,"threadId"),N(n,"workspaceId"),N(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(H).where(and(eq(H.thread_id,e),eq(H.request_id,r))).orderBy(desc(H.requested_at),desc(H.id)).limit(1).get()??null:null}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){N(e,"runId"),n!==void 0&&N(n,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.findRegenerationRun(s,e,n);if(a||Ce(`Highlight regeneration run ${e} not found`),xo(a.status)||B(`invalid highlight regeneration status: ${a.status}`),a.status!=="queued")return a;s.update(H).set({status:"running",started_at:r}).where(and(eq(H.id,a.id),eq(H.status,"queued"))).run();let u=s.select().from(H).where(eq(H.id,a.id)).get();if(!u)throw new f("DB_ERROR","Highlight regeneration run start did not return a row");return u},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){N(e.runId,"runId"),N(e.errorCode,"errorCode"),e.workspaceId!==void 0&&N(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||Ce(`Highlight regeneration run ${e.runId} not found`),xo(s.status)||B(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(H).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(H.id,s.id),inArray(H.status,lr))).run();let a=o.select().from(H).where(eq(H.id,s.id)).get();if(!a)throw new f("DB_ERROR","Highlight regeneration run failure did not return a row");return a},{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=hl){N(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(H).set({status:"failed",completed_at:n,error_code:e}).where(inArray(H.status,lr)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){N(e.runId,"runId"),N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.detectorVersion,"detectorVersion");let n=Ol(e.candidates),r=wn(e),o=this.openHandle(true),s=false;try{return o.db.transaction(a=>{let u=this.findRegenerationRun(a,e.runId,e.workspaceId);if((!u||u.thread_id!==e.threadId)&&Ce(`Highlight regeneration run ${e.runId} not found`),xo(u.status)||B(`invalid highlight regeneration status: ${u.status}`),u.status==="failed")throw new f("CONFLICT","Highlight regeneration run has already failed");if(u.status==="completed")return {run:u,deletedCount:0,createdCount:0,previousAutoCount:u.previous_auto_count??0,newAutoCount:u.new_auto_count??0};s=!0;let d=this.findThread(a,e.threadId,e.workspaceId);d||Ce(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&B("detectorVersion does not match the regeneration run");let c=a.select().from(P).where(eq(P.thread_id,d.id)).orderBy(asc(P.created_at),asc(P.id)).all(),l=new Set(n.map(A=>A.contentFingerprint)),p=c.filter(A=>A.source==="auto"&&A.status==="active"&&A.revision===0&&!l.has(A.content_fingerprint??"")),g=c.filter(A=>A.source==="auto"&&A.status==="active").length,m=new Set(c.filter(A=>!p.includes(A)&&A.content_fingerprint).map(A=>A.content_fingerprint)),T=n.filter(A=>!m.has(A.contentFingerprint)),E=new Date().toISOString(),w=yn(a,d.id)+1;En(a,d.id)||(Rn(a,d,r,E,w),w+=1);for(let A of p)a.delete(P).where(eq(P.id,A.id)).run(),xl(a,A,r,E,w,{runId:e.runId,reason:gl}),w+=1;let C=0,M=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let A of T){let Q=kn("thl");a.insert(P).values({id:Q,thread_id:d.id,source:"auto",kind:A.kind,status:"active",text:A.text,covers_from_task_id:A.coversFromTaskId,covers_to_task_id:A.coversToTaskId,revision:0,created_at:E,updated_at:E,agent_id:M,source_task_id:A.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:A.contentFingerprint,dismissed_at:null}).run();let _e=a.select().from(P).where(eq(P.id,Q)).get();if(!_e)throw new f("DB_ERROR","Regenerated highlight insert did not return a row");pr(a,_e,r,E,"thread.highlight.created",w),w+=1,C+=1;}let y=a.select().from(P).where(eq(P.thread_id,d.id)).all().filter(A=>A.source==="auto"&&A.status==="active").length;_t(a,{threadId:d.id,seq:w,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:E,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:y,deletedCount:p.length,createdCount:C}}),a.update(H).set({status:"completed",started_at:u.started_at??E,completed_at:E,error_code:null,previous_auto_count:g,new_auto_count:y}).where(and(eq(H.id,u.id),inArray(H.status,lr))).run();let x=a.select().from(H).where(eq(H.id,u.id)).get();if(!x)throw new f("DB_ERROR","Highlight regeneration completion did not return a row");return {run:x,deletedCount:p.length,createdCount:C,previousAutoCount:g,newAutoCount:y}},{behavior:"immediate"})}catch(a){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:ml});}catch{}throw a instanceof f?a:new f("DB_ERROR","Failed to complete highlight regeneration",a)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;N(o.threadId,"threadId"),N(o.workspaceId,"workspaceId");let s=Sl(o);if(!existsSync(this.resolveDbPath()))return null;let a=this.openHandle(false);try{if(!this.findThread(a.db,o.threadId,o.workspaceId))return null;let u=a.db.select({maxSeq:sql`COALESCE(MAX(${U.seq}), 0)`}).from(U).where(eq(U.thread_id,o.threadId)).get()?.maxSeq??0,d;o.beforeSeq!==void 0?d=a.db.select().from(U).where(and(eq(U.thread_id,o.threadId),lt$1(U.seq,o.beforeSeq))).orderBy(desc(U.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?d=a.db.select().from(U).where(and(eq(U.thread_id,o.threadId),sql`${U.seq} > ${o.afterSeq}`)).orderBy(asc(U.seq)).limit(s+1).all():d=a.db.select().from(U).where(eq(U.thread_id,o.threadId)).orderBy(desc(U.seq)).limit(s+1).all().reverse();let c=d.length>s,l=o.afterSeq!==void 0?d.slice(0,s):c?d.slice(1):d,p=!1,g=l[0];return g&&(p=!!a.db.select({id:U.id}).from(U).where(and(eq(U.thread_id,o.threadId),lt$1(U.seq,g.seq))).limit(1).get()),{items:l,latestSeq:u,hasMoreOlder:p}}catch(u){throw u instanceof f?u:new f("DB_ERROR","Failed to list thread timeline",u)}finally{a.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=Al(e),r=wn(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(a=>{let u=this.findThread(a,e.threadId,e.workspaceId);if(u||Ce(`Thread ${e.threadId} not found`),n.source==="auto"){let g=a.select().from(P).where(and(eq(P.thread_id,e.threadId),eq(P.source_task_id,n.sourceTaskId),eq(P.detector_version,n.detectorVersion),eq(P.content_fingerprint,n.contentFingerprint))).orderBy(asc(P.created_at),asc(P.id)).limit(1).get();if(g)return g}let d=e.id??kn("thl"),c={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};a.insert(P).values(c).run();let l=a.select().from(P).where(eq(P.id,d)).get();if(!l)throw new f("DB_ERROR","Highlight insert did not return a row");let p=yn(a,u.id)+1;return En(a,u.id)||(Rn(a,u,r,o,p),p+=1),pr(a,l,r,o,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(a){throw a instanceof f?a:new f("DB_ERROR","Failed to create thread highlight",a)}finally{s.close();}}updateHighlight(e){N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&B("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&B("highlight update requires at least one field"),e.kind!==void 0&&Do(e.kind);let n=e.text===void 0?void 0:Po(e.text),r=wn(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(a=>{let u=this.findThread(a,e.threadId,e.workspaceId);u||Ce(`Thread ${e.threadId} not found`);let d=a.select().from(P).where(and(eq(P.id,e.highlightId),eq(P.thread_id,u.id))).limit(1).get();if(d||Ce(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new In(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new In(u.id,d.id,e.expectedRevision,d.revision);let c=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,g=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||g.length===0)&&B("highlight projection is incomplete");let m=c!==d.kind||l!==d.text||p!==d.covers_from_task_id||g!==d.covers_to_task_id,T=r.actorType==="user"&&d.source==="auto"&&m?"manual":d.source;if(!(m||T!==d.source))return d;let w=d.revision+1;a.update(P).set({source:T,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:g,revision:w,updated_at:o}).where(and(eq(P.id,d.id),eq(P.revision,d.revision))).run();let C=a.select().from(P).where(eq(P.id,d.id)).get();if(!C)throw new f("DB_ERROR","Highlight update did not return a row");let M=yn(a,u.id)+1;return En(a,u.id)||(Rn(a,u,r,o,M),M+=1),pr(a,C,r,o,"thread.highlight.updated",M,d),C},{behavior:"immediate"})}catch(a){throw a instanceof f?a:new f("DB_ERROR","Failed to update thread highlight",a)}finally{s.close();}}dismissHighlight(e){N(e.threadId,"threadId"),N(e.workspaceId,"workspaceId"),N(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&B("expectedRevision must be a non-negative integer");let n=wn(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let a=this.findThread(s,e.threadId,e.workspaceId);a||Ce(`Thread ${e.threadId} not found`);let u=s.select().from(P).where(and(eq(P.id,e.highlightId),eq(P.thread_id,a.id))).limit(1).get();if(u||Ce(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new In(a.id,u.id,e.expectedRevision,u.revision);if(u.status==="dismissed")return u;let d=u.revision+1;s.update(P).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(and(eq(P.id,u.id),eq(P.revision,u.revision))).run();let c=s.select().from(P).where(eq(P.id,u.id)).get();if(!c)throw new f("DB_ERROR","Highlight dismissal did not return a row");let l=yn(s,a.id)+1;return En(s,a.id)||(Rn(s,a,n,r,l),l+=1),pr(s,c,n,r,"thread.highlight.deleted",l,u),c},{behavior:"immediate"})}catch(s){throw s instanceof f?s:new f("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(N(e,"threadId"),N(n,"workspaceId"),r.taskId!==void 0&&N(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&N(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&N(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,n))return null;let a=o.db.select().from(P).where(and(eq(P.thread_id,e),eq(P.status,"active"))).orderBy(asc(P.created_at),asc(P.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return a;let u=o.db.all(sql`
|
|
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 Bt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(d=>d!=="priority"&&d!=="state"))return new Bt("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 Bt("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 Bt("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=wn(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=dl(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=wn(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 _=wn(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=wn(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();Tt();wt();ot();h();var bo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ul(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+=bo[o%62]);}for(;n.length<t;)n+=bo[randomBytes(1)[0]%62];return n}function yn(t){return `${t}_${ul(8)}`}function _a(t,e){let{createHash:n}=_t("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+=bo[i%62];return `${t}_${s}`}Rt();h();var cl=["urgent","high","medium","low"],ll=["investigating","in-progress","in-review","on-hold","done"],ka="custom:";var pl=new Set(cl),fl=new Set(ll);function Oo(t){return typeof t=="string"&&pl.has(t)}function xo(t){if(typeof t!="string")return false;if(fl.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(ka))return false;let e=t.slice(ka.length);return e.length>=1&&e.length<=20}function Ta(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 Co(t){let e=Ta(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return Oo(r.priority)&&(o.priority=r.priority),xo(r.state)&&(o.state=r.state),o}function wa(t,e){let n=Ta(t)??{},r={...Co(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)}or();var kl="regeneration_replaced";var Tl="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var wl="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Do=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;}},bn=class extends Do{},Lo=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;}},yl=new Set(Rs),El=new Set(Es),Rl=new Set(Ss),Sl=new Set(Is),Il=50,Ea=100,Ra=280,Sa=40,Al=new Set(As),gr=["queued","running"];function Po(t){return Al.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 Rn(t={}){let e=t.actor??t,n=e.actorType??"system";return yl.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 vl(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&&!Oo(t.priority)&&B(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!xo(t.state)&&B(`invalid state: ${String(t.state)}`);}function bl(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??Il;return (!Number.isInteger(e)||e<1||e>Ea)&&B(`limit must be between 1 and ${Ea}`),e}function Mo(t){typeof t!="string"&&B("text is required");let e=t.trim();return e.length===0&&B("text must not be empty"),e.length>Ra&&B(`text must be at most ${Ra} characters`),e}function Je(t,e){return N(t??"",e),t}function Ho(t){Sl.has(t)||B(`invalid highlight kind: ${String(t)}`);}function Ol(t){Rl.has(t)||B(`invalid highlight source: ${String(t)}`);}function xl(t){N(t.threadId,"threadId"),N(t.workspaceId,"workspaceId");let e=t.source??"manual";Ol(e),Ho(t.kind);let n=Mo(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 Cl(t,e){(!t||typeof t!="object")&&B(`candidates[${e}] is required`),Ho(t.kind);let n=Mo(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()||_a("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 Nl(t){Array.isArray(t)||B("candidates must be an array"),t.length>Sa&&B(`candidates must contain at most ${Sa} items`);let e=new Map;for(let[n,r]of t.entries()){let o=Cl(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function vn(t){let e=Co(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 Pl(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 Sn(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${q.seq}), 0)`}).from(q).where(eq(q.thread_id,e)).get()?.maxSeq??0}function In(t,e){return !!t.select({id:q.id}).from(q).where(eq(q.thread_id,e)).limit(1).get()}function ht(t,e){El.has(e.type)||B(`invalid thread event type: ${String(e.type)}`);let n=yn("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:Pl(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 An(t,e,n,r,o){let s=vn(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 mr(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 hr(t,e,n,r,o,s,i){let u=o==="thread.highlight.created"?mr(e):{before:i?mr({...e,...i,id:e.id}):void 0,after:mr(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 Dl(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:mr(e),...s??{}}})}var _r=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?vn(o):null}catch(o){throw o instanceof f?o:new f("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){vl(e);let n=Rn(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=vn(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=wa(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 vn(L)}let k=Sn(s,i.id)+1;In(s,i.id)||(An(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 vn(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,[...Ui,"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,gr))).orderBy(asc($.requested_at),asc($.id)).limit(1).get();if(u)throw new Lo(u);let d=e.runId??yn("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`),Po(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`),Po(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,gr))).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=Tl){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,gr)).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=Nl(e.candidates),r=Rn(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`),Po(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=Sn(i,d.id)+1;In(i,d.id)||(An(i,d,r,w,k),k+=1);for(let b of p)i.delete(P).where(eq(P.id,b.id)).run(),Dl(i,b,r,w,k,{runId:e.runId,reason:kl}),k+=1;let C=0,L=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let b of m){let Q=yn("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");hr(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,gr))).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:wl});}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=bl(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=xl(e),r=Rn(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??yn("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=Sn(i,u.id)+1;return In(i,u.id)||(An(i,u,r,o,p),p+=1),hr(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&&Ho(e.kind);let n=e.text===void 0?void 0:Mo(e.text),r=Rn(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 bn(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new bn(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=Sn(i,u.id)+1;return In(i,u.id)||(An(i,u,r,o,L),L+=1),hr(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=Rn(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 bn(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=Sn(s,i.id)+1;return In(s,i.id)||(An(s,i,n,r,l),l+=1),hr(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`
|
|
409
349
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
410
350
|
ORDER BY started_at ASC, id ASC
|
|
411
|
-
`),d=new Map(u.map((g,
|
|
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();Tt();wt();ot();Rt();Pr();var J=class extends f{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Aa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function jl(){let t=randomBytes(16),e="";for(let n of t)e+=Aa[n%Aa.length];return e.slice(0,12)}function va(){return `c_${jl()}`}function Wl(t){return typeof t=="string"&&Cr.includes(t)}function Gl(t){return typeof t=="string"&&Nr.includes(t)}function zt(t){if(!Wl(t))throw new J("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function ba(t){if(!Gl(t))throw new J("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function Oa(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 Vt(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 kr(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 Tr=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(zt(e),Vt(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(zt(e),Vt(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(zt(n),Vt(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)kr(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(zt(e),kr(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){Vt(e.workspaceId);let n=Oa(e.name);ba(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=va();for(;o.select({code:I.code}).from(I).where(and(eq(I.code_group,"THREAD_STATE"),eq(I.code,d))).limit(1).get();)d=va();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(zt(e.group),kr(e.code),Vt(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:Oa(e.name);e.color!==void 0&&ba(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(zt(e),kr(n),Vt(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")}};bt();h();var mt={threadContext:"crewx_thread_context",apps:"apps",crewxUiState:"crewx_ui_state"};function Kl(t){return t.replace(new RegExp(`<${mt.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${mt.threadContext}>`,"g"),"").replace(new RegExp(`<${mt.apps}\\b[^>]*>[\\s\\S]*?<\\/${mt.apps}>`,"g"),"").replace(new RegExp(`<${mt.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${mt.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
|
|
412
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(`
|
|
413
|
-
`).trim()}function
|
|
414
|
-
`):o&&typeof o=="object"&&o.result!==void 0&&(r=o.result||"");}catch{r=
|
|
415
|
-
`)[0].slice(0,200)),n.push({id:`${r.id}-assistant`,text:
|
|
353
|
+
`).trim()}function Jl(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 Xl(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=Kl(r);}return r}var wr=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new fr({dbPath:this.dbPath})}getThreadHistoryRepo(){return new _r({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 Tr({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=Jl(r.metadata),i=Xl(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 $o=class extends Xe{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new wr(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{$o as ConversationPlugin,Er as FileLoggerPlugin,vo as SqliteTracingPlugin};
|