@crewx/sdk 0.9.0-rc.111 → 0.9.0-rc.112
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/index.js +152 -151
- package/dist/esm/plugins/index.js +40 -40
- package/dist/esm/repository/index.js +17 -17
- package/dist/index.d.ts +3 -3
- package/dist/index.js +151 -150
- package/dist/plugins/index.js +37 -37
- package/dist/provider/cli/protocol-envelope.d.ts +1 -0
- package/dist/utils/crewx-executable.d.ts +23 -1
- package/package.json +1 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import*as Ce from'path';import Ce__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as ha from'fs';import ha__default,{existsSync,mkdirSync,readFileSync,statfsSync,realpathSync,statSync}from'fs';import li,{homedir}from'os';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,index,check,primaryKey,getTableConfig,real,uniqueIndex,unique}from'drizzle-orm/sqlite-core';import {sql,eq,asc,desc,or as or$1,isNull,and,ne,inArray,lt as lt$1,notLike,like,gte,isNotNull,gt,lte}from'drizzle-orm';import {spawn}from'child_process';var ru=Object.defineProperty;var ht=(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 x=(t,e)=>()=>(t&&(e=t(t=0)),e);var ou=(t,e)=>{for(var n in e)ru(t,n,{get:e[n],enumerable:true});};var au,du,
|
|
1
|
+
import*as Ce from'path';import Ce__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as ha from'fs';import ha__default,{existsSync,mkdirSync,readFileSync,statfsSync,realpathSync,statSync}from'fs';import li,{homedir}from'os';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,index,check,primaryKey,getTableConfig,real,uniqueIndex,unique}from'drizzle-orm/sqlite-core';import {sql,eq,asc,desc,or as or$1,isNull,and,ne,inArray,lt as lt$1,notLike,like,gte,isNotNull,gt,lte}from'drizzle-orm';import {spawn}from'child_process';var ru=Object.defineProperty;var ht=(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 x=(t,e)=>()=>(t&&(e=t(t=0)),e);var ou=(t,e)=>{for(var n in e)ru(t,n,{get:e[n],enumerable:true});};var au,du,S,m=x(()=>{au=()=>fileURLToPath(import.meta.url),du=()=>Ce__default.dirname(au()),S=du();});function ci(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 pu(t,e){let n=ci(t),r=ci(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Ge(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&pu(t,join(li.homedir(),".crewx","crewx.db")))throw new Error(`${lu}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var lu,j,ie=x(()=>{m();lu="[crewx] Refusing to open the real CrewX database from a test process";j=class{resolveDbPath(){if(process.env.CREWX_TRACES_DB!==void 0)throw new Error(`CREWX_TRACES_DB is removed. Use CREWX_DB instead. (got: ${process.env.CREWX_TRACES_DB})`);let e=process.env.CREWX_DB||join(li.homedir(),".crewx","crewx.db");return Ge(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};});var l,pe=x(()=>{m();l=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 C(t,e={}){let n=Ge(t),r=ht("better-sqlite3"),{drizzle:o}=ht("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 = ${gi}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),runRaw:(i,d=[])=>s.prepare(i).run(...d),close:()=>s.close()}}function fu(t,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let n=Ge(t),r=ht("better-sqlite3"),o=pi(n),s;try{s=new r(n),s.pragma("busy_timeout = 1000");let i=s.pragma(`wal_checkpoint(${e})`),d=pi(n);return {busy:i[0]?.busy===1,walBytesBefore:o,walBytesAfter:d}}finally{s?.close();}}var pi,gi,fe=x(()=>{m();ie();pi=t=>{try{return ha.statSync(`${t}-wal`).size}catch{return 0}},gi=32*1024*1024;});function pr(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function hu(t,e){if(e>0||!pr(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(gu))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function _u(t,e,n){if(!pr(t,"__drizzle_migrations")||!pr(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(Ce__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=mu[i.tag];if(!d)continue;let c=Ce__default.join(e,`${i.tag}.sql`);if(!existsSync(c))continue;let u=readFileSync(c,"utf-8"),p=createHash("sha256").update(u).digest("hex");if(o.has(p))continue;let f=t.all("PRAGMA table_info(tasks)"),g=new Set(f.map(h=>h.name));for(let[h,_]of Object.entries(d))g.has(h)||(t.run(`ALTER TABLE tasks ADD COLUMN ${h} ${_}`),g.add(h));}}function mi(t){let e=t.trim().replace(/;+\s*$/,"").trim(),n=e.match(/^ALTER\s+TABLE\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ADD\s+(?:COLUMN\s+)?[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(n)return {kind:"add-column",table:n[1],column:n[2]};let r=e.match(/^CREATE\s+(?:UNIQUE\s+)?INDEX(?:\s+IF\s+NOT\s+EXISTS)?\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ON\s+/i);if(r)return {kind:"create-index",name:r[1]};let o=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(o)return {kind:"drop-index",name:o[1]}}function _i(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function ku(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(s=>s.name===n)}function Tu(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function lr(t,e){return e.kind==="add-column"?ku(t,e.table,e.column):Tu(t,e.name)}function ki(t,e,n){let r=t;for(let o of _i(e)){let s=mi(o);s?.kind==="add-column"&&lr(r,s)||s?.kind==="create-index"&&lr(r,s)||s?.kind==="drop-index"&&!lr(r,s)||r.run(n.raw(o));}}function wu(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(Ce__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=Ce__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let c=readFileSync(d,"utf-8"),u=createHash("sha256").update(c).digest("hex");if(o.has(u))continue;let f=_i(c).map(mi);if(f.some(h=>!h))continue;let g=f;g.some(h=>h.kind==="add-column")&&g.some(h=>lr(t,h))&&(t.transaction(h=>{ki(h,c,n),h.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);},{behavior:"immediate"}),o.add(u),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function yu(t,e){let{sql:n}=ht("drizzle-orm"),r=JSON.parse(readFileSync(Ce__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 d=r.entries.find(u=>u.tag===i);if(!d)throw new Error(`Missing release/App compatibility migration: ${i}`);let c=readFileSync(Ce__default.join(e,`${i}.sql`),"utf-8");return {entry:d,content:c,hash:createHash("sha256").update(c).digest("hex")}});t.transaction(i=>{let d=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(c=>c.hash));if(d.has(s[0].hash))for(let c of s.slice(1))d.has(c.hash)||(ki(i,c.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c.hash}, ${c.entry.when})`),d.add(c.hash),console.error(`[crewx] Replayed release/App migration ${c.entry.tag} safely.`));},{behavior:"immediate"});}function Eu(t,e,n,r){let s=JSON.parse(readFileSync(Ce__default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:f})=>f===Ru);if(!s)return;let i=Ce__default.join(e,`${s.tag}.sql`);if(!existsSync(i))return;let d=createHash("sha256").update(readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.hash===d))return;if(!pr(t,"tasks"))return {hash:d,affectedRows:0};let c=t.all("PRAGMA table_info(tasks)"),u=new Set(c.map(f=>f.name));if(!u.has("stop_requested_at")||!u.has("stop_requested_epoch"))return {hash:d,affectedRows:0};let p=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:d,affectedRows:p?.count??0}}function Yt(t){let{migrate:e}=ht("drizzle-orm/better-sqlite3/migrator"),{sql:n}=ht("drizzle-orm"),r=[Ce__default.join(
|
|
6
|
+
`);return {hash:d,affectedRows:p?.count??0}}function Yt(t){let{migrate:e}=ht("drizzle-orm/better-sqlite3/migrator"),{sql:n}=ht("drizzle-orm"),r=[Ce__default.join(S,"../migrations"),Ce__default.join(S,"migrations"),Ce__default.join(S,"../../../../drizzle/migrations"),Ce__default.join(process.cwd(),"drizzle/migrations")],o=r.find(p=>existsSync(Ce__default.join(p,"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'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),hu(t,i),s?.cnt&&(yu(t,o),wu(t,o,n),_u(t,o,n));let d=Eu(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let u=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let p=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${p} (${u} migration${u>1?"s":""} applied).`);}d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===d.hash)&&console.error(`[crewx] Task stop-marker cleanup (${d.affectedRows} success/failed row(s) affected).`);}function J(t,e){hi.has(e)||(Yt(t),hi.add(e));}var hi,gu,mu,Ru,ce=x(()=>{m();hi=new Set,gu={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"};mu={"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"}};Ru="0027_task_stop_scope_cleanup";});var P,ko=x(()=>{m();P=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,vn=x(()=>{m();a=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),actor_kind:text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:text("actor_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 st,yi=x(()=>{m();vn();st=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 Pu,Du,w,_r=x(()=>{m();ko();Pu="json_extract(metadata, '$.threadTitle.state')",Du="json_extract(metadata, '$.threadTitle.priority')",w=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>P.id,{onDelete:"set null"}),created_by_kind:text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:text("created_by_id"),created_by_task_id:text("created_by_task_id"),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_workspace_created_by_kind_updated_at:index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,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(Pu)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(Du))}));});var mt,bi=x(()=>{m();vn();mt=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(()=>mt.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 it,Si=x(()=>{m();vn();it=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 We,vi=x(()=>{m();_r();We=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>w.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 Xt,Oi=x(()=>{m();Xt=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 _e,Ci=x(()=>{m();_e=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 De,Pi=x(()=>{m();De=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 q,ae,Li=x(()=>{m();q=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`)})),ae=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 W,Hi=x(()=>{m();W=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 Ui=x(()=>{m();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 Fi=x(()=>{m();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),hu(t,i),s?.cnt&&(yu(t,o),wu(t,o,n),_u(t,o,n));let d=Eu(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let u=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(u>0){let p=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${p} (${u} migration${u>1?"s":""} applied).`);}d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===d.hash)&&console.error(`[crewx] Task stop-marker cleanup (${d.affectedRows} success/failed row(s) affected).`);}function J(t,e){hi.has(e)||(Yt(t),hi.add(e));}var hi,gu,mu,Ru,ce=x(()=>{m();hi=new Set,gu={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"};mu={"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"}};Ru="0027_task_stop_scope_cleanup";});var P,ko=x(()=>{m();P=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,vn=x(()=>{m();a=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),actor_kind:text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:text("actor_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 st,yi=x(()=>{m();vn();st=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 Pu,Du,w,_r=x(()=>{m();ko();Pu="json_extract(metadata, '$.threadTitle.state')",Du="json_extract(metadata, '$.threadTitle.priority')",w=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>P.id,{onDelete:"set null"}),created_by_kind:text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:text("created_by_id"),created_by_task_id:text("created_by_task_id"),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_workspace_created_by_kind_updated_at:index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,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(Pu)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(Du))}));});var mt,Si=x(()=>{m();vn();mt=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(()=>mt.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 it,bi=x(()=>{m();vn();it=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 We,vi=x(()=>{m();_r();We=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>w.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 Xt,Oi=x(()=>{m();Xt=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 _e,Ci=x(()=>{m();_e=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 De,Pi=x(()=>{m();De=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 q,ae,Li=x(()=>{m();q=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`)})),ae=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 W,Hi=x(()=>{m();W=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 Ui=x(()=>{m();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 Fi=x(()=>{m();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 K,Le,Ye,Bi=x(()=>{m();K=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`)})),Le=sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>K.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)})),Ye=sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>K.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 yr,Rr,I,So=x(()=>{m();yr=["THREAD_STATE","THREAD_PRIORITY"],Rr=["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 ji,Wi,zi,Gi,Ki,V,B,H,Vi=x(()=>{m();_r();ji=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Wi=["user","agent","system"],zi=["auto","manual"],Gi=["decision","judgment","issue","result","pivot"],Ki=["queued","running","completed","failed"],V=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>w.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)})),B=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>w.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)})),H=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>w.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 Yi=x(()=>{m();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 ue=x(()=>{m();ko();vn();yi();_r();bi();Si();vi();Oi();Ci();Pi();Li();Hi();Ui();Fi();Bi();So();Vi();Yi();});var rn,Mo,Ta,Ho=x(()=>{m();rn={"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}},Mo=new Set(["gpt-5.3-codex-spark"]),Ta=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 Uo(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 Xl(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Cn;let e=Uo(t),n=Yl[e];if(n)return Nr[n]??rn[n]??Cn;if(Nr[e])return Nr[e];if(rn[e])return rn[e];if(Mo.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Cn;if(Ta.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Cn;let r={...rn,...Nr};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Cn}function Ql(t,e,n,r=0,o){let s=Xl(n),i=Math.min(r,t),c=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,p=e*s.output/1e6;return c+u+p}function wa(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:Ql(e??0,n??0,o,r??0)}var Yl,Cn,Nr,xr=x(()=>{m();Ho();Ho();Yl={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"},Cn={input:0,cachedInput:0,output:0},Nr={};});function ba(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Ra(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Sa(t){return Number.isSafeInteger(t)&&t>0}function rp(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:ba(u)});return}let o="",s="",i=false,d,c=setTimeout(()=>{try{r.kill();}catch{}d({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${ya}ms`)});},ya);d=u=>{i||(i=true,clearTimeout(c),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{o+=String(u);}),r.stderr?.on("data",u=>{s+=String(u);}),r.once("error",u=>{d({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{d({status:u,stdout:o,stderr:s});});})}async function Ia(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):rp(t,e)}function op(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function sp(){return new Promise(t=>{setImmediate(t);})}function Lt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Ra(n)==="ESRCH"?"not_found":Ra(n)==="EPERM"?"alive":"unknown"}}function ip(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 va(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??tp),i=Date.now()+o,d,c=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(p=>{d=setTimeout(p,o);});u.then(()=>{c=true;});try{for(await sp();;){let p=ip(t,e);if(p==="not_found")return p;let f=i-Date.now();if(c||f<=0)return p;await Promise.race([u,op(Math.min(s,f))]);}}finally{d!==void 0&&clearTimeout(d);}}async function Ea(t,e,n,r,o){let s=await va(t,e,o.hardConfirmMs??np,{...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 Fo(t,e,n={}){if(!Sa(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 Ia(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let d=i.stdout.trim();if(!d)return "not_found";let c=r==="win32"?d.toLowerCase():d;return e.filter(p=>p.trim().length>0).some(p=>{let f=r==="win32"?p.toLowerCase():p;return c.includes(f)})?"owned":"not_owned"}async function qo(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(!Sa(t))return o("Invalid process ID");let s=e.kill??process.kill,i=Lt(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 Ia("taskkill",["/PID",String(t),"/T","/F"],e);}catch(_){g={status:null,stdout:"",stderr:"",error:ba(_)};}let h=Lt(t,s);return h==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let d,c=e.signal??"SIGKILL";try{s(-t,c);}catch(g){d=g;}if(c==="SIGKILL")return Ea(t,s,d,r,e);if(await va(t,s,e.graceMs??ep,e)==="not_found")return d?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let p;try{s(-t,"SIGKILL");}catch(g){p=g;}let f=await Ea(t,s,p,r,e);return f.status==="terminated"?f:f.status==="not_found"?d?f:{status:"terminated",pid:t,method:r}:o(f.error??"Process termination failed")}var ya,$o,ep,tp,np,Bo=x(()=>{m();ya=3e3,$o="SIGINT",ep=2e3,tp=25,np=100;});function Ca(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new l("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new l("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Na(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new l("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new l("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>Ca(r,o))}catch(r){throw r instanceof l?new l("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Pa(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new l("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new l("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new l("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function xa(t){return {taskId:t.id,source:Pa(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function pp(t){if(!Number.isInteger(t)||t<0)throw new l("VALIDATION","Task log tail limit must be a non-negative integer")}var Mt,Cr=x(()=>{m();ie();fe();ce();pe();ue();Mt=class extends j{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?Ge(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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(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 l("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)=>Ca(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new l("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let d=this.requireStateRowInTransaction(i,e),c=Pa(d);if(c==="blob"){let g=Na(e,d.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 l("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let u=d.last_log_seq+1,p=d.last_log_seq+r.length;if(i.insert(st).values(r.map((g,h)=>({task_id:e,seq:u+h,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(a).set({last_log_seq:p,log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new l("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:d.log_revision+1,lastSeq:p}},{behavior:"immediate"})}catch(s){throw s instanceof l?s:new l("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?xa(r):void 0}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return pp(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=xa(s);if(i.source==="blob"){let p=Na(e,s.logs);return {...i,entries:n===void 0?p:p.slice(Math.max(0,p.length-n))}}let d=o.select({seq:st.seq,timestamp:st.timestamp,level:st.level,message:st.message}).from(st).where(eq(st.task_id,e)).orderBy(n===void 0?asc(st.seq):desc(st.seq)),u=(n===void 0?d.all():d.limit(n).all()).map(({timestamp:p,level:f,message:g})=>({timestamp:p,level:f,message:g}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var Da=x(()=>{m();});var re,Ht=x(()=>{m();re=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 Ut,jo=x(()=>{m();Ht();Ut=class extends re{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function fp(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?yp[e]:void 0;return s?s(r,o):Object.values(Ma).some(i=>i(r,o))}function on(t,e){let n=t.split(`
|
|
13
|
-
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>fp(r,e))}function Ue(t){return typeof t=="object"&&t!==null}function La(t,e){if(e==="assistant"||e==="user"){let n=t.message;return Ue(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||Ue(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?Ue(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function gp(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:La(t,e)}function hp(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Ue(t.error);if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return Ue(n)&&typeof n.type=="string"}return false}function mp(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||Ue(t.part):e==="text"||e==="tool_use"?Ue(t.part):e==="result"?typeof t.result=="string":false}function _p(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||Ue(t.part)||e==="result"&&typeof t.result=="string")}function kp(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?Ue(t.data):e==="result"?typeof t.result=="string":false}function Tp(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 wp(t,e){return e==="available_commands"?Ue(t.tools)||Ue(t.commands):e==="usage"?Ue(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||Ue(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var Ma,yp,Pr=x(()=>{m();Ma={claude:La,codex:hp,opencode:mp,copilot:kp,gemini:Tp},yp={...Ma,claude:gp,opencode:_p,grok:wp,antigravity:()=>false};});function ut(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function lt(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 sn=x(()=>{m();});function
|
|
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 K,Le,Ye,Bi=x(()=>{m();K=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`)})),Le=sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>K.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)})),Ye=sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>K.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 yr,Rr,I,bo=x(()=>{m();yr=["THREAD_STATE","THREAD_PRIORITY"],Rr=["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 ji,Wi,zi,Gi,Ki,V,B,H,Vi=x(()=>{m();_r();ji=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Wi=["user","agent","system"],zi=["auto","manual"],Gi=["decision","judgment","issue","result","pivot"],Ki=["queued","running","completed","failed"],V=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>w.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)})),B=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>w.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)})),H=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>w.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 Yi=x(()=>{m();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 ue=x(()=>{m();ko();vn();yi();_r();Si();bi();vi();Oi();Ci();Pi();Li();Hi();Ui();Fi();Bi();bo();Vi();Yi();});var rn,Mo,Ta,Ho=x(()=>{m();rn={"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}},Mo=new Set(["gpt-5.3-codex-spark"]),Ta=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 Uo(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 Xl(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Cn;let e=Uo(t),n=Yl[e];if(n)return Nr[n]??rn[n]??Cn;if(Nr[e])return Nr[e];if(rn[e])return rn[e];if(Mo.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Cn;if(Ta.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Cn;let r={...rn,...Nr};for(let o of Object.keys(r))if(e.includes(o))return r[o];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Cn}function Ql(t,e,n,r=0,o){let s=Xl(n),i=Math.min(r,t),c=(t-i)*s.input/1e6,u=i*s.cachedInput/1e6,p=e*s.output/1e6;return c+u+p}function wa(t,e,n,r,o,s){return t&&t>0?t:!e&&!n?0:Ql(e??0,n??0,o,r??0)}var Yl,Cn,Nr,xr=x(()=>{m();Ho();Ho();Yl={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"},Cn={input:0,cachedInput:0,output:0},Nr={};});function Sa(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function Ra(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function ba(t){return Number.isSafeInteger(t)&&t>0}function rp(t,e){return new Promise(n=>{let r;try{r=spawn(t,e,{windowsHide:!0});}catch(u){n({status:null,stdout:"",stderr:"",error:Sa(u)});return}let o="",s="",i=false,d,c=setTimeout(()=>{try{r.kill();}catch{}d({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${ya}ms`)});},ya);d=u=>{i||(i=true,clearTimeout(c),n(u));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",u=>{o+=String(u);}),r.stderr?.on("data",u=>{s+=String(u);}),r.once("error",u=>{d({status:null,stdout:o,stderr:s,error:u});}),r.once("close",u=>{d({status:u,stdout:o,stderr:s});});})}async function Ia(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):rp(t,e)}function op(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function sp(){return new Promise(t=>{setImmediate(t);})}function Lt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return Ra(n)==="ESRCH"?"not_found":Ra(n)==="EPERM"?"alive":"unknown"}}function ip(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 va(t,e,n,r){let o=Math.max(0,n),s=Math.max(1,r.pollIntervalMs??tp),i=Date.now()+o,d,c=o===0,u=r.sleep?Promise.resolve().then(()=>r.sleep(o)).then(()=>{},()=>{}):new Promise(p=>{d=setTimeout(p,o);});u.then(()=>{c=true;});try{for(await sp();;){let p=ip(t,e);if(p==="not_found")return p;let f=i-Date.now();if(c||f<=0)return p;await Promise.race([u,op(Math.min(s,f))]);}}finally{d!==void 0&&clearTimeout(d);}}async function Ea(t,e,n,r,o){let s=await va(t,e,o.hardConfirmMs??np,{...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 Fo(t,e,n={}){if(!ba(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 Ia(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let d=i.stdout.trim();if(!d)return "not_found";let c=r==="win32"?d.toLowerCase():d;return e.filter(p=>p.trim().length>0).some(p=>{let f=r==="win32"?p.toLowerCase():p;return c.includes(f)})?"owned":"not_owned"}async function qo(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(!ba(t))return o("Invalid process ID");let s=e.kill??process.kill,i=Lt(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 Ia("taskkill",["/PID",String(t),"/T","/F"],e);}catch(_){g={status:null,stdout:"",stderr:"",error:Sa(_)};}let h=Lt(t,s);return h==="not_found"?g.status===0&&!g.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:o(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let d,c=e.signal??"SIGKILL";try{s(-t,c);}catch(g){d=g;}if(c==="SIGKILL")return Ea(t,s,d,r,e);if(await va(t,s,e.graceMs??ep,e)==="not_found")return d?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let p;try{s(-t,"SIGKILL");}catch(g){p=g;}let f=await Ea(t,s,p,r,e);return f.status==="terminated"?f:f.status==="not_found"?d?f:{status:"terminated",pid:t,method:r}:o(f.error??"Process termination failed")}var ya,$o,ep,tp,np,Bo=x(()=>{m();ya=3e3,$o="SIGINT",ep=2e3,tp=25,np=100;});function Ca(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new l("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new l("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Na(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new l("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new l("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,o)=>Ca(r,o))}catch(r){throw r instanceof l?new l("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Pa(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new l("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new l("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new l("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function xa(t){return {taskId:t.id,source:Pa(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function pp(t){if(!Number.isInteger(t)||t<0)throw new l("VALIDATION","Task log tail limit must be a non-negative integer")}var Mt,Cr=x(()=>{m();ie();fe();ce();pe();ue();Mt=class extends j{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?Ge(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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(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 l("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)=>Ca(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new l("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let d=this.requireStateRowInTransaction(i,e),c=Pa(d);if(c==="blob"){let g=Na(e,d.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 l("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let u=d.last_log_seq+1,p=d.last_log_seq+r.length;if(i.insert(st).values(r.map((g,h)=>({task_id:e,seq:u+h,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(a).set({last_log_seq:p,log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new l("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:c,revision:d.log_revision+1,lastSeq:p}},{behavior:"immediate"})}catch(s){throw s instanceof l?s:new l("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?xa(r):void 0}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return pp(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=xa(s);if(i.source==="blob"){let p=Na(e,s.logs);return {...i,entries:n===void 0?p:p.slice(Math.max(0,p.length-n))}}let d=o.select({seq:st.seq,timestamp:st.timestamp,level:st.level,message:st.message}).from(st).where(eq(st.task_id,e)).orderBy(n===void 0?asc(st.seq):desc(st.seq)),u=(n===void 0?d.all():d.limit(n).all()).map(({timestamp:p,level:f,message:g})=>({timestamp:p,level:f,message:g}));return n!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};});var Da=x(()=>{m();});var re,Ht=x(()=>{m();re=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 Ut,jo=x(()=>{m();Ht();Ut=class extends re{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function fp(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?yp[e]:void 0;return s?s(r,o):Object.values(Ma).some(i=>i(r,o))}function on(t,e){let n=t.split(`
|
|
13
|
+
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>fp(r,e))}function Ue(t){return typeof t=="object"&&t!==null}function La(t,e){if(e==="assistant"||e==="user"){let n=t.message;return Ue(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||Ue(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?Ue(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function gp(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:La(t,e)}function hp(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Ue(t.error);if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return Ue(n)&&typeof n.type=="string"}return false}function mp(t,e){return e==="step_start"||e==="step_finish"?typeof t.stepID=="string"||typeof t.sessionID=="string"||Ue(t.part):e==="text"||e==="tool_use"?Ue(t.part):e==="result"?typeof t.result=="string":false}function _p(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||Ue(t.part)||e==="result"&&typeof t.result=="string")}function kp(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?Ue(t.data):e==="result"?typeof t.result=="string":false}function Tp(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 wp(t,e){return e==="available_commands"?Ue(t.tools)||Ue(t.commands):e==="usage"?Ue(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||Ue(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var Ma,yp,Pr=x(()=>{m();Ma={claude:La,codex:hp,opencode:mp,copilot:kp,gemini:Tp},yp={...Ma,claude:gp,opencode:_p,grok:wp,antigravity:()=>false};});function ut(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function lt(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 sn=x(()=>{m();});function Sp(t){let e=bp(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>vp(s.value)),r=Ip(e);return {result:n.length===1&&n[0].index===r?Ap(n[0].line.value):null,resultPreview:xp(e,n),hasReservedLine:n.length>0}}function kt(t,e){let n=Sp(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function bp(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
14
14
|
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
15
15
|
`?`\r
|
|
16
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 Ip(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function vp(t){return t.trimStart().startsWith(Rp)}function Ap(t){let e=t.trim();if(!e.startsWith(Ha)||!e.endsWith("]]"))return null;let n=e.slice(Ha.length,-2);if(!n)return null;try{return Op(JSON.parse(n))}catch{return null}}function Op(t){return Np(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Np(t){if(!Cp(t)||Object.keys(t).some(r=>!Ep.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?Ua(t.taskId)&&Ua(t.agentId):t.isError===true}function xp(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 Ua(t){return typeof t=="string"&&t.trim().length>0}function Cp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ha,Rp,Ep,Dn=x(()=>{m();Ha="[[crewx:delegation-result ",Rp="[[crewx:delegation-result",Ep=new Set(["schema","taskId","agentId","isError"]);});function pt(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 an=x(()=>{m();});var $a,Dr,Wo,Lr=x(()=>{m();$a=["none","minimal","low","medium","high","xhigh","max","ultra"],Dr={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"]},Wo={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(Wo).map(([t,e])=>[t,e.models]));});function zo(t){return Dp[t]??t}function Mp(t){return Lp.get(t)??t}function Go(t){if(!t)return {};let e=Up.get(t);return e?{...e}:{model:t}}function Ko(t,e){return t==="antigravity"||t==="cli/antigravity"?Go(e):e===void 0?{}:{model:Mp(e)}}var Pp,Dp,Lp,Hp,Up,Ln=x(()=>{m();Pp=[{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]"}],Dp={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Lp=new Map(Pp.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Hp=[{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"}],Up=new Map(Hp.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Fp(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function It(t){return Mr(t).models}function Mr(t){return $p[t]??Wo[t]??Fp()}function Mn(t,e){let n=Mr(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Ko(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Fa(t){return Mr(t).modelOverrides}function qa(){return It("claude")}function Ba(){return It("codex")}function ja(){return It("copilot")}function Wa(){return It("antigravity")}var $p,$t=x(()=>{m();Lr();xr();Ln();$p={};});function za(t){return qp[t]??t}var qp,Ga=x(()=>{m();$t();Ln();qp={auto:"default"};});function Hr(t,e){return (Dr[t]??[]).includes(e)}function vt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Bp.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Ka(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 Va(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 Ja(t){return !t||!Hr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Ya(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=za(t);return e.has(n)?["--permission-mode",n]:[]}function Xa(t){return t?Hr("claude",t)?["--effort",t]:[]:[]}function Qa(t){return t==="default"?[]:t&&jp.has(t)?["--permission-mode",t]:[]}function Za(t){return t===true?["--always-approve"]:[]}function ed(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 td(t){return t?Hr("grok",t)?["--effort",t]:[]:[]}function nd(t){if(!t)return [];switch(zo(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function rd(t){return t?Hr("antigravity",t)?["--effort",t]:[]:[]}var Bp,jp,Hn=x(()=>{m();Ga();Ln();Lr();Bp=new Set($a);jp=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function Wp(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 zp(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,d="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,c=i!==void 0?i:d??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:c}}function Gp(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 od(t){let e=new Map,n;for(let s of t.split(`
|
|
@@ -24,12 +24,12 @@ ${r.join(`
|
|
|
24
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,d=o.modelUsage,c=d?Object.keys(d)[0]??null:null;return {usage:i,model:c}}}catch{}let n=od(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 [];let o=Qe(n,e??new Date().toISOString()),s=Xp(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];if(r!=="assistant"&&r!=="user")return [];let d=n.message?.content;if(!Array.isArray(d))return [];let c=[];for(let u of d){let p=ef(o,u);p&&c.push(p);}return c},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Kp.has(r):!1}catch{return false}}};});function ad(t){let e=t.split(`
|
|
25
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 tf,Jo,Yo=x(()=>{m();Pr();Un();sn();an();Dn();$t();Lr();Ft();tf=new Set(["interactive","plan","autopilot"]);Jo={command:"copilot",meta:{displayName:"Copilot",models:ja()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&tf.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Dr.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=ad(t);if(e)return e;let n=t.trim();return on(n,"copilot")?"":n},extractPartialText(t){return ad(t)},parseResultMeta(t){let e=dn(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=Qe(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let d=String(o.toolName||""),c=o.arguments,u=pt(c);return (d==="bash"||d==="Bash")&&ut(u)?[lt(s,u,i)]:[{timestamp:s,type:"tool_use",toolName:d,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let d=o.error;if(d)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...kt(String(d.message||""),true)}];let c=o.result,u=String(c?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...kt(u,false)}]}if(r==="assistant.message"){let d=String(o.content||"");return d?[{timestamp:s,type:"text",content:d}]:[]}return []}};});function of(t){let e=[],n=0,r=false,o=false,s=0;for(let d=0;d<t.length;d++){let c=t[d];if(o){o=false;continue}if(c==="\\"&&r){o=true;continue}if(c==='"'){r=!r;continue}if(!r){if(c==="{")n++;else if(c==="}"&&(n--,n===0)){let u=t.slice(s,d+1).trim();u&&e.push(u),s=d+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function sf(t){return t[0]==="exec"?t.slice(1):t}function dd(t){let e=t.split(`
|
|
26
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 Xo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function cd(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Xo(t.error)}function ud(t){let e=Xo(t.error)?t.error:void 0,n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0];for(let r of n)if(typeof r=="string"&&r.trim())return r;return t.type==="turn.failed"?"Codex turn failed.":"Codex CLI reported an error."}function af(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Xo(n)&&cd(n))return ud(n)}}function df(t,e){let n=e.type;if(n==="command_execution"){let r=String(e.command||"");return ut(r)?[lt(t,r)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:r}]}return n==="web_search"?[]:n==="file_change"?[]:[]}function cf(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=uf(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",...kt(r,o)}}if(n==="tool_use"){let r=String(e.name||e.tool_name||""),o=e.input,s=pt(o);return r==="Bash"&&ut(s)?lt(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",...kt(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 uf(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=pt(o);return r==="Bash"&&ut(s)?lt(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var nf,rf,Qo,Zo=x(()=>{m();Ht();Pr();Un();sn();an();Dn();Hn();$t();Ft();nf=new Set(["turn.started","turn.completed","item.updated"]),rf="cli/codex";Qo={command:"codex",meta:{displayName:"Codex",models:Ba(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=vt(e.model),s=e.effort??o,i=e.resumeSessionId?Va(e.mode):Ka(e.mode),d=Ja(s),c=r?["-m",r]:[],u=sf(e.additionalArgs??[]),f=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...f,...i,...d,...c,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...f,...i,...d,...c,...u],stdinMessage:t}},extractText(t){let e=af(t);if(e)throw new re(e,rf);let n=dd(t);if(n)return n;let r=t.trim();return on(r,"codex")?"":r},extractPartialText(t){return dd(t)},parseResultMeta(t){let e=dn(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=of(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let d=i.type;if(!d)continue;let c=Qe(i,n);if(cd(i)){let p=ud(i);r.push({timestamp:c,type:"error",content:p,errorMessage:p});continue}if(!d.startsWith("item.")&&!d.startsWith("turn.")&&!d.startsWith("thread."))continue;let u=i.item;if(u){if(d==="item.started"){r.push(...df(c,u));continue}if(d==="item.completed"){let p=cf(c,u);p&&r.push(p);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?nf.has(r):!1}catch{return false}}};});function ff(t){return t?pf[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function $r(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function hd(t){let e=[],n=0,r=false,o=false,s=0;for(let d=0;d<t.length;d++){let c=t[d];if(o){o=false;continue}if(c==="\\"&&r){o=true;continue}if(c==='"'){r=!r;continue}if(!r){if(c==="{")n++;else if(c==="}"&&(n--,n===0)){let u=t.slice(s,d+1).trim();u&&e.push(u),s=d+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function un(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gf(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);un(i)?e.push(i):n=!0;continue}catch{}let s=hd(o);s.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of s)try{let d=JSON.parse(i);un(d)?e.push(d):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function qt(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,gd).trim()}function md(t){let e=un(t.error)?t.error:void 0,n=e&&un(e.data)?e.data:void 0,r=qt(e?.name),o=qt(n?.message)??qt(e?.message)??qt(t.message)??qt(t.errorMessage)??qt(t.error),s=qt(t.ref),i=r&&o&&r!==o?`${r}: ${o}`:r??o??fd;return (s?`${i} (ref: ${s})`:i).slice(0,gd)}function ld(t){let e=gf(t),n=[],r=null,o=0,s=[],i,d=false;for(let c of e.events){let u=typeof c.type=="string"?c.type:void 0;if(u){if(u==="text"){let p=un(c.part)?c.part:void 0,f=typeof p?.text=="string"?p.text:void 0;f?.trim()&&n.push(f.trim());continue}if(u==="result"){typeof c.result=="string"&&(r=c.result);continue}if(u==="tool_use"){o++;continue}if(u==="error"){s.push(md(c));continue}if(u==="step_finish"){d=true;let p=un(c.part)?c.part:void 0;i=typeof p?.reason=="string"?p.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:o,errorMessages:s,terminalReason:i,hasTerminal:d}}function _d(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Fr(){return new re("OpenCode returned no assistant output.",cn,{code:"EMPTY_OUTPUT",kind:"transient"})}function hf(){return new re("OpenCode emitted malformed JSON output.",cn,{code:"PROVIDER_CRASHED",kind:"transient"})}function pd(t,e){switch(_d(t)){case "length":return new re("OpenCode stopped because the context window was exceeded.",cn,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new re("OpenCode stopped because the content filter blocked the response.",cn,{code:"UNKNOWN",kind:"permanent"});case "error":return new re(e?`OpenCode error: ${e}`:`${fd} while generating a response.`,cn,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var lf,cn,fd,gd,pf,es,ts=x(()=>{m();Ht();Un();an();Ft();lf=new Set(["step_start","step_finish"]),cn="cli/opencode",fd="OpenCode provider error",gd=240,pf={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};es={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,o=r!==void 0?[...r]:["run"];$r(o,"--format")||o.push("--format","json"),e.resumeSessionId&&!o.includes("-s")&&!o.includes("--session")&&o.push("-s",e.resumeSessionId);let{agent:s,autoApprove:i}=ff(e.mode);$r(o,"--agent")||s!==void 0&&o.push("--agent",s),i&&!$r(o,"--auto")&&o.push("--auto"),e.effort!==void 0&&!$r(o,"--variant")&&o.push("--variant",e.effort),e.model&&o.push("--model",e.model);let d;return !n&&!i&&!e.env?.OPENCODE_PERMISSION&&(d={OPENCODE_PERMISSION:JSON.stringify({external_directory:"allow"})}),{args:o,stdinMessage:t,env:d}},extractText(t){let e=ld(t),n=e.errorMessages[0];if(n){let i=pd("error",n);if(i)throw i}let r=pd(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 Fr();return o}if(e.resultText?.trim()){if(!e.hasTerminal)throw Fr();return e.resultText}if(e.malformed)throw hf();if(!e.hasTerminal)throw Fr();let s=_d(e.terminalReason);if((s==="stop"||s==="tool-calls")&&e.toolUseCount>0)return "";throw Fr()},interpretExit(t,e,n=""){if(t===0)return null;let o=ld(n).errorMessages[0];return o?new re(`OpenCode error: ${o}`,cn,{code:"PROVIDER_CRASHED",kind:"transient"}):null},parseResultMeta(t){let e=dn(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=hd(t),o.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let s of o){let i;try{i=JSON.parse(s);}catch{continue}let d=Qe(i,n),c=i.type;if(c){if(c==="text"){let p=i.part?.text;p&&r.push({timestamp:d,type:"text",content:p});continue}if(c==="tool_use"){let u=i.part;if(!u)continue;let p=String(u.tool||""),f=String(u.callID||""),g=u.state,h=String(g?.status||""),_=g?.input,k=pt(_);if(r.push({timestamp:d,type:"tool_use",toolName:p,toolUseId:f,toolInput:k}),h==="completed"&&g?.output!==void 0){let T=g.output,E=typeof T=="string"?T:JSON.stringify(T);r.push({timestamp:d,type:"tool_result",toolUseId:f,resultPreview:E,isError:false});}else h==="error"&&r.push({timestamp:d,type:"tool_result",toolUseId:f,resultPreview:String(g?.error||"tool error"),isError:true});continue}if(c==="error"){let u=md(i);r.push({timestamp:d,type:"error",content:u,errorMessage:u});continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?lf.has(r):!1}catch{return false}}};});function $n(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function mf(t,e){if(!(t?It(ns).some(s=>s.id===t):false)||!t)return e;let r=Mn(ns,t),o=Fa(ns)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}var ns,rs,os=x(()=>{m();Ht();Ln();$t();Hn();ns="antigravity";rs={command:"agy",meta:{displayName:"Antigravity",models:Wa(),defaultTimeoutMs:{query:12e4,execute:3e5},defaultIdleMs:0},buildArgs(t,e,n){let{model:r,effort:o}=vt(e.model),s=Go(r),i=s.model,d=e.effort??o??s.effort,c=mf(i,d),u=e.additionalArgs??[],p=i&&!$n(u,"--model")?["--model",i]:[],f=$n(u,"--effort")?[]:rd(c),g=$n(u,"--mode")||$n(u,"--dangerously-skip-permissions")?[]:nd(e.mode),h=$n(u,"--print")?[]:["--print",t];return {args:[...p,...f,...g,...u,...h]}},extractText(t){let e=t.trim();if(!e)throw new re("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 kd=x(()=>{m();sn();an();Dn();Ft();});function ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Br(t){return ln(t)?t:void 0}function Oe(t){return typeof t=="string"?t:void 0}function Bt(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function yf(t){let e=[],n=-1,r=0,o=false,s=false;for(let i=0;i<t.length;i+=1){let d=t[i];if(n===-1){(d==="{"||d==="[")&&(n=i,r=1);continue}if(s){s=false;continue}if(d==="\\"&&o){s=true;continue}if(d==='"'){o=!o;continue}o||(d==="{"||d==="["?r+=1:(d==="}"||d==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function Fn(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return ln(n)?[n]:[]}catch{return yf(e).flatMap(n=>{try{let r=JSON.parse(n);return ln(r)?[r]:[]}catch{return []}})}}function qn(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Bn(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Bn).filter(n=>n!==void 0);return e.length>0?e.join(`
|
|
27
|
-
`):void 0}if(ln(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=Bn(t[e]);if(n!==void 0)return n}}}function Rf(t){if(t.rawOutput!==null&&t.rawOutput!==void 0)return Bn(t.rawOutput)??qn(t.rawOutput);if(t.content!==null&&t.content!==void 0)return Bn(t.content)??qn(t.content);if(t.result!==null&&t.result!==void 0)return Bn(t.result)??qn(t.result)}function Ed(t){let e=Br(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?
|
|
27
|
+
`):void 0}if(ln(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=Bn(t[e]);if(n!==void 0)return n}}}function Rf(t){if(t.rawOutput!==null&&t.rawOutput!==void 0)return Bn(t.rawOutput)??qn(t.rawOutput);if(t.content!==null&&t.content!==void 0)return Bn(t.content)??qn(t.content);if(t.result!==null&&t.result!==void 0)return Bn(t.result)??qn(t.result)}function Ed(t){let e=Br(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?Sd(n):"Grok CLI reported an error."}function Sd(t){return (t.replace(wf,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Rd(t){return Tf.test(t)}function Ef(t){let e=Br(t.modelUsage);return e?Object.keys(e)[0]??null:null}function Sf(t){let e=Br(t.usage);if(!e)return null;let n=Bt(e.cache_read_input_tokens);return {inputTokens:Bt(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Bt(e.output_tokens),costUsd:Bt(t.total_cost_usd)}}function bf(t){let e=0,n=0,r=0,o=false,s=new Set;for(let i of t.split(`
|
|
28
28
|
`).flatMap(Fn)){if(i.type!=="usage")continue;let d=Br(i.usage);if(!d)continue;let c=Oe(i.signature);if(c&&c.length>0){let p=`signature:${c}`;if(s.has(p))continue;s.add(p);}let u=Bt(d.cache_read_input_tokens);e+=Bt(d.input_tokens)+u,n+=u,r+=Bt(d.output_tokens),o=true;}return o?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function If(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let s of e.entries.slice(0,Td)){if(!ln(s))continue;let i=Oe(s.content)?.trim();if(!i)continue;let d=Oe(s.status)?.trim(),c=Oe(s.priority)?.trim(),u=[d?`status=${d}`:void 0,c?`priority=${c}`:void 0].filter(f=>!!f),p=u.length>0?` (${u.join(", ")})`:"";n.push(`- ${i}${p}`);}if(n.length===0)return [];e.entries.length>Td&&n.push(yd);let r=n.join(`
|
|
29
29
|
`),o=r.length>wd?`${r.slice(0,wd-1)}${yd}`:r;return [{timestamp:t,type:"info",content:o}]}function vf(t,e){let n=Oe(e.type);if(n==="thought"){let r=Oe(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=Oe(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return If(t,e);if(n==="tool_call"){let r=Oe(e.toolCallId),o=Oe(e.toolName)??Oe(e.title),s=e.rawInput===void 0?void 0:qn(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:o,toolInput:s}]}if(n==="tool_call_update"){let r=Oe(e.status);return r!=="completed"&&r!=="failed"&&r!=="error"?[]:[{timestamp:t,type:"tool_result",toolUseId:Oe(e.toolCallId),toolName:Oe(e.toolName)??Oe(e.title),resultPreview:Rf(e),isError:r!=="completed"||e.isError===true}]}if(n==="error"){let r=Ed(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}var qr,kf,Tf,wf,Td,wd,yd,ss,is=x(()=>{m();Ht();jo();$t();Hn();Ft();qr="cli/grok",kf=new Set(["available_commands","usage","end"]),Tf=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,wf=/\u001b\[[0-?]*[ -/]*[@-~]/g,Td=20,wd=4e3,yd="\u2026";ss={command:"grok",createSessionId:()=>randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=vt(e.model),o=e.effort??r,s=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],d=n?It("grok").some(U=>U.id===n):false,c=n&&d?Mn("grok",n):[],u=!o||c.length===0||c.includes(o)?o:void 0,p=td(u),f=e.additionalArgs??[],g=U=>f.some(R=>R===U||R.startsWith(`${U}=`)),h=e.providerOptions,_=h?.alwaysApprove,k=h?.sandbox,T=g("--permission-mode")?[]:Qa(e.mode),E=g("--always-approve")?[]:Za(_),L=g("--sandbox")?[]:ed(k);return {args:["--no-auto-update",...s,"--single",t,"--output-format","streaming-json","--no-alt-screen",...i,...p,...T,...E,...L,...f]}},extractText(t){let e=[],n=false;for(let r of t.split(`
|
|
30
|
-
`).flatMap(Fn))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 Fn(t))if(e.type==="error"){let n=Ed(e);return Rd(qn(e))?new Ut(n,qr):new re(n,qr)}return null},interpretExit(t,e){if(t===0)return null;let n=
|
|
31
|
-
`).flatMap(Fn).find(r=>r.type==="end");return n?{usage:
|
|
32
|
-
`)??"";if(!n.trim())return;let r=vd(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=Af(o?.model,t.model),i=o?.usage;if(!i)return {stdout:n,adapter:r};let d=jr(i.inputTokens),c=jr(i.outputTokens),u=jr(i.cachedInputTokens),p=wa(jr(i.costUsd),d,c,u,s);return d!==0||c!==0||u!==0||p!==0?{stdout:n,adapter:r,usage:{inputTokens:d,outputTokens:c,cachedInputTokens:u,costUsd:p,model:s}}:{stdout:n,adapter:r}}var as=x(()=>{m();Ad();xr();});function Nf(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"&&Of.has(n)?n:void 0}catch{return}}function At(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=Nf(t.metadata);return e==="user_stop"?"stopped":e==="runner_lost"?"runner_lost":e==="launch_failed"?"failed":typeof t.error=="string"&&ds.stopped.test(t.error)?"stopped":typeof t.error=="string"&&ds.runnerLost.test(t.error)?"runner_lost":"failed"}default:return t.status}}var cs,ds,Of,jn=x(()=>{m();cs=["success","failed","stopped","runner_lost"],ds={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},Of=new Set(["user_stop","runner_lost","launch_failed"]);});function gs(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 Gr(){return gs("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function jt(){return gs("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Wn(){return gs("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function fn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function zr(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 Cf(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 Od(t,e){return !!t.stop_requested_at&&fn(t.stop_requested_epoch)===fn(e)}function us(t,e){let n=fn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=Cf(t.getTask(e.taskId));return !o||o.status!=="running"||fn(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function Nd(t,e){let n=pn.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),pn.delete(t),true)}function xd(t,e){let n=pn.get(t);return !n||e!==void 0&&n.runEpoch!==fn(e)?false:Nd(t,n)}function Pf(t,e){let n=fn(e.runEpoch);xd(e.taskId);let r=true,o=null;try{let u=us(t,{...e,runEpoch:n});r=u.accepted,o=u.row;}catch(u){zr(u);}if(!r)return false;let s=Gr(),i=Math.min(s,1e3),d=setInterval(()=>{let u=pn.get(e.taskId);if(!(!u||u.timer!==d))try{u.heartbeatElapsedMs+=i;let p=u.heartbeatElapsedMs>=s,f=us(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:p});if(!f.accepted){Nd(e.taskId,u);return}p&&(u.heartbeatElapsedMs%=s,u.lastHeartbeatAt=Date.now()),f.row&&Od(f.row,n)&&!u.stopRequested&&(u.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(f.row)).catch(zr));}catch(p){zr(p);}},i),c={timer:d,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return pn.set(e.taskId,c),typeof d=="object"&&d!==null&&"unref"in d&&d.unref(),o&&Od(o,n)&&e.onStopRequested&&(c.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(zr)),true}var ls,ps,fs,xf,pn,zn=x(()=>{m();ls=1e4,ps=3e4,fs=18e5,xf=1e3;pn=new Map;});function ws(t,e=Date.now(),n=Jr){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=Ts(n,Jr,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function Ts(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function $d(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function Df(t){if(!t)return;let e=$d(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function ft(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=Df(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function Fd(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 ye(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 hs(t,e){return ye(t,Hd,e)}function Lf(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=jt():false}function Mf(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Hf(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=$d(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 Uf(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return ft(r,n)}async function $f(t,e,n,r){let o=Date.now()+n;for(;;){let s=Uf(t,e);if(s)return s;let i=o-Date.now();if(i<=0)return;await new Promise(d=>{setTimeout(d,Math.min(r,i));});}}async function Cd(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 U=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),R=t.getTask(e);if(U||!R||R.status!=="running")return ft(R);if(s=t.requestTaskStop({id:e,requestedAt:r,...o}),!s.accepted&&s.status!=="running"||!s.accepted&&!s.alreadyRequestedAt)return ft(t.getTask(e))}else if(!(s.status==="running"&&s.alreadyRequestedAt))return ft(i)}let d=s.runEpoch,c=Ts(n.graceMs,Jr,0),u=Ts(n.pollMs,Ld,1),p=await $f(t,e,c,u);if(p)return p;let f=t.getTask(e);if(!f||f.status!=="running")return ft(f);let g=Hf(f),h=g[0];if(!h){let U=t.finalizeTaskStop({id:e,runEpoch:d,method:"forced"}),R=t.getTask(e);return U||R?.status!=="running"?ft(R):ye(R,"Failed to finalize task stop")}let _=Mf(n),k="unknown";if(!Lf(f,Date.now())){let U=n.processControl?.checkProcessOwnershipAsync??Fo;try{k=await U(h,n.ownershipMarkers??ys,_);}catch{k="unknown";}if(k!=="owned")return Fd(f)}let T=n.processControl?.terminateProcessTree??qo;for(let U of g){let R;try{R=await T(U,{..._,signal:$o});}catch(O){R={status:"failed",pid:U,method:_.platform==="win32"?"taskkill":"process-group",error:O instanceof Error?O.message:String(O)};}if(R.status==="failed")return ye(t.getTask(e),R.error??"Failed to terminate process tree")}let E=t.finalizeTaskStop({id:e,runEpoch:d,method:"forced"}),L=t.getTask(e);return E||L?.status!=="running"?ft(L,h):ye(L,"Task changed before stop was finalized")}function Pd(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Dd(t){return Number.isSafeInteger(t)&&t>=0}function ms(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Ff(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}async function qd(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return hs(n,Pd(e.targetPid)?e.targetPid:void 0);if(!Dd(e.sourceRunEpoch)||!Dd(e.settleRunEpoch)||ms(n.run_epoch)!==e.settleRunEpoch)return ye(n,Kr,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return ye(n,Vr,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 ye(n,Ud,e.targetPid)}let s=t.getTask(e.taskId);if(!s||s.status!=="running")return hs(s,e.targetPid);if(o.runEpoch!==e.settleRunEpoch||ms(s.run_epoch)!==e.settleRunEpoch)return ye(s,Kr,e.targetPid);if(e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId)return ye(s,Vr,e.targetPid);if(!Pd(e.targetPid))return ye(s,Md);let i=Ff(e),d=e.processControl?.checkProcessOwnershipAsync??Fo,c="unknown";try{c=await d(e.targetPid,e.ownershipMarkers??ys,i);}catch{c="unknown";}if(c!=="owned")return Fd(s,e.targetPid);let u=t.getTask(e.taskId);if(!u||u.status!=="running")return hs(u,e.targetPid);if(ms(u.run_epoch)!==e.settleRunEpoch)return ye(u,Kr,e.targetPid);if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId)return ye(u,Vr,e.targetPid);let p=e.processControl?.terminateProcessTree??qo,f;try{f=await p(e.targetPid,{...i,signal:$o});}catch{return ye(t.getTask(e.taskId),_s,e.targetPid)}if(f.status==="failed")return ye(t.getTask(e.taskId),_s,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return ye(t.getTask(e.taskId),ks,e.targetPid)}return g?ft(t.getTask(e.taskId),e.targetPid):ye(t.getTask(e.taskId),ks,e.targetPid)}function Rs(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(Gn(),Bd)).then(({TaskRepository:s})=>Cd(new s,r,o))}return Cd(t,e,n)}var Jr,Ld,ys,Md,Kr,Vr,Hd,_s,ks,Ud,Es=x(()=>{m();Bo();zn();Jr=5e3,Ld=250;ys=["crewx","claude","codex","opencode","grok","node"],Md="INSTRUCTION_STOP_TARGET_PID_MISSING",Kr="INSTRUCTION_STOP_EPOCH_MISMATCH",Vr="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Hd="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",_s="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",ks="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Ud="INSTRUCTION_STOP_REQUEST_FAILED";});var Bd={};ou(Bd,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Ps,HOST_SHUTDOWN_TERMINAL_ERROR:()=>Gd,PENDING_ADOPT_GRACE_MS:()=>Vd,PID_NULL_REAP_GRACE_MS:()=>Cs,TASK_HEARTBEAT_HARD_STALE_MS:()=>fs,TASK_HEARTBEAT_INTERVAL_MS:()=>ls,TASK_HEARTBEAT_STALE_MS:()=>ps,TaskRepository:()=>to,hasRecordedUsage:()=>kn,mergeTerminalReason:()=>eo,resolveTaskHeartbeatHardStaleMs:()=>Wn,resolveTaskHeartbeatIntervalMs:()=>Gr,resolveTaskHeartbeatStaleMs:()=>jt});function et(t){return {...t,status:At(t)}}function Ss(t){return {...t,status:At(t)}}function vs(t=a.model,e=a.metadata){let n=sql`
|
|
30
|
+
`).flatMap(Fn))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 Fn(t))if(e.type==="error"){let n=Ed(e);return Rd(qn(e))?new Ut(n,qr):new re(n,qr)}return null},interpretExit(t,e){if(t===0)return null;let n=Sd(e)||`Grok CLI exited with code ${t}.`;return Rd(e)?new Ut(n,qr):new re(n,qr)},parseResultMeta(t){let n=t.split(`
|
|
31
|
+
`).flatMap(Fn).find(r=>r.type==="end");return n?{usage:Sf(n),model:Ef(n)}:{usage:bf(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return Fn(t).flatMap(r=>vf(Qe(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return ln(n)&&typeof n.type=="string"?kf.has(n.type):!1}catch{return false}}};});var bd,Id=x(()=>{m();Vo();Yo();Zo();ts();os();kd();is();Vo();Yo();Zo();ts();os();is();sn();bd={codex:Qo,claude:Ur,opencode:es,antigravity:rs,copilot:Jo,grok:ss};});function vd(t){if(t.startsWith("cli/"))return bd[t.slice(4)]}var Ad=x(()=>{m();Da();Id();});function jr(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Af(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function Wr(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=vd(t.provider);if(!r)return;let o;try{o=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let s=Af(o?.model,t.model),i=o?.usage;if(!i)return {stdout:n,adapter:r};let d=jr(i.inputTokens),c=jr(i.outputTokens),u=jr(i.cachedInputTokens),p=wa(jr(i.costUsd),d,c,u,s);return d!==0||c!==0||u!==0||p!==0?{stdout:n,adapter:r,usage:{inputTokens:d,outputTokens:c,cachedInputTokens:u,costUsd:p,model:s}}:{stdout:n,adapter:r}}var as=x(()=>{m();Ad();xr();});function Nf(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"&&Of.has(n)?n:void 0}catch{return}}function At(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=Nf(t.metadata);return e==="user_stop"?"stopped":e==="runner_lost"?"runner_lost":e==="launch_failed"?"failed":typeof t.error=="string"&&ds.stopped.test(t.error)?"stopped":typeof t.error=="string"&&ds.runnerLost.test(t.error)?"runner_lost":"failed"}default:return t.status}}var cs,ds,Of,jn=x(()=>{m();cs=["success","failed","stopped","runner_lost"],ds={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},Of=new Set(["user_stop","runner_lost","launch_failed"]);});function gs(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 Gr(){return gs("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function jt(){return gs("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function Wn(){return gs("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function fn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function zr(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 Cf(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 Od(t,e){return !!t.stop_requested_at&&fn(t.stop_requested_epoch)===fn(e)}function us(t,e){let n=fn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let o=Cf(t.getTask(e.taskId));return !o||o.status!=="running"||fn(o.run_epoch)!==n?{accepted:false,row:o}:{accepted:true,row:o}}function Nd(t,e){let n=pn.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),pn.delete(t),true)}function xd(t,e){let n=pn.get(t);return !n||e!==void 0&&n.runEpoch!==fn(e)?false:Nd(t,n)}function Pf(t,e){let n=fn(e.runEpoch);xd(e.taskId);let r=true,o=null;try{let u=us(t,{...e,runEpoch:n});r=u.accepted,o=u.row;}catch(u){zr(u);}if(!r)return false;let s=Gr(),i=Math.min(s,1e3),d=setInterval(()=>{let u=pn.get(e.taskId);if(!(!u||u.timer!==d))try{u.heartbeatElapsedMs+=i;let p=u.heartbeatElapsedMs>=s,f=us(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:p});if(!f.accepted){Nd(e.taskId,u);return}p&&(u.heartbeatElapsedMs%=s,u.lastHeartbeatAt=Date.now()),f.row&&Od(f.row,n)&&!u.stopRequested&&(u.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(f.row)).catch(zr));}catch(p){zr(p);}},i),c={timer:d,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return pn.set(e.taskId,c),typeof d=="object"&&d!==null&&"unref"in d&&d.unref(),o&&Od(o,n)&&e.onStopRequested&&(c.stopRequested=true,Promise.resolve(e.onStopRequested(o)).catch(zr)),true}var ls,ps,fs,xf,pn,zn=x(()=>{m();ls=1e4,ps=3e4,fs=18e5,xf=1e3;pn=new Map;});function ws(t,e=Date.now(),n=Jr){let r=t?Date.parse(t):Number.NaN,o=typeof e=="number"?e:Date.parse(e),s=Ts(n,Jr,0);return Number.isFinite(r)&&Number.isFinite(o)&&o-r>s?"forced":"cooperative"}function Ts(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function $d(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function Df(t){if(!t)return;let e=$d(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function ft(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=Df(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function Fd(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 ye(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 hs(t,e){return ye(t,Hd,e)}function Lf(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=jt():false}function Mf(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Hf(t){let e=typeof t.pid=="number"&&t.pid>0?t.pid:void 0,n=$d(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 Uf(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return ft(r,n)}async function $f(t,e,n,r){let o=Date.now()+n;for(;;){let s=Uf(t,e);if(s)return s;let i=o-Date.now();if(i<=0)return;await new Promise(d=>{setTimeout(d,Math.min(r,i));});}}async function Cd(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 U=t.stopPendingTask(e,void 0,void 0,{...o,at:r}),R=t.getTask(e);if(U||!R||R.status!=="running")return ft(R);if(s=t.requestTaskStop({id:e,requestedAt:r,...o}),!s.accepted&&s.status!=="running"||!s.accepted&&!s.alreadyRequestedAt)return ft(t.getTask(e))}else if(!(s.status==="running"&&s.alreadyRequestedAt))return ft(i)}let d=s.runEpoch,c=Ts(n.graceMs,Jr,0),u=Ts(n.pollMs,Ld,1),p=await $f(t,e,c,u);if(p)return p;let f=t.getTask(e);if(!f||f.status!=="running")return ft(f);let g=Hf(f),h=g[0];if(!h){let U=t.finalizeTaskStop({id:e,runEpoch:d,method:"forced"}),R=t.getTask(e);return U||R?.status!=="running"?ft(R):ye(R,"Failed to finalize task stop")}let _=Mf(n),k="unknown";if(!Lf(f,Date.now())){let U=n.processControl?.checkProcessOwnershipAsync??Fo;try{k=await U(h,n.ownershipMarkers??ys,_);}catch{k="unknown";}if(k!=="owned")return Fd(f)}let T=n.processControl?.terminateProcessTree??qo;for(let U of g){let R;try{R=await T(U,{..._,signal:$o});}catch(O){R={status:"failed",pid:U,method:_.platform==="win32"?"taskkill":"process-group",error:O instanceof Error?O.message:String(O)};}if(R.status==="failed")return ye(t.getTask(e),R.error??"Failed to terminate process tree")}let E=t.finalizeTaskStop({id:e,runEpoch:d,method:"forced"}),L=t.getTask(e);return E||L?.status!=="running"?ft(L,h):ye(L,"Task changed before stop was finalized")}function Pd(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Dd(t){return Number.isSafeInteger(t)&&t>=0}function ms(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Ff(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}async function qd(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return hs(n,Pd(e.targetPid)?e.targetPid:void 0);if(!Dd(e.sourceRunEpoch)||!Dd(e.settleRunEpoch)||ms(n.run_epoch)!==e.settleRunEpoch)return ye(n,Kr,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return ye(n,Vr,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 ye(n,Ud,e.targetPid)}let s=t.getTask(e.taskId);if(!s||s.status!=="running")return hs(s,e.targetPid);if(o.runEpoch!==e.settleRunEpoch||ms(s.run_epoch)!==e.settleRunEpoch)return ye(s,Kr,e.targetPid);if(e.workspaceId!==void 0&&s.workspace_id!==e.workspaceId)return ye(s,Vr,e.targetPid);if(!Pd(e.targetPid))return ye(s,Md);let i=Ff(e),d=e.processControl?.checkProcessOwnershipAsync??Fo,c="unknown";try{c=await d(e.targetPid,e.ownershipMarkers??ys,i);}catch{c="unknown";}if(c!=="owned")return Fd(s,e.targetPid);let u=t.getTask(e.taskId);if(!u||u.status!=="running")return hs(u,e.targetPid);if(ms(u.run_epoch)!==e.settleRunEpoch)return ye(u,Kr,e.targetPid);if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId)return ye(u,Vr,e.targetPid);let p=e.processControl?.terminateProcessTree??qo,f;try{f=await p(e.targetPid,{...i,signal:$o});}catch{return ye(t.getTask(e.taskId),_s,e.targetPid)}if(f.status==="failed")return ye(t.getTask(e.taskId),_s,e.targetPid);let g;try{g=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return ye(t.getTask(e.taskId),ks,e.targetPid)}return g?ft(t.getTask(e.taskId),e.targetPid):ye(t.getTask(e.taskId),ks,e.targetPid)}function Rs(t,e,n={}){if(typeof t=="string"){let r=t,o=e??{};return Promise.resolve().then(()=>(Gn(),Bd)).then(({TaskRepository:s})=>Cd(new s,r,o))}return Cd(t,e,n)}var Jr,Ld,ys,Md,Kr,Vr,Hd,_s,ks,Ud,Es=x(()=>{m();Bo();zn();Jr=5e3,Ld=250;ys=["crewx","claude","codex","opencode","grok","node"],Md="INSTRUCTION_STOP_TARGET_PID_MISSING",Kr="INSTRUCTION_STOP_EPOCH_MISMATCH",Vr="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Hd="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",_s="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",ks="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Ud="INSTRUCTION_STOP_REQUEST_FAILED";});var Bd={};ou(Bd,{DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Ps,HOST_SHUTDOWN_TERMINAL_ERROR:()=>Gd,PENDING_ADOPT_GRACE_MS:()=>Vd,PID_NULL_REAP_GRACE_MS:()=>Cs,TASK_HEARTBEAT_HARD_STALE_MS:()=>fs,TASK_HEARTBEAT_INTERVAL_MS:()=>ls,TASK_HEARTBEAT_STALE_MS:()=>ps,TaskRepository:()=>to,hasRecordedUsage:()=>kn,mergeTerminalReason:()=>eo,resolveTaskHeartbeatHardStaleMs:()=>Wn,resolveTaskHeartbeatIntervalMs:()=>Gr,resolveTaskHeartbeatStaleMs:()=>jt});function et(t){return {...t,status:At(t)}}function bs(t){return {...t,status:At(t)}}function vs(t=a.model,e=a.metadata){let n=sql`
|
|
33
33
|
CASE
|
|
34
34
|
WHEN ${t} LIKE 'claude-%' OR ${t} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
35
35
|
WHEN ${t} LIKE 'gpt-%' OR ${t} LIKE 'codex-%' THEN 'codex'
|
|
@@ -109,7 +109,7 @@ ${r.join(`
|
|
|
109
109
|
FROM tasks
|
|
110
110
|
GROUP BY workspace_id
|
|
111
111
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
112
|
-
`)}catch(r){throw new l("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,d=0;for(let c of r){if(!existsSync(c))continue;let u=C(c);try{let p=eq(a.thread_id,e),f=n?and(p,eq(a.workspace_id,n)):p,g=u.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(f).all();for(let h of g)o.has(h.id)||(o.add(h.id),s+=h.input_tokens??0,i+=h.output_tokens??0,d+=h.cost_usd??0);}catch(p){throw new l("DB_ERROR","Failed to get thread token usage",p)}finally{u.close();}}return {inputTokens:s,outputTokens:i,costUsd:d}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],d=r?.projection==="activity-log";for(let c of o){if(!existsSync(c))continue;let u=C(c);try{let p=eq(a.thread_id,e),f=n?and(p,eq(a.workspace_id,n)):p,g=d?u.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(f).orderBy(asc(a.started_at)).all():u.db.select().from(a).where(f).orderBy(asc(a.started_at)).all().map(et);for(let h of g)s.has(h.id)||(s.add(h.id),i.push(h));}catch(p){throw new l("DB_ERROR","Failed to find tasks by thread",p)}finally{u.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=C(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"),inArray(a.status,["running","pending"]),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(a.started_at)).all().map(
|
|
112
|
+
`)}catch(r){throw new l("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,d=0;for(let c of r){if(!existsSync(c))continue;let u=C(c);try{let p=eq(a.thread_id,e),f=n?and(p,eq(a.workspace_id,n)):p,g=u.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(f).all();for(let h of g)o.has(h.id)||(o.add(h.id),s+=h.input_tokens??0,i+=h.output_tokens??0,d+=h.cost_usd??0);}catch(p){throw new l("DB_ERROR","Failed to get thread token usage",p)}finally{u.close();}}return {inputTokens:s,outputTokens:i,costUsd:d}}findTasksByThread(e,n,r){let o=this.resolveDbPaths(),s=new Set,i=[],d=r?.projection==="activity-log";for(let c of o){if(!existsSync(c))continue;let u=C(c);try{let p=eq(a.thread_id,e),f=n?and(p,eq(a.workspace_id,n)):p,g=d?u.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(f).orderBy(asc(a.started_at)).all():u.db.select().from(a).where(f).orderBy(asc(a.started_at)).all().map(et);for(let h of g)s.has(h.id)||(s.add(h.id),i.push(h));}catch(p){throw new l("DB_ERROR","Failed to find tasks by thread",p)}finally{u.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=C(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"),inArray(a.status,["running","pending"]),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(a.started_at)).all().map(bs));}catch(o){throw new l("DB_ERROR","Failed to find workflow parent tasks",o)}finally{r.close();}}return e}findWorkflowParentTasksByWorkspace(e){let n=[],r=new Map;for(let o of this.resolveDbPaths()){if(!existsSync(o))continue;let s=C(o);try{let i=s.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))).orderBy(desc(a.started_at),desc(a.id)).all();for(let d of i){let c=this.parseWorkflowCardMetadata(d.metadata);if(c.kind!=="workflow_card"&&c.kind!=="workflow_ui_instance"||typeof c.workflowRunId!="string")continue;let u=c.kind,p=r.get(u)??new Set;p.has(c.workflowRunId)||(p.add(c.workflowRunId),r.set(u,p),n.push(bs(d)));}}catch(i){throw new l("DB_ERROR","Failed to find workflow parent tasks by workspace",i)}finally{s.close();}}return n}findWorkflowParentTask(e){if(this.dbExists())for(let n of this.resolveDbPaths()){if(!existsSync(n))continue;let r=C(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 bs(s)}}catch(o){throw new l("DB_ERROR","Failed to find workflow parent task",o)}finally{r.close();}}}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let o=new Set(e),s=new Map,i=n?eq(a.workspace_id,n):void 0,d=(c,u)=>{if(!c)return;let p=s.get(c);if(p&&u.started_at<=p)return;let f=this.parseWorkflowCardMetadata(u.metadata);f.kind!=="workflow_card"&&f.kind!=="workflow_ui_instance"||(s.set(c,u.started_at),r.set(c,{taskId:u.id,workflowRunId:f.workflowRunId,raw:u.result??void 0}));};for(let c of this.resolveDbPaths()){if(!existsSync(c))continue;let u=C(c);try{let p=and(inArray(a.thread_id,e),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%'))),f=u.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(p,i):p).all();for(let _ of f)d(_.thread_id,_);let g=and(isNull(a.thread_id),or$1(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%'))),h=u.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 _ of h){let k=this.extractThreadIdFromCommand(_.command);!k||!o.has(k)||d(k,_);}}catch(p){throw new l("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{u.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 d=r.length>0?and(...r):void 0,c=n.db.select({count:sql`count(*)`}).from(a).where(d).get(),u=(e.sortDir??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at);return {rows:n.db.select().from(a).where(d).orderBy(u).limit(e.limit).offset(e.offset).all().map(et),total:c?.count??0}}catch(r){throw new l("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=vs(sql.raw("t.model"),sql.raw("t.metadata")),i=Yn(sql.raw("t.status")),d=Yr(sql.raw("t.metadata")),c=sql`
|
|
113
113
|
COALESCE(t.input_tokens, 0)
|
|
114
114
|
+ CASE
|
|
115
115
|
WHEN t.started_at >= ${gn}
|
|
@@ -279,7 +279,7 @@ ${r.join(`
|
|
|
279
279
|
GROUP BY ${a.caller_agent_id}, ${a.agent_id}
|
|
280
280
|
ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
|
|
281
281
|
LIMIT ${Is+1}
|
|
282
|
-
`),u=c.length>Is;return {edges:c.slice(0,Is).map(f=>({callerAgentId:f.caller_agent_id??null,agentId:f.agent_id,taskCount:f.task_count,totalTokens:f.input_tokens+f.output_tokens,outputTokens:f.output_tokens})),truncated:u}}catch(s){throw new l("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:c,metadata:u,...p})=>({...p,status:At({status:p.status,error:c,metadata:u})}))}catch(r){throw new l("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(),d=new Map;for(let u of i){if(!u.thread_id)continue;let p={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},f=d.get(u.thread_id);f?f.push(p):d.set(u.thread_id,[p]);}let c=[];for(let[u,p]of d){let f=p.filter(g=>g.agentId===e.targetAgentId).length;f<2||c.push({threadId:u,targetAgentTurnCount:f,turns:p});}return c.sort((u,p)=>{let f=u.turns[u.turns.length-1].startedAt,g=p.turns[p.turns.length-1].startedAt;return f<g?1:f>g?-1:0}),c.slice(0,r).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(r){throw new l("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}};});m();ie();pe();m();ie();fe();ce();pe();ue();So();var te=class extends l{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Qi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function kl(){let t=randomBytes(16),e="";for(let n of t)e+=Qi[n%Qi.length];return e.slice(0,12)}function vo(){return `c_${kl()}`}function Tl(t){return typeof t=="string"&&yr.includes(t)}function wl(t){return typeof t=="string"&&Rr.includes(t)}function Zt(t){if(!Tl(t))throw new te("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Zi(t){if(!wl(t))throw new te("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function ea(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new te("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function en(t){if(typeof t!="string"||t.trim().length===0)throw new te("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Ir(t){if(typeof t!="string"||t.trim().length===0)throw new te("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function St(t,e){return and(eq(I.code_group,t),or$1(isNull(I.workspace_id),eq(I.workspace_id,e)))}var Ao=class extends j{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 l("NOT_FOUND","Database not found");e&&mkdirSync(dirname(n),{recursive:true});let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(Zt(e),en(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(I).where(and(St(e,n),eq(I.is_archived,0))).orderBy(asc(I.sort_order),asc(I.code)).all()}catch(o){throw new l("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(Zt(e),en(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(I).where(St(e,n)).orderBy(asc(I.sort_order),asc(I.code)).all()}catch(o){throw new l("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(Zt(n),en(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)Ir(o);if(new Set(e.codes).size!==e.codes.length)throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(I).where(St(n,e.workspaceId)).all(),i=s.filter(h=>h.is_archived===0),d=new Set(s.map(h=>h.code)),c=new Set(i.map(h=>h.code)),u=e.codes.find(h=>!d.has(h));if(u)throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${u}`);if(e.codes.length!==i.length||e.codes.some(h=>!c.has(h)))throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let p=new Map(i.map(h=>[h.code,h])),f=e.codes.map(h=>{let _=p.get(h);if(!_)throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${h}`);return _}),g;for(let[h,_]of f.entries())_.sort_order!==h&&(g??=new Date().toISOString(),o.update(I).set({sort_order:h,updated_at:g}).where(and(eq(I.code_group,n),eq(I.code,_.code))).run());return o.select().from(I).where(St(n,e.workspaceId)).orderBy(asc(I.sort_order),asc(I.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(Zt(e),Ir(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 l("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){en(e.workspaceId);let n=ea(e.name);Zi(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:I.code}).from(I).where(and(St("THREAD_STATE",e.workspaceId),eq(I.is_archived,0),eq(I.code_name,n))).limit(1).get())throw new te("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(St("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),c=vo();for(;o.select({code:I.code}).from(I).where(and(eq(I.code_group,"THREAD_STATE"),eq(I.code,c))).limit(1).get();)c=vo();o.insert(I).values({code_group:"THREAD_STATE",code:c,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:d,updated_at:d}).run();let u=o.select().from(I).where(and(eq(I.code_group,"THREAD_STATE"),eq(I.code,c))).limit(1).get();if(!u)throw new l("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(Zt(e.group),Ir(e.code),en(e.workspaceId),e.name===void 0&&e.color===void 0)throw new te("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:ea(e.name);e.color!==void 0&&Zi(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 te("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 te("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let c=and(St(e.group,e.workspaceId),eq(I.is_archived,0));if(o.select({code:I.code}).from(I).where(and(c,eq(I.code_name,n),sql`${I.code} <> ${e.code}`)).limit(1).get())throw new te("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 d=o.select().from(I).where(and(eq(I.code_group,e.group),eq(I.code,e.code))).limit(1).get();if(!d)throw new l("DB_ERROR","Updated common code could not be read back");return d},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(Zt(e),Ir(n),en(r),typeof o!="boolean")throw new te("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let d=i.select().from(I).where(and(eq(I.code_group,e),eq(I.code,n))).limit(1).get();if(!d)throw new te("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(d.is_builtin===1)throw new te("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(d,r),!o&&d.code_name!==null&&i.select({code:I.code}).from(I).where(and(St(e,r),eq(I.is_archived,0),eq(I.code_name,d.code_name),ne(I.code,n))).limit(1).get())throw new te("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${d.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 c=i.select().from(I).where(and(eq(I.code_group,e),eq(I.code,n))).limit(1).get();if(!c)throw new l("DB_ERROR","Archived common code could not be read back");return c},{behavior:"immediate"})}catch(i){throw i instanceof l?i:new l("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 te("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};m();ie();fe();ce();pe();ue();m();function Oo(t){let e=Ce.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 ta(t){let e=Oo(t);return createHash("sha256").update(e).digest("hex")}function vr(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Co=class extends j{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{Yt(r.db);}catch(o){throw r.close(),o}return r}resolveSlug(e,n,r){let o=vr(basename(r)),i=`${vr(basename(dirname(r)))}-${o}`,d=[o,i];try{let c=u=>e.select({id:P.id}).from(P).where(and(eq(P.slug,u),ne(P.id,n))).limit(1).all().length>0;for(let u of d)if(!c(u))return u;for(let u=2;u<1e3;u+=1){let p=`${i}-${u}`;if(!c(p))return p}}catch{}return o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let n=e.db.select({id:P.id,slug:P.slug}).from(P).all(),r=0;for(let o of n)if(o.slug.includes("/")){let s=vr(o.slug.replace(/\//g,"-"));e.db.update(P).set({slug:s,updated_at:new Date().toISOString()}).where(eq(P.id,o.id)).run(),r+=1;}return {updated:r,checked:n.length}}catch(n){throw new l("DB_ERROR","Failed to normalize legacy slugs",n)}finally{e.close();}}ensureRow(e,n){let{id:r,slug:o,name:s,workspacePath:i}=n,d=new Date().toISOString();e.insert(P).values({id:r,slug:o,name:s,workspace_path:i,is_active:1,created_at:d,updated_at:d}).onConflictDoNothing().run(),e.update(P).set({workspace_path:i,updated_at:d}).where(and(eq(P.id,r),isNull(P.workspace_path))).run();}registerWorkspace(e){let n=Oo(e),r=this.openHandle(true);try{let o=ta(n),s=basename(n),i=this.resolveSlug(r.db,o,n);return this.ensureRow(r.db,{id:o,slug:i,name:s,workspacePath:n}),{id:o,slug:i}}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to register workspace",o)}finally{r.close();}}listProjects(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=e.isActive!==void 0?eq(P.is_active,e.isActive?1:0):void 0,o=n.db.select({count:sql`count(*)`}).from(P).where(r).get();return {rows:n.db.select().from(P).where(r).orderBy(desc(P.updated_at)).limit(e.limit).offset(e.offset).all(),total:o?.count??0}}catch(r){throw new l("DB_ERROR","Failed to list projects",r)}finally{n.close();}}findById(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(P).where(eq(P.id,e)).limit(1).get()??void 0}catch(r){throw new l("DB_ERROR","Failed to find workspace",r)}finally{n.close();}}toggleStar(e){let n=this.openHandle(true);try{let r=n.db.select({starred:P.starred}).from(P).where(eq(P.id,e)).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(P).set({starred:o}).where(eq(P.id,e)).run(),{starred:!!o}}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to toggle workspace star",r)}finally{n.close();}}findAgentsByProject(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${e} AND agent_id IS NOT NULL ORDER BY agent_id`).map(o=>o.agent_id)}catch(r){throw new l("DB_ERROR","Failed to find agents by project",r)}finally{n.close();}}findThreadsByProject(e,n){if(!this.dbExists())return {rows:[],total:0};let r=this.openHandle(false);try{let o=r.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);return {rows:r.db.all(sql`SELECT t.*,
|
|
282
|
+
`),u=c.length>Is;return {edges:c.slice(0,Is).map(f=>({callerAgentId:f.caller_agent_id??null,agentId:f.agent_id,taskCount:f.task_count,totalTokens:f.input_tokens+f.output_tokens,outputTokens:f.output_tokens})),truncated:u}}catch(s){throw new l("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:c,metadata:u,...p})=>({...p,status:At({status:p.status,error:c,metadata:u})}))}catch(r){throw new l("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(),d=new Map;for(let u of i){if(!u.thread_id)continue;let p={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},f=d.get(u.thread_id);f?f.push(p):d.set(u.thread_id,[p]);}let c=[];for(let[u,p]of d){let f=p.filter(g=>g.agentId===e.targetAgentId).length;f<2||c.push({threadId:u,targetAgentTurnCount:f,turns:p});}return c.sort((u,p)=>{let f=u.turns[u.turns.length-1].startedAt,g=p.turns[p.turns.length-1].startedAt;return f<g?1:f>g?-1:0}),c.slice(0,r).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(r){throw new l("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}};});m();ie();pe();m();ie();fe();ce();pe();ue();bo();var te=class extends l{reason;constructor(e,n="VALIDATION",r=e,o){super(n,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Qi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function kl(){let t=randomBytes(16),e="";for(let n of t)e+=Qi[n%Qi.length];return e.slice(0,12)}function vo(){return `c_${kl()}`}function Tl(t){return typeof t=="string"&&yr.includes(t)}function wl(t){return typeof t=="string"&&Rr.includes(t)}function Zt(t){if(!Tl(t))throw new te("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Zi(t){if(!wl(t))throw new te("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function ea(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new te("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function en(t){if(typeof t!="string"||t.trim().length===0)throw new te("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Ir(t){if(typeof t!="string"||t.trim().length===0)throw new te("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function bt(t,e){return and(eq(I.code_group,t),or$1(isNull(I.workspace_id),eq(I.workspace_id,e)))}var Ao=class extends j{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 l("NOT_FOUND","Database not found");e&&mkdirSync(dirname(n),{recursive:true});let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}listSelectable(e,n){if(Zt(e),en(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(I).where(and(bt(e,n),eq(I.is_archived,0))).orderBy(asc(I.sort_order),asc(I.code)).all()}catch(o){throw new l("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,n){if(Zt(e),en(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(I).where(bt(e,n)).orderBy(asc(I.sort_order),asc(I.code)).all()}catch(o){throw new l("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let n=e.group;if(Zt(n),en(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)Ir(o);if(new Set(e.codes).size!==e.codes.length)throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new te("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(bt(n,e.workspaceId)).all(),i=s.filter(h=>h.is_archived===0),d=new Set(s.map(h=>h.code)),c=new Set(i.map(h=>h.code)),u=e.codes.find(h=>!d.has(h));if(u)throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${u}`);if(e.codes.length!==i.length||e.codes.some(h=>!c.has(h)))throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let p=new Map(i.map(h=>[h.code,h])),f=e.codes.map(h=>{let _=p.get(h);if(!_)throw new te("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${h}`);return _}),g;for(let[h,_]of f.entries())_.sort_order!==h&&(g??=new Date().toISOString(),o.update(I).set({sort_order:h,updated_at:g}).where(and(eq(I.code_group,n),eq(I.code,_.code))).run());return o.select().from(I).where(bt(n,e.workspaceId)).orderBy(asc(I.sort_order),asc(I.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,n){if(Zt(e),Ir(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 l("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){en(e.workspaceId);let n=ea(e.name);Zi(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:I.code}).from(I).where(and(bt("THREAD_STATE",e.workspaceId),eq(I.is_archived,0),eq(I.code_name,n))).limit(1).get())throw new te("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(bt("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),c=vo();for(;o.select({code:I.code}).from(I).where(and(eq(I.code_group,"THREAD_STATE"),eq(I.code,c))).limit(1).get();)c=vo();o.insert(I).values({code_group:"THREAD_STATE",code:c,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:d,updated_at:d}).run();let u=o.select().from(I).where(and(eq(I.code_group,"THREAD_STATE"),eq(I.code,c))).limit(1).get();if(!u)throw new l("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(Zt(e.group),Ir(e.code),en(e.workspaceId),e.name===void 0&&e.color===void 0)throw new te("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:ea(e.name);e.color!==void 0&&Zi(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 te("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 te("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&s.is_archived===0){let c=and(bt(e.group,e.workspaceId),eq(I.is_archived,0));if(o.select({code:I.code}).from(I).where(and(c,eq(I.code_name,n),sql`${I.code} <> ${e.code}`)).limit(1).get())throw new te("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 d=o.select().from(I).where(and(eq(I.code_group,e.group),eq(I.code,e.code))).limit(1).get();if(!d)throw new l("DB_ERROR","Updated common code could not be read back");return d},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,n,r,o=true){if(Zt(e),Ir(n),en(r),typeof o!="boolean")throw new te("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let d=i.select().from(I).where(and(eq(I.code_group,e),eq(I.code,n))).limit(1).get();if(!d)throw new te("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(d.is_builtin===1)throw new te("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(d,r),!o&&d.code_name!==null&&i.select({code:I.code}).from(I).where(and(bt(e,r),eq(I.is_archived,0),eq(I.code_name,d.code_name),ne(I.code,n))).limit(1).get())throw new te("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${d.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 c=i.select().from(I).where(and(eq(I.code_group,e),eq(I.code,n))).limit(1).get();if(!c)throw new l("DB_ERROR","Archived common code could not be read back");return c},{behavior:"immediate"})}catch(i){throw i instanceof l?i:new l("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 te("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};m();ie();fe();ce();pe();ue();m();function Oo(t){let e=Ce.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 ta(t){let e=Oo(t);return createHash("sha256").update(e).digest("hex")}function vr(t){return t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Co=class extends j{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{Yt(r.db);}catch(o){throw r.close(),o}return r}resolveSlug(e,n,r){let o=vr(basename(r)),i=`${vr(basename(dirname(r)))}-${o}`,d=[o,i];try{let c=u=>e.select({id:P.id}).from(P).where(and(eq(P.slug,u),ne(P.id,n))).limit(1).all().length>0;for(let u of d)if(!c(u))return u;for(let u=2;u<1e3;u+=1){let p=`${i}-${u}`;if(!c(p))return p}}catch{}return o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let n=e.db.select({id:P.id,slug:P.slug}).from(P).all(),r=0;for(let o of n)if(o.slug.includes("/")){let s=vr(o.slug.replace(/\//g,"-"));e.db.update(P).set({slug:s,updated_at:new Date().toISOString()}).where(eq(P.id,o.id)).run(),r+=1;}return {updated:r,checked:n.length}}catch(n){throw new l("DB_ERROR","Failed to normalize legacy slugs",n)}finally{e.close();}}ensureRow(e,n){let{id:r,slug:o,name:s,workspacePath:i}=n,d=new Date().toISOString();e.insert(P).values({id:r,slug:o,name:s,workspace_path:i,is_active:1,created_at:d,updated_at:d}).onConflictDoNothing().run(),e.update(P).set({workspace_path:i,updated_at:d}).where(and(eq(P.id,r),isNull(P.workspace_path))).run();}registerWorkspace(e){let n=Oo(e),r=this.openHandle(true);try{let o=ta(n),s=basename(n),i=this.resolveSlug(r.db,o,n);return this.ensureRow(r.db,{id:o,slug:i,name:s,workspacePath:n}),{id:o,slug:i}}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to register workspace",o)}finally{r.close();}}listProjects(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=e.isActive!==void 0?eq(P.is_active,e.isActive?1:0):void 0,o=n.db.select({count:sql`count(*)`}).from(P).where(r).get();return {rows:n.db.select().from(P).where(r).orderBy(desc(P.updated_at)).limit(e.limit).offset(e.offset).all(),total:o?.count??0}}catch(r){throw new l("DB_ERROR","Failed to list projects",r)}finally{n.close();}}findById(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(P).where(eq(P.id,e)).limit(1).get()??void 0}catch(r){throw new l("DB_ERROR","Failed to find workspace",r)}finally{n.close();}}toggleStar(e){let n=this.openHandle(true);try{let r=n.db.select({starred:P.starred}).from(P).where(eq(P.id,e)).get();if(!r)return null;let o=r.starred?0:1;return n.db.update(P).set({starred:o}).where(eq(P.id,e)).run(),{starred:!!o}}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to toggle workspace star",r)}finally{n.close();}}findAgentsByProject(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${e} AND agent_id IS NOT NULL ORDER BY agent_id`).map(o=>o.agent_id)}catch(r){throw new l("DB_ERROR","Failed to find agents by project",r)}finally{n.close();}}findThreadsByProject(e,n){if(!this.dbExists())return {rows:[],total:0};let r=this.openHandle(false);try{let o=r.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);return {rows:r.db.all(sql`SELECT t.*,
|
|
283
283
|
(SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
|
|
284
284
|
FROM threads t
|
|
285
285
|
WHERE t.workspace_id = ${e}
|
|
@@ -299,7 +299,7 @@ ${r.join(`
|
|
|
299
299
|
MAX(seq) AS maxSeq
|
|
300
300
|
FROM task_log_events GROUP BY task_id`),n=e.reduce((r,o)=>r+o.eventCount,0);return {rows:e,eventCount:n}}function wt(t,e,n,r={}){return {taskId:t,kind:e,reason:n,...r}}function Eg(t,e,n){let r=[];for(let f of n.failures)f.kind==="malformed"?r.push(wt(f.taskId,"malformed-blob",f.reason)):f.kind==="mixed-source"?r.push(wt(f.taskId,"mixed-source",f.reason)):r.push(wt(f.taskId,"source-invariant",f.reason));let o=Rg(t),s=new Map(o.rows.map(f=>[f.taskId,f]));for(let f of o.rows){let g=n.tasks.get(f.taskId);if(!g){r.push(wt(null,"orphan-event",`Event rows reference missing task ${f.taskId}`,{actual:f.eventCount}));continue}(f.minSeq===null||f.minSeq<1||f.distinctSeqCount!==f.maxSeq)&&r.push(wt(g.id,"seq-gap","Task event sequence has a gap or invalid starting sequence",{expected:f.maxSeq??0,actual:f.distinctSeqCount})),g.log_storage==="events"&&g.last_log_seq!==f.eventCount&&r.push(wt(g.id,"count-mismatch","last_log_seq does not match task_log_events row count",{expected:g.last_log_seq??0,actual:f.eventCount}));}for(let f of n.tasks.values())f.log_storage==="events"&&!s.has(f.id)&&f.last_log_seq!==0&&r.push(wt(f.id,"count-mismatch","Event-source task has no rows for its last_log_seq",{expected:f.last_log_seq??0,actual:0}));for(let f of wn(t,`SELECT task_id AS taskId, seq, COUNT(*) AS duplicateCount
|
|
301
301
|
FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))r.push(wt(f.taskId,"duplicate-seq",`Duplicate task event sequence ${f.seq}`,{actual:f.duplicateCount,seq:f.seq}));let i=Tn(t,`SELECT COUNT(*) AS count FROM task_log_events
|
|
302
|
-
WHERE seq IS NULL OR seq < 1 OR timestamp IS NULL OR level IS NULL OR message IS NULL`)?.count??0;i>0&&r.push(wt(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:i}));let d=new Set(r.flatMap(f=>f.taskId?[f.taskId]:[])),c=r.map(f=>({taskId:f.taskId??"(orphan)",reason:f.reason,kind:f.kind==="malformed-blob"?"malformed":f.kind==="mixed-source"?"mixed-source":"metadata"})),u=c.filter(f=>f.kind==="malformed"),p={checkedTasks:n.taskCount,eventSourceTasks:n.eventSourceTasks,blobSourceTasks:n.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:r.filter(f=>f.kind==="orphan-event").length,failedTasks:d.size,issues:r};return no("verify",e,n,{ok:r.length===0,migratedTasks:n.eventSourceTasks,migratedEntries:o.eventCount,skippedTasks:n.candidateTaskCount,failedTasks:d.size,malformedRows:u,failures:c,remainingTaskCount:n.candidateTaskCount,verification:p})}function
|
|
302
|
+
WHERE seq IS NULL OR seq < 1 OR timestamp IS NULL OR level IS NULL OR message IS NULL`)?.count??0;i>0&&r.push(wt(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:i}));let d=new Set(r.flatMap(f=>f.taskId?[f.taskId]:[])),c=r.map(f=>({taskId:f.taskId??"(orphan)",reason:f.reason,kind:f.kind==="malformed-blob"?"malformed":f.kind==="mixed-source"?"mixed-source":"metadata"})),u=c.filter(f=>f.kind==="malformed"),p={checkedTasks:n.taskCount,eventSourceTasks:n.eventSourceTasks,blobSourceTasks:n.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:r.filter(f=>f.kind==="orphan-event").length,failedTasks:d.size,issues:r};return no("verify",e,n,{ok:r.length===0,migratedTasks:n.eventSourceTasks,migratedEntries:o.eventCount,skippedTasks:n.candidateTaskCount,failedTasks:d.size,malformedRows:u,failures:c,remainingTaskCount:n.candidateTaskCount,verification:p})}function Sg(t){if(t.mode!=="apply"&&t.batchTasks!==void 0)throw new Error("--batch-tasks is only valid with --apply");if(t.batchTasks!==void 0&&(!Number.isInteger(t.batchTasks)||t.batchTasks<1))throw new Error("--batch-tasks must be a positive integer")}async function bg(t){Sg(t);let e=so(t.dbPath),n=ec(e,t.mode!=="apply");try{pg(n);let r=gg(n),o=hg(n);if(t.mode==="verify")return {...Eg(n,e,r),activeTaskCount:o};if(t.mode==="dry-run")return no("dry-run",e,r,{ok:r.failures.length===0,activeTaskCount:o,skippedTasks:r.eventSourceTasks,remainingTaskCount:r.candidateTaskCount});let s=t.backupPath??ic(e),i=oc(e,r.entryCount,s);if(!i.freeSpaceGatePassed)return no("apply",e,r,{ok:!1,activeTaskCount:o,blockedReason:`Apply blocked: available free space (${i.availableFreeSpaceBytes} bytes) is below the required ${i.requiredFreeSpaceBytes} bytes (including a ${i.minimumFreeSpaceReserveBytes} byte reserve)`,skippedTasks:r.eventSourceTasks,remainingTaskCount:r.candidateTaskCount},i);let d=await yg(n,e,s),c=[...r.failures],u=t.batchTasks===void 0?r.candidateIds:r.candidateIds.slice(0,t.batchTasks),p=t.batchTasks??Math.max(u.length,1),f=0,g=0,h=0,_=[...i.warnings];for(let[k,T]of u.entries()){try{let E=wg(n,T);E.status==="migrated"&&(f+=1,g+=E.entryCount,h+=E.sourceBytes);}catch(E){c.push(Hs(E,T));}if((k+1)%p===0||k===u.length-1){let E=Xn(n);E&&_.push(E);}}return no("apply",e,r,{ok:c.length===0,activeTaskCount:o,backupPath:d,backupMethod:"sqlite-online-backup",migratedTasks:f,migratedEntries:g,logicalSourceBytesRemoved:h,failedTasks:sc(c),failures:c,malformedRows:r.malformedRows,remainingTaskCount:mg(n),skippedTasks:r.eventSourceTasks,warnings:_},i)}finally{n.close();}}function Ig(t){return basename(t)}Cr();Gn();as();var ao=["success","failed","completed"],uc=1440*60*1e3,lc=1,Ng=2048,Us=64*1024*1024,Bs=[{key:"usageBackfill",field:"metadata.usageBackfill",before:"before_usage_backfill",after:"after_usage_backfill"},{key:"usageAccounting",field:"metadata.usageAccounting",before:"before_usage_accounting",after:"after_usage_accounting"},{key:"usageAccountingReason",field:"metadata.usageAccountingReason",before:"before_usage_accounting_reason",after:"after_usage_accounting_reason"}],ac=["run_epoch","completed_at","input_tokens","output_tokens","cached_input_tokens","cost_usd","model",...Bs.map(t=>t.field)],xg=20,Cg=["pre-instrumentation","provider-no-usage","suppressed-by-adapter","not-captured"];function pc(){return ht("better-sqlite3")}function js(t,e){let n=Ge(t),r=t===":memory:";if(!r&&!existsSync(n))throw new Error(`Database not found: ${n}`);let o=new(pc())(n,{readonly:e,fileMustExist:!r,timeout:5e3});return o.pragma("foreign_keys = ON"),o.pragma("busy_timeout = 5000"),o}function Qn(t,e,n=[]){return t.prepare(e).all(...n)}function Gt(t,e,n=[]){return t.prepare(e).get(...n)}function Nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Kt(t){if(!t)return {};try{let e=JSON.parse(t);return Nt(e)?{...e}:{}}catch{return {}}}function fc(t){let e=t.provider;if(!(typeof e!="string"||e.trim().length===0))return e.trim()}function gc(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Pg(t){return t??"unknown"}function Dg(t){return ao.includes(t)}function Lg(t){return t==="plugin/mock"}function hc(t,e,n){return Dg(t.status)&&!kn(t)&&t.agent_id!=="workflow"&&t.platform!=="workflow"&&t.platform!=="mcp"&&t.agent_id!=="direct"&&n.direct_call!==true&&!Lg(e)}function Mg(t,e){let n=t.usageBackfill;return Nt(n)&&Object.prototype.hasOwnProperty.call(n,String(e))}function Hg(t){return typeof t=="string"&&Cg.includes(t)}function mc(t,e){return t.usageAccounting==="recorded"||t.usageAccounting==="unavailable"&&Hg(t.usageAccountingReason)?true:Mg(t,e)}function Ug(t){return Qn(t,`SELECT id, agent_id, status, completed_at, metadata, model, platform, run_epoch,
|
|
303
303
|
input_tokens, output_tokens, cached_input_tokens, cost_usd
|
|
304
304
|
FROM tasks
|
|
305
305
|
WHERE status IN (?, ?, ?)
|
|
@@ -362,7 +362,7 @@ ${r.join(`
|
|
|
362
362
|
FROM tasks WHERE id = ?`,[e.id]);if(!r)return {taskId:e.id,fields:[...ac]};let o=rh(r,e);if(o.length>0)return {taskId:e.id,fields:o};let s=oh(r.metadata,e);return t.prepare(`UPDATE tasks
|
|
363
363
|
SET run_epoch = ?, completed_at = ?, input_tokens = ?, output_tokens = ?,
|
|
364
364
|
cached_input_tokens = ?, cost_usd = ?, model = ?, metadata = ?
|
|
365
|
-
WHERE id = ?`).run(e.before_run_epoch,e.before_completed_at,e.before_input_tokens,e.before_output_tokens,e.before_cached_input_tokens,e.before_cost_usd,e.before_model,s,e.id).changes===1?void 0:{taskId:e.id,fields:[...ac]}}).immediate()}function ih(t){if(!Gt(t,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tasks'"))throw new Error("Usage backfill requires the tasks table");let n=new Set(Qn(t,"PRAGMA table_info(tasks)").map(i=>i.name)),o=["id","agent_id","status","completed_at","metadata","model","platform","run_epoch","input_tokens","output_tokens","cached_input_tokens","cost_usd"].filter(i=>!n.has(i));if(o.length>0)throw new Error(`Usage backfill requires task columns: ${o.join(", ")}`);if(!Gt(t,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'task_log_events'"))throw new Error("Usage backfill requires the task_log_events table")}function ah(t,e,n,r){return {mode:t,ok:true,dbPath:e,scannedTasks:n.scannedTasks,terminalTasks:n.terminalTasks,rawTargetTasks:n.rawTargetRows.length,candidateTasks:n.candidates.length,recoveredTasks:0,unavailableTasks:0,deferredTasks:0,changedTasks:0,wouldChangeTasks:0,restored:0,skippedConflict:0,conflictSamples:[],accountingTasks:n.accountingTasks,remainingTargetTasks:n.candidates.length,providerDistribution:{},reasonCounts:Wg(),estimatedFreeSpaceBytes:r.estimatedFreeSpaceBytes,requiredFreeSpaceBytes:r.requiredFreeSpaceBytes,availableFreeSpaceBytes:r.availableFreeSpaceBytes,minimumFreeSpaceReserveBytes:r.minimumFreeSpaceReserveBytes,freeSpaceGatePassed:r.freeSpaceGatePassed,failures:[],warnings:[...r.warnings]}}function dh(t,e){for(let n of e)Bg(t.providerDistribution,n.candidate.provider,n.outcome),jg(t.reasonCounts,n.outcome==="unavailable"?n.reason:void 0),n.outcome==="recovered"&&(t.recoveredTasks+=1),n.outcome==="unavailable"&&(t.unavailableTasks+=1),n.outcome==="deferred"&&(t.deferredTasks+=1);t.providerDistribution=zg(t.providerDistribution),t.wouldChangeTasks=t.recoveredTasks+t.unavailableTasks;}function ch(t){if(!["dry-run","apply","verify","restore"].includes(t.mode))throw new Error(`Unsupported usage backfill mode: ${t.mode}`);if(t.backupPath&&t.mode!=="apply")throw new Error("--backup is only valid with --apply");if(t.restorePath&&t.mode!=="restore")throw new Error("--restore is only valid with restore mode");if(t.mode==="restore"&&!t.restorePath)throw new Error("Restore mode requires a usage undo snapshot path")}async function uh(t){ch(t);let e=so(t.dbPath),n=$g(t.now),r=new Date(n).toISOString(),o=t.mode==="restore"?th(t.restorePath,e):void 0,s=js(e,t.mode!=="apply"&&t.mode!=="restore"),i;try{ih(s);let d=$s(s),c=t.mode==="apply"&&d.candidates.length>0?t.backupPath??kc(e):void 0,u=Jg(e,d.candidates.length,c),p=ah(t.mode,e,d,u);if(o){p.backupPath=o.path,p.snapshotPath=o.path;for(let T of o.rows)try{let E=sh(s,T);E?(p.skippedConflict+=1,p.conflictSamples.length<xg&&p.conflictSamples.push(E)):p.restored+=1;}catch(E){p.failures.push({taskId:T.id,reason:E instanceof Error?E.message:String(E)});}let _=$s(s);p.accountingTasks=_.accountingTasks,p.remainingTargetTasks=_.candidates.length,p.ok=p.failures.length===0;let k=Xn(s);return k&&p.warnings.push(k),p}if(t.mode==="verify")return p;if(t.mode==="apply"&&!u.freeSpaceGatePassed&&d.candidates.length>0)return p.ok=!1,p.blockedReason=`Apply blocked: available free space (${u.availableFreeSpaceBytes} bytes) is below the required ${u.requiredFreeSpaceBytes} bytes (including a ${u.minimumFreeSpaceReserveBytes} byte reserve)`,p;if(d.candidates.length===0)return p;let f=new Mt({dbPath:e}),g=[];for(let _ of d.candidates){let k=qg(_,f,n);g.push(k);}if(dh(p,g),t.mode==="dry-run"&&(p.changedTasks=0),t.mode==="apply"){i=Qg(e,c,r,{candidates:g.length,recovered:p.recoveredTasks,unavailable:p.unavailableTasks,deferred:p.deferredTasks}),p.backupPath=i.path,p.snapshotPath=i.path,p.backupMethod="row-undo-snapshot";for(let k of g)if(k.outcome!=="deferred")try{Vg(s,i,k,r)==="changed"&&(p.changedTasks+=1);}catch(T){p.failures.push({taskId:k.candidate.id,reason:T instanceof Error?T.message:String(T)});}let _=i.path;i.db.close(),i=void 0,Tc(_);}let h=$s(s);if(p.accountingTasks=h.accountingTasks,p.remainingTargetTasks=h.candidates.length,p.ok=p.failures.length===0,t.mode==="apply"){let _=Xn(s);_&&p.warnings.push(_);}return p}finally{i&&i.db.close(),s.close();}}Cr();m();ie();fe();ce();pe();ue();jn();function co(t){return {...t,status:At(t)}}function mh({metadata:t,...e}){return {...e,status:At({...e,metadata:t})}}var Ec=900;function uo(t){return t!==null&&t!==""}function _h(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":uo(t.parent_task_id)||uo(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function kh(t){return {origin:t.created_by_kind==="human"?"direct":"delegated",delegatedByAgentId:t.created_by_kind==="agent"&&uo(t.created_by_id)?t.created_by_id:null}}function
|
|
365
|
+
WHERE id = ?`).run(e.before_run_epoch,e.before_completed_at,e.before_input_tokens,e.before_output_tokens,e.before_cached_input_tokens,e.before_cost_usd,e.before_model,s,e.id).changes===1?void 0:{taskId:e.id,fields:[...ac]}}).immediate()}function ih(t){if(!Gt(t,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tasks'"))throw new Error("Usage backfill requires the tasks table");let n=new Set(Qn(t,"PRAGMA table_info(tasks)").map(i=>i.name)),o=["id","agent_id","status","completed_at","metadata","model","platform","run_epoch","input_tokens","output_tokens","cached_input_tokens","cost_usd"].filter(i=>!n.has(i));if(o.length>0)throw new Error(`Usage backfill requires task columns: ${o.join(", ")}`);if(!Gt(t,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'task_log_events'"))throw new Error("Usage backfill requires the task_log_events table")}function ah(t,e,n,r){return {mode:t,ok:true,dbPath:e,scannedTasks:n.scannedTasks,terminalTasks:n.terminalTasks,rawTargetTasks:n.rawTargetRows.length,candidateTasks:n.candidates.length,recoveredTasks:0,unavailableTasks:0,deferredTasks:0,changedTasks:0,wouldChangeTasks:0,restored:0,skippedConflict:0,conflictSamples:[],accountingTasks:n.accountingTasks,remainingTargetTasks:n.candidates.length,providerDistribution:{},reasonCounts:Wg(),estimatedFreeSpaceBytes:r.estimatedFreeSpaceBytes,requiredFreeSpaceBytes:r.requiredFreeSpaceBytes,availableFreeSpaceBytes:r.availableFreeSpaceBytes,minimumFreeSpaceReserveBytes:r.minimumFreeSpaceReserveBytes,freeSpaceGatePassed:r.freeSpaceGatePassed,failures:[],warnings:[...r.warnings]}}function dh(t,e){for(let n of e)Bg(t.providerDistribution,n.candidate.provider,n.outcome),jg(t.reasonCounts,n.outcome==="unavailable"?n.reason:void 0),n.outcome==="recovered"&&(t.recoveredTasks+=1),n.outcome==="unavailable"&&(t.unavailableTasks+=1),n.outcome==="deferred"&&(t.deferredTasks+=1);t.providerDistribution=zg(t.providerDistribution),t.wouldChangeTasks=t.recoveredTasks+t.unavailableTasks;}function ch(t){if(!["dry-run","apply","verify","restore"].includes(t.mode))throw new Error(`Unsupported usage backfill mode: ${t.mode}`);if(t.backupPath&&t.mode!=="apply")throw new Error("--backup is only valid with --apply");if(t.restorePath&&t.mode!=="restore")throw new Error("--restore is only valid with restore mode");if(t.mode==="restore"&&!t.restorePath)throw new Error("Restore mode requires a usage undo snapshot path")}async function uh(t){ch(t);let e=so(t.dbPath),n=$g(t.now),r=new Date(n).toISOString(),o=t.mode==="restore"?th(t.restorePath,e):void 0,s=js(e,t.mode!=="apply"&&t.mode!=="restore"),i;try{ih(s);let d=$s(s),c=t.mode==="apply"&&d.candidates.length>0?t.backupPath??kc(e):void 0,u=Jg(e,d.candidates.length,c),p=ah(t.mode,e,d,u);if(o){p.backupPath=o.path,p.snapshotPath=o.path;for(let T of o.rows)try{let E=sh(s,T);E?(p.skippedConflict+=1,p.conflictSamples.length<xg&&p.conflictSamples.push(E)):p.restored+=1;}catch(E){p.failures.push({taskId:T.id,reason:E instanceof Error?E.message:String(E)});}let _=$s(s);p.accountingTasks=_.accountingTasks,p.remainingTargetTasks=_.candidates.length,p.ok=p.failures.length===0;let k=Xn(s);return k&&p.warnings.push(k),p}if(t.mode==="verify")return p;if(t.mode==="apply"&&!u.freeSpaceGatePassed&&d.candidates.length>0)return p.ok=!1,p.blockedReason=`Apply blocked: available free space (${u.availableFreeSpaceBytes} bytes) is below the required ${u.requiredFreeSpaceBytes} bytes (including a ${u.minimumFreeSpaceReserveBytes} byte reserve)`,p;if(d.candidates.length===0)return p;let f=new Mt({dbPath:e}),g=[];for(let _ of d.candidates){let k=qg(_,f,n);g.push(k);}if(dh(p,g),t.mode==="dry-run"&&(p.changedTasks=0),t.mode==="apply"){i=Qg(e,c,r,{candidates:g.length,recovered:p.recoveredTasks,unavailable:p.unavailableTasks,deferred:p.deferredTasks}),p.backupPath=i.path,p.snapshotPath=i.path,p.backupMethod="row-undo-snapshot";for(let k of g)if(k.outcome!=="deferred")try{Vg(s,i,k,r)==="changed"&&(p.changedTasks+=1);}catch(T){p.failures.push({taskId:k.candidate.id,reason:T instanceof Error?T.message:String(T)});}let _=i.path;i.db.close(),i=void 0,Tc(_);}let h=$s(s);if(p.accountingTasks=h.accountingTasks,p.remainingTargetTasks=h.candidates.length,p.ok=p.failures.length===0,t.mode==="apply"){let _=Xn(s);_&&p.warnings.push(_);}return p}finally{i&&i.db.close(),s.close();}}Cr();m();ie();fe();ce();pe();ue();jn();function co(t){return {...t,status:At(t)}}function mh({metadata:t,...e}){return {...e,status:At({...e,metadata:t})}}var Ec=900;function uo(t){return t!==null&&t!==""}function _h(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":uo(t.parent_task_id)||uo(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function kh(t){return {origin:t.created_by_kind==="human"?"direct":"delegated",delegatedByAgentId:t.created_by_kind==="agent"&&uo(t.created_by_id)?t.created_by_id:null}}function Sc(t){return t==="direct"?sql`created_by_kind = 'human'`:t==="delegated"?sql`created_by_kind IN ('agent', 'system', 'unknown')`:sql`created_by_kind IS NOT NULL`}var Vt=class extends l{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function Zn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Th(t){let n=Zn(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 Ws=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,n){return e.db.select({id:P.id}).from(P).where(eq(P.id,n)).limit(1).get()?n:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
366
366
|
SELECT 1 FROM tasks parent
|
|
367
367
|
WHERE parent.id = ${e}.parent_task_id
|
|
368
368
|
AND parent.thread_id = ${e}.thread_id
|
|
@@ -434,11 +434,11 @@ ${r.join(`
|
|
|
434
434
|
FROM root
|
|
435
435
|
LEFT JOIN tasks parent ON parent.id = root.parent_task_id
|
|
436
436
|
WHERE root.rn = 1
|
|
437
|
-
`}findRecordedThreadOriginsQuery(e,n){let r=[sql`id IN (${sql.join(e.map(o=>sql`${o}`),sql`, `)})`,
|
|
437
|
+
`}findRecordedThreadOriginsQuery(e,n){let r=[sql`id IN (${sql.join(e.map(o=>sql`${o}`),sql`, `)})`,Sc()];return n&&r.unshift(sql`workspace_id = ${n}`),sql`
|
|
438
438
|
SELECT id AS thread_id, created_by_kind, created_by_id
|
|
439
439
|
FROM threads INDEXED BY idx_threads_workspace_created_by_kind_updated_at
|
|
440
440
|
WHERE ${sql.join(r,sql` AND `)}
|
|
441
|
-
`}findThreadsByOriginQuery(e,n){let r=[
|
|
441
|
+
`}findThreadsByOriginQuery(e,n){let r=[Sc(e)];return n&&r.unshift(sql`workspace_id = ${n}`),sql`
|
|
442
442
|
SELECT *
|
|
443
443
|
FROM threads INDEXED BY idx_threads_workspace_created_by_kind_updated_at
|
|
444
444
|
WHERE ${sql.join(r,sql` AND `)}
|
|
@@ -456,7 +456,7 @@ ${r.join(`
|
|
|
456
456
|
message_count = message_count + 1,
|
|
457
457
|
updated_at = ${s}
|
|
458
458
|
WHERE id = ${e}
|
|
459
|
-
`),u},{behavior:"immediate"})}}catch(s){throw s instanceof l?s:new l("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(w).set({last_message:n,updated_at:s}).where(eq(w.id,e)).run();}catch(s){throw s instanceof l?s:new l("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(w).set(o).where(eq(w.id,e)).run();}catch(o){throw o instanceof l?o:new l("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 Vt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(c=>c!=="priority"&&c!=="state"))return new Vt("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 Vt("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let c of [i.priority,i.state])if(c!=null&&(typeof c!="string"||c.length===0))return new Vt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let c=r?and(eq(w.id,e),eq(w.workspace_id,r)):eq(w.id,e);return d.db.transaction(u=>{let p=u.select({metadata:w.metadata}).from(w).where(c).get();if(!p)return null;let f=Zn(p.metadata),g=f.threadTitle,h=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};i.priority===null?delete h.priority:i.priority!==void 0&&(h.priority=i.priority),i.state===null?delete h.state:i.state!==void 0&&(h.state=i.state),Object.keys(h).length>0?f.threadTitle=h:delete f.threadTitle;let _=Object.keys(f).length>0?JSON.stringify(f):null,k=new Date().toISOString();u.update(w).set({metadata:_,updated_at:k}).where(c).run();let T=u.select({metadata:w.metadata}).from(w).where(c).get();if(!T)throw new l("DB_ERROR","Thread-title metadata update could not be read back");let E=Th(T.metadata);return {threadId:e,priority:E.priority,state:E.state}},{behavior:"immediate"})}catch(c){throw c instanceof l?c:new l("DB_ERROR","Failed to patch thread-title metadata",c)}finally{d.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?and(eq(w.id,e),eq(w.workspace_id,n)):eq(w.id,e);return r.db.transaction(s=>{let i=s.select({pinned:w.pinned,metadata:w.metadata}).from(w).where(o).get();if(!i)return null;let d=i.pinned?0:1,c=Zn(i.metadata);if(d){let u=n?and(eq(w.pinned,1),eq(w.workspace_id,n)):eq(w.pinned,1),p=s.select({metadata:w.metadata}).from(w).where(u).all(),f=null;for(let g of p){let h=Zn(g.metadata);typeof h.pinOrder=="number"&&(f===null||h.pinOrder<f)&&(f=h.pinOrder);}c.pinOrder=f===null?0:f-1;}else delete c.pinOrder;return s.update(w).set({pinned:d,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(o).run(),{pinned:!!d}},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("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(w.id,e[s]),eq(w.workspace_id,n)):eq(w.id,e[s]),d=o.select({metadata:w.metadata}).from(w).where(i).get();if(!d)continue;let c=Zn(d.metadata);c.pinOrder=s+1,o.update(w).set({metadata:JSON.stringify(c)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?and(eq(w.id,e),eq(w.workspace_id,n)):eq(w.id,e),s=r.db.select({starred:w.starred}).from(w).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(w).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let d=n?and(eq(w.id,e),eq(w.workspace_id,n)):eq(w.id,e);return i.db.transaction(u=>{let p=u.select({metadata:w.metadata}).from(w).where(d).get();if(!p)return null;let f=p.metadata?JSON.parse(p.metadata):{},g=f.overdrive??{},h=o?.defaultTurns??g.defaultTurns??3,_=o?.updatedBy??"ui",k=new Date().toISOString(),T,E,L,U;switch(r){case "enable-count":{let R=o?.turns??h,O=o?.consumeCurrent?Math.max(R-1,0):R;T=O>0?"count":"off",E=O,L=!0,U="count";break}case "enable-latch":{T="latch",E=0,L=!0,U="latch";break}case "disable":{T="off",E=0,L=!1;break}default:{let R=g.state??"off",O=typeof g.remaining=="number"?g.remaining:0;if(R==="count"&&O>0){let N=O-1;N<=0?(T="off",E=0):(T="count",E=N),L=!0,U="count";}else R==="latch"?(T="latch",E=0,L=!0,U="latch"):(T="off",E=0,L=!1);break}}return f.overdrive={state:T,remaining:E,defaultTurns:h,updatedAt:k,updatedBy:_},u.update(w).set({metadata:JSON.stringify(f),updated_at:k}).where(d).run(),{applied:L,appliedMode:U,state:T,remaining:E}},{behavior:"immediate"})}catch(d){throw d instanceof l?d:new l("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};m();ie();fe();ce();pe();ue();m();var Ic=["urgent","high","medium","low"],vc=["investigating","in-progress","in-review","on-hold","done"],er="custom:";var wh=new Set(Ic),yh=new Set(vc),Rh={urgent:"U \uAE34\uAE09 Urgent",high:"P0 \uAE09\uD568 High",medium:"P1 \uC911\uC694 Medium",low:"P2 \uBCF4\uD1B5 Low"},zs={investigating:"\uC870\uC0AC\uC911 Looking into","in-progress":"\uC9C4\uD589\uC911 In progress","in-review":"\uAC80\uD1A0\uC911 In review","on-hold":"\uBCF4\uB958 On hold",done:"\uC644\uB8CC Done"};function Sc(t,e){return !e||e.includes(t)?e??t:`${t} ${e}`}function tr(t){return typeof t=="string"&&wh.has(t)}function nr(t){if(typeof t!="string")return false;if(yh.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(er))return false;let e=t.slice(er.length);return e.length>=1&&e.length<=20}function Ac(t){if(t.startsWith(er))return t.slice(er.length)}function Gs(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 Eh(t){let e=Gs(t);return !!e&&Object.prototype.hasOwnProperty.call(e,"threadTitle")}function lo(t){let e=Gs(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return tr(r.priority)&&(o.priority=r.priority),nr(r.state)&&(o.state=r.state),o}function Ks(t,e){let n=Gs(t)??{},r={...lo(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)}function bh(t,e=new Map){let n=[];return t.priority&&n.push(Sc(Rh[t.priority],e.get(t.priority))),t.state&&(t.state.startsWith(er)?n.push(Ac(t.state)??""):zs[t.state]?n.push(Sc(zs[t.state],e.get(t.state))):e.has(t.state)?n.push(t.state,e.get(t.state)??""):t.state.startsWith("c_")?n.push(t.state):n.push(zs[t.state]??"")),n.filter(Boolean).join(" ")}function Oc(t,e){if(!t||t.trim().length===0)return;let n=new Set,r=false,o=false;for(let s of t.split(",")){let i=s.trim();if(i){if(i==="none"){r=true,o=true;continue}e(i)&&(n.add(i),o=true);}}if(o)return {values:n,includeNone:r}}function Sh(t){return Oc(t,tr)}function Ih(t){return Oc(t,nr)}function vh(t,e){return e?t?e.values.has(t):e.includeNone:true}jn();var Dc="regeneration_replaced",Ch="THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS",Lc="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED",Ph="THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED",Mc="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",ho=class extends l{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 ho{},mo=class extends l{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Dh=new Set(Wi),Lh=new Set(ji),Mh=new Set(zi),Hh=new Set(Gi),Uh=50,xc=100,Cc=280,Pc=40,$h=new Set(Ki),po=["queued","running"];function Js(t){return $h.has(t)}function X(t){throw new l("VALIDATION",t)}function rt(t){throw new l("NOT_FOUND",t)}function M(t,e){(typeof t!="string"||t.trim().length===0)&&X(`${e} is required`);}function or(t={}){let e=t.actor??t,n=e.actorType??"system";return Dh.has(n)||X(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&X("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Fh(t){M(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&M(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&X("title must not be empty"),t.title.length>120&&X("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!tr(t.priority)&&X(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!nr(t.state)&&X(`invalid state: ${String(t.state)}`);}function qh(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&X("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)&&X(`${n} must be a non-negative integer`);let e=t.limit??Uh;return (!Number.isInteger(e)||e<1||e>xc)&&X(`limit must be between 1 and ${xc}`),e}function Xs(t){typeof t!="string"&&X("text is required");let e=t.trim();return e.length===0&&X("text must not be empty"),e.length>Cc&&X(`text must be at most ${Cc} characters`),e}function yt(t,e){return M(t??"",e),t}function Qs(t){Hh.has(t)||X(`invalid highlight kind: ${String(t)}`);}function Bh(t){Mh.has(t)||X(`invalid highlight source: ${String(t)}`);}function jh(t){M(t.threadId,"threadId"),M(t.workspaceId,"workspaceId");let e=t.source??"manual";Bh(e),Qs(t.kind);let n=Xs(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let p=t.taskId??(r&&o&&r===o?r:void 0),f=yt(p,"taskId");return (r!==f||o!==f)&&X("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:f,coversToTaskId:f,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=yt(r,"coversFromTaskId"),i=yt(o,"coversToTaskId"),d=t.sourceTaskId??s,c=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),u=t.contentFingerprint??t.idempotencyKey??null;return yt(d??void 0,"sourceTaskId"),yt(c??void 0,"detectorVersion"),yt(u??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:d,detectorVersion:c,contentFingerprint:u}}function Wh(t,e){(!t||typeof t!="object")&&X(`candidates[${e}] is required`),Qs(t.kind);let n=Xs(t.text),r=yt(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=yt(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=yt(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||sa("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return M(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function zh(t){Array.isArray(t)||X("candidates must be an array"),t.length>Pc&&X(`candidates must contain at most ${Pc} items`);let e=new Map;for(let[n,r]of t.entries()){let o=Wh(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function dr(t){let e=lo(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 Gh(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&X("event payload must be a JSON object"),e}catch(e){throw new l("VALIDATION","event payload must be JSON serializable",e)}}function sr(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${V.seq}), 0)`}).from(V).where(eq(V.thread_id,e)).get()?.maxSeq??0}function ir(t,e){return !!t.select({id:V.id}).from(V).where(eq(V.thread_id,e)).limit(1).get()}function Jt(t,e){Lh.has(e.type)||X(`invalid thread event type: ${String(e.type)}`);let n=He("the");t.insert(V).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:Gh(e.payload),created_at:e.createdAt}).run();let r=t.select().from(V).where(eq(V.id,n)).get();if(!r)throw new l("DB_ERROR","Thread event insert did not return a row");return r}function ar(t,e,n,r,o){let s=dr(e);Jt(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 go(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 fo(t,e,n,r,o,s,i){let d=o==="thread.highlight.created"?go(e):{before:i?go({...e,...i,id:e.id}):void 0,after:go(e)};return Jt(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:d})}function Kh(t,e,n,r,o,s){return Jt(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:go(e),...s??{}}})}var Ys=class extends j{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 l("NOT_FOUND","Database not found");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=eq(w.id,n),s=r===void 0?o:r===null?and(o,isNull(w.workspace_id)):and(o,eq(w.workspace_id,r));return e.select().from(w).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(B).where(eq(B.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(M(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:w.workspace_id}).from(w).where(eq(w.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(M(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?dr(o):null}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Fh(e);let n=or(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||rt(`Thread ${e.threadId} not found`);let d=dr(i),c=e.title!==void 0,u=c&&e.title!==d.title,p=c&&i.title_locked!==1,f=e.priority!==void 0&&e.priority!==d.priority,g=e.state!==void 0&&e.state!==d.state,h=u||f||g;if(!h&&!p)return d;let _=i.metadata;(f||g)&&(_=Ks(i.metadata,{priority:e.priority,state:e.state}));let k={};if(h&&(k.metadata=_,k.updated_at=r),u&&(k.title=e.title),c&&(k.title_locked=1),s.update(w).set(k).where(e.workspaceId===void 0?eq(w.id,e.threadId):e.workspaceId===null?and(eq(w.id,e.threadId),isNull(w.workspace_id)):and(eq(w.id,e.threadId),eq(w.workspace_id,e.workspaceId))).run(),!h){let L={...i,title_locked:1};return dr(L)}let T=sr(s,i.id)+1;ir(s,i.id)||(ar(s,i,n,r,T),T+=1),u&&(Jt(s,{threadId:i.id,seq:T,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),T+=1),f&&(Jt(s,{threadId:i.id,seq:T,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),T+=1),g&&Jt(s,{threadId:i.id,seq:T,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let E={...i,title:u?e.title:i.title,metadata:_,title_locked:c?1:i.title_locked,updated_at:r};return dr(E)},{behavior:"immediate"})}catch(s){throw s instanceof l?s:new l("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(M(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(${V.seq}), 0)`}).from(V).where(eq(V.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(M(e,"threadId"),M(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,[...cs,"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 l?o:new l("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.requestId,"requestId"),M(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&M(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||rt(`Thread ${e.threadId} not found`);let i=o.select().from(B).where(and(eq(B.thread_id,s.id),eq(B.request_id,e.requestId))).orderBy(desc(B.requested_at),desc(B.id)).limit(1).get();if(i)return {run:i,created:!1};let d=o.select().from(B).where(and(eq(B.thread_id,s.id),inArray(B.status,po))).orderBy(asc(B.requested_at),asc(B.id)).limit(1).get();if(d)throw new mo(d);let c=e.runId??He("thr");o.insert(B).values({id:c,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 u=o.select().from(B).where(eq(B.id,c)).get();if(!u)throw new l("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:u,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("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(M(e,"runId"),n!==void 0&&M(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 l?o:new l("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(M(e,"threadId"),M(n,"workspaceId"),M(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(B).where(and(eq(B.thread_id,e),eq(B.request_id,r))).orderBy(desc(B.requested_at),desc(B.id)).limit(1).get()??null:null}catch(s){throw s instanceof l?s:new l("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){M(e,"runId"),n!==void 0&&M(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||rt(`Highlight regeneration run ${e} not found`),Js(i.status)||X(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(B).set({status:"running",started_at:r}).where(and(eq(B.id,i.id),eq(B.status,"queued"))).run();let d=s.select().from(B).where(eq(B.id,i.id)).get();if(!d)throw new l("DB_ERROR","Highlight regeneration run start did not return a row");return d},{behavior:"immediate"})}catch(s){throw s instanceof l?s:new l("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){M(e.runId,"runId"),M(e.errorCode,"errorCode"),e.workspaceId!==void 0&&M(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||rt(`Highlight regeneration run ${e.runId} not found`),Js(s.status)||X(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(B).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(B.id,s.id),inArray(B.status,po))).run();let i=o.select().from(B).where(eq(B.id,s.id)).get();if(!i)throw new l("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=Lc){M(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(B).set({status:"failed",completed_at:n,error_code:e}).where(inArray(B.status,po)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){M(e.runId,"runId"),M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.detectorVersion,"detectorVersion");let n=zh(e.candidates),r=or(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let d=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!d||d.thread_id!==e.threadId)&&rt(`Highlight regeneration run ${e.runId} not found`),Js(d.status)||X(`invalid highlight regeneration status: ${d.status}`),d.status==="failed")throw new l("CONFLICT","Highlight regeneration run has already failed");if(d.status==="completed")return {run:d,deletedCount:0,createdCount:0,previousAutoCount:d.previous_auto_count??0,newAutoCount:d.new_auto_count??0};s=!0;let c=this.findThread(i,e.threadId,e.workspaceId);c||rt(`Thread ${e.threadId} not found`),d.detector_version!==e.detectorVersion&&X("detectorVersion does not match the regeneration run");let u=i.select().from(H).where(eq(H.thread_id,c.id)).orderBy(asc(H.created_at),asc(H.id)).all(),p=new Set(n.map(N=>N.contentFingerprint)),f=u.filter(N=>N.source==="auto"&&N.status==="active"&&N.revision===0&&!p.has(N.content_fingerprint??"")),g=u.filter(N=>N.source==="auto"&&N.status==="active").length,h=new Set(u.filter(N=>!f.includes(N)&&N.content_fingerprint).map(N=>N.content_fingerprint)),_=n.filter(N=>!h.has(N.contentFingerprint)),k=new Date().toISOString(),T=sr(i,c.id)+1;ir(i,c.id)||(ar(i,c,r,k,T),T+=1);for(let N of f)i.delete(H).where(eq(H.id,N.id)).run(),Kh(i,N,r,k,T,{runId:e.runId,reason:Dc}),T+=1;let E=0,L=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let N of _){let se=He("thl");i.insert(H).values({id:se,thread_id:c.id,source:"auto",kind:N.kind,status:"active",text:N.text,covers_from_task_id:N.coversFromTaskId,covers_to_task_id:N.coversToTaskId,revision:0,created_at:k,updated_at:k,agent_id:L,source_task_id:N.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:N.contentFingerprint,dismissed_at:null}).run();let xe=i.select().from(H).where(eq(H.id,se)).get();if(!xe)throw new l("DB_ERROR","Regenerated highlight insert did not return a row");fo(i,xe,r,k,"thread.highlight.created",T),T+=1,E+=1;}let R=i.select().from(H).where(eq(H.thread_id,c.id)).all().filter(N=>N.source==="auto"&&N.status==="active").length;Jt(i,{threadId:c.id,seq:T,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:d.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:R,deletedCount:f.length,createdCount:E}}),i.update(B).set({status:"completed",started_at:d.started_at??k,completed_at:k,error_code:null,previous_auto_count:g,new_auto_count:R}).where(and(eq(B.id,d.id),inArray(B.status,po))).run();let O=i.select().from(B).where(eq(B.id,d.id)).get();if(!O)throw new l("DB_ERROR","Highlight regeneration completion did not return a row");return {run:O,deletedCount:f.length,createdCount:E,previousAutoCount:g,newAutoCount:R}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Mc});}catch{}throw i instanceof l?i:new l("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;M(o.threadId,"threadId"),M(o.workspaceId,"workspaceId");let s=qh(o);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let d=i.db.select({maxSeq:sql`COALESCE(MAX(${V.seq}), 0)`}).from(V).where(eq(V.thread_id,o.threadId)).get()?.maxSeq??0,c;o.beforeSeq!==void 0?c=i.db.select().from(V).where(and(eq(V.thread_id,o.threadId),lt$1(V.seq,o.beforeSeq))).orderBy(desc(V.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?c=i.db.select().from(V).where(and(eq(V.thread_id,o.threadId),sql`${V.seq} > ${o.afterSeq}`)).orderBy(asc(V.seq)).limit(s+1).all():c=i.db.select().from(V).where(eq(V.thread_id,o.threadId)).orderBy(desc(V.seq)).limit(s+1).all().reverse();let u=c.length>s,p=o.afterSeq!==void 0?c.slice(0,s):u?c.slice(1):c,f=!1,g=p[0];return g&&(f=!!i.db.select({id:V.id}).from(V).where(and(eq(V.thread_id,o.threadId),lt$1(V.seq,g.seq))).limit(1).get()),{items:p,latestSeq:d,hasMoreOlder:f}}catch(d){throw d instanceof l?d:new l("DB_ERROR","Failed to list thread timeline",d)}finally{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=jh(e),r=or(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);if(d||rt(`Thread ${e.threadId} not found`),n.source==="auto"){let g=i.select().from(H).where(and(eq(H.thread_id,e.threadId),eq(H.source_task_id,n.sourceTaskId),eq(H.detector_version,n.detectorVersion),eq(H.content_fingerprint,n.contentFingerprint))).orderBy(asc(H.created_at),asc(H.id)).limit(1).get();if(g)return g}let c=e.id??He("thl"),u={id:c,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(H).values(u).run();let p=i.select().from(H).where(eq(H.id,c)).get();if(!p)throw new l("DB_ERROR","Highlight insert did not return a row");let f=sr(i,d.id)+1;return ir(i,d.id)||(ar(i,d,r,o,f),f+=1),fo(i,p,r,o,"thread.highlight.created",f),p},{behavior:"immediate"})}catch(i){throw i instanceof l?i:new l("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&X("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&X("highlight update requires at least one field"),e.kind!==void 0&&Qs(e.kind);let n=e.text===void 0?void 0:Xs(e.text),r=or(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);d||rt(`Thread ${e.threadId} not found`);let c=i.select().from(H).where(and(eq(H.id,e.highlightId),eq(H.thread_id,d.id))).limit(1).get();if(c||rt(`Highlight ${e.highlightId} not found`),c.revision!==e.expectedRevision)throw new bn(d.id,c.id,e.expectedRevision,c.revision);if(c.status!=="active")throw new bn(d.id,c.id,e.expectedRevision,c.revision);let u=e.kind??c.kind,p=n??c.text,f=e.coversFromTaskId??c.covers_from_task_id,g=e.coversToTaskId??c.covers_to_task_id;(!p||f.length===0||g.length===0)&&X("highlight projection is incomplete");let h=u!==c.kind||p!==c.text||f!==c.covers_from_task_id||g!==c.covers_to_task_id,_=r.actorType==="user"&&c.source==="auto"&&h?"manual":c.source;if(!(h||_!==c.source))return c;let T=c.revision+1;i.update(H).set({source:_,kind:u,text:p,covers_from_task_id:f,covers_to_task_id:g,revision:T,updated_at:o}).where(and(eq(H.id,c.id),eq(H.revision,c.revision))).run();let E=i.select().from(H).where(eq(H.id,c.id)).get();if(!E)throw new l("DB_ERROR","Highlight update did not return a row");let L=sr(i,d.id)+1;return ir(i,d.id)||(ar(i,d,r,o,L),L+=1),fo(i,E,r,o,"thread.highlight.updated",L,c),E},{behavior:"immediate"})}catch(i){throw i instanceof l?i:new l("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&X("expectedRevision must be a non-negative integer");let n=or(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||rt(`Thread ${e.threadId} not found`);let d=s.select().from(H).where(and(eq(H.id,e.highlightId),eq(H.thread_id,i.id))).limit(1).get();if(d||rt(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new bn(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let c=d.revision+1;s.update(H).set({status:"dismissed",text:null,revision:c,updated_at:r,dismissed_at:r}).where(and(eq(H.id,d.id),eq(H.revision,d.revision))).run();let u=s.select().from(H).where(eq(H.id,d.id)).get();if(!u)throw new l("DB_ERROR","Highlight dismissal did not return a row");let p=sr(s,i.id)+1;return ir(s,i.id)||(ar(s,i,n,r,p),p+=1),fo(s,u,n,r,"thread.highlight.deleted",p,d),u},{behavior:"immediate"})}catch(s){throw s instanceof l?s:new l("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(M(e,"threadId"),M(n,"workspaceId"),r.taskId!==void 0&&M(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&M(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&M(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(H).where(and(eq(H.thread_id,e),eq(H.status,"active"))).orderBy(asc(H.created_at),asc(H.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(sql`
|
|
459
|
+
`),u},{behavior:"immediate"})}}catch(s){throw s instanceof l?s:new l("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(w).set({last_message:n,updated_at:s}).where(eq(w.id,e)).run();}catch(s){throw s instanceof l?s:new l("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(w).set(o).where(eq(w.id,e)).run();}catch(o){throw o instanceof l?o:new l("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 Vt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(c=>c!=="priority"&&c!=="state"))return new Vt("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 Vt("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let c of [i.priority,i.state])if(c!=null&&(typeof c!="string"||c.length===0))return new Vt("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let c=r?and(eq(w.id,e),eq(w.workspace_id,r)):eq(w.id,e);return d.db.transaction(u=>{let p=u.select({metadata:w.metadata}).from(w).where(c).get();if(!p)return null;let f=Zn(p.metadata),g=f.threadTitle,h=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};i.priority===null?delete h.priority:i.priority!==void 0&&(h.priority=i.priority),i.state===null?delete h.state:i.state!==void 0&&(h.state=i.state),Object.keys(h).length>0?f.threadTitle=h:delete f.threadTitle;let _=Object.keys(f).length>0?JSON.stringify(f):null,k=new Date().toISOString();u.update(w).set({metadata:_,updated_at:k}).where(c).run();let T=u.select({metadata:w.metadata}).from(w).where(c).get();if(!T)throw new l("DB_ERROR","Thread-title metadata update could not be read back");let E=Th(T.metadata);return {threadId:e,priority:E.priority,state:E.state}},{behavior:"immediate"})}catch(c){throw c instanceof l?c:new l("DB_ERROR","Failed to patch thread-title metadata",c)}finally{d.close();}}togglePin(e,n){let r=this.openHandle(true);try{let o=n?and(eq(w.id,e),eq(w.workspace_id,n)):eq(w.id,e);return r.db.transaction(s=>{let i=s.select({pinned:w.pinned,metadata:w.metadata}).from(w).where(o).get();if(!i)return null;let d=i.pinned?0:1,c=Zn(i.metadata);if(d){let u=n?and(eq(w.pinned,1),eq(w.workspace_id,n)):eq(w.pinned,1),p=s.select({metadata:w.metadata}).from(w).where(u).all(),f=null;for(let g of p){let h=Zn(g.metadata);typeof h.pinOrder=="number"&&(f===null||h.pinOrder<f)&&(f=h.pinOrder);}c.pinOrder=f===null?0:f-1;}else delete c.pinOrder;return s.update(w).set({pinned:d,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(o).run(),{pinned:!!d}},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("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(w.id,e[s]),eq(w.workspace_id,n)):eq(w.id,e[s]),d=o.select({metadata:w.metadata}).from(w).where(i).get();if(!d)continue;let c=Zn(d.metadata);c.pinOrder=s+1,o.update(w).set({metadata:JSON.stringify(c)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let o=n?and(eq(w.id,e),eq(w.workspace_id,n)):eq(w.id,e),s=r.db.select({starred:w.starred}).from(w).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(w).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,o){let i=this.openHandle(true);try{let d=n?and(eq(w.id,e),eq(w.workspace_id,n)):eq(w.id,e);return i.db.transaction(u=>{let p=u.select({metadata:w.metadata}).from(w).where(d).get();if(!p)return null;let f=p.metadata?JSON.parse(p.metadata):{},g=f.overdrive??{},h=o?.defaultTurns??g.defaultTurns??3,_=o?.updatedBy??"ui",k=new Date().toISOString(),T,E,L,U;switch(r){case "enable-count":{let R=o?.turns??h,O=o?.consumeCurrent?Math.max(R-1,0):R;T=O>0?"count":"off",E=O,L=!0,U="count";break}case "enable-latch":{T="latch",E=0,L=!0,U="latch";break}case "disable":{T="off",E=0,L=!1;break}default:{let R=g.state??"off",O=typeof g.remaining=="number"?g.remaining:0;if(R==="count"&&O>0){let N=O-1;N<=0?(T="off",E=0):(T="count",E=N),L=!0,U="count";}else R==="latch"?(T="latch",E=0,L=!0,U="latch"):(T="off",E=0,L=!1);break}}return f.overdrive={state:T,remaining:E,defaultTurns:h,updatedAt:k,updatedBy:_},u.update(w).set({metadata:JSON.stringify(f),updated_at:k}).where(d).run(),{applied:L,appliedMode:U,state:T,remaining:E}},{behavior:"immediate"})}catch(d){throw d instanceof l?d:new l("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};m();ie();fe();ce();pe();ue();m();var Ic=["urgent","high","medium","low"],vc=["investigating","in-progress","in-review","on-hold","done"],er="custom:";var wh=new Set(Ic),yh=new Set(vc),Rh={urgent:"U \uAE34\uAE09 Urgent",high:"P0 \uAE09\uD568 High",medium:"P1 \uC911\uC694 Medium",low:"P2 \uBCF4\uD1B5 Low"},zs={investigating:"\uC870\uC0AC\uC911 Looking into","in-progress":"\uC9C4\uD589\uC911 In progress","in-review":"\uAC80\uD1A0\uC911 In review","on-hold":"\uBCF4\uB958 On hold",done:"\uC644\uB8CC Done"};function bc(t,e){return !e||e.includes(t)?e??t:`${t} ${e}`}function tr(t){return typeof t=="string"&&wh.has(t)}function nr(t){if(typeof t!="string")return false;if(yh.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(er))return false;let e=t.slice(er.length);return e.length>=1&&e.length<=20}function Ac(t){if(t.startsWith(er))return t.slice(er.length)}function Gs(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 Eh(t){let e=Gs(t);return !!e&&Object.prototype.hasOwnProperty.call(e,"threadTitle")}function lo(t){let e=Gs(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,o={};return tr(r.priority)&&(o.priority=r.priority),nr(r.state)&&(o.state=r.state),o}function Ks(t,e){let n=Gs(t)??{},r={...lo(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)}function Sh(t,e=new Map){let n=[];return t.priority&&n.push(bc(Rh[t.priority],e.get(t.priority))),t.state&&(t.state.startsWith(er)?n.push(Ac(t.state)??""):zs[t.state]?n.push(bc(zs[t.state],e.get(t.state))):e.has(t.state)?n.push(t.state,e.get(t.state)??""):t.state.startsWith("c_")?n.push(t.state):n.push(zs[t.state]??"")),n.filter(Boolean).join(" ")}function Oc(t,e){if(!t||t.trim().length===0)return;let n=new Set,r=false,o=false;for(let s of t.split(",")){let i=s.trim();if(i){if(i==="none"){r=true,o=true;continue}e(i)&&(n.add(i),o=true);}}if(o)return {values:n,includeNone:r}}function bh(t){return Oc(t,tr)}function Ih(t){return Oc(t,nr)}function vh(t,e){return e?t?e.values.has(t):e.includeNone:true}jn();var Dc="regeneration_replaced",Ch="THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS",Lc="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED",Ph="THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED",Mc="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",ho=class extends l{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;}},Sn=class extends ho{},mo=class extends l{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Dh=new Set(Wi),Lh=new Set(ji),Mh=new Set(zi),Hh=new Set(Gi),Uh=50,xc=100,Cc=280,Pc=40,$h=new Set(Ki),po=["queued","running"];function Js(t){return $h.has(t)}function X(t){throw new l("VALIDATION",t)}function rt(t){throw new l("NOT_FOUND",t)}function M(t,e){(typeof t!="string"||t.trim().length===0)&&X(`${e} is required`);}function or(t={}){let e=t.actor??t,n=e.actorType??"system";return Dh.has(n)||X(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&X("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function Fh(t){M(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&M(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&X("title must not be empty"),t.title.length>120&&X("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!tr(t.priority)&&X(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!nr(t.state)&&X(`invalid state: ${String(t.state)}`);}function qh(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&X("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)&&X(`${n} must be a non-negative integer`);let e=t.limit??Uh;return (!Number.isInteger(e)||e<1||e>xc)&&X(`limit must be between 1 and ${xc}`),e}function Xs(t){typeof t!="string"&&X("text is required");let e=t.trim();return e.length===0&&X("text must not be empty"),e.length>Cc&&X(`text must be at most ${Cc} characters`),e}function yt(t,e){return M(t??"",e),t}function Qs(t){Hh.has(t)||X(`invalid highlight kind: ${String(t)}`);}function Bh(t){Mh.has(t)||X(`invalid highlight source: ${String(t)}`);}function jh(t){M(t.threadId,"threadId"),M(t.workspaceId,"workspaceId");let e=t.source??"manual";Bh(e),Qs(t.kind);let n=Xs(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,o=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let p=t.taskId??(r&&o&&r===o?r:void 0),f=yt(p,"taskId");return (r!==f||o!==f)&&X("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:f,coversToTaskId:f,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=yt(r,"coversFromTaskId"),i=yt(o,"coversToTaskId"),d=t.sourceTaskId??s,c=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),u=t.contentFingerprint??t.idempotencyKey??null;return yt(d??void 0,"sourceTaskId"),yt(c??void 0,"detectorVersion"),yt(u??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:s,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:d,detectorVersion:c,contentFingerprint:u}}function Wh(t,e){(!t||typeof t!="object")&&X(`candidates[${e}] is required`),Qs(t.kind);let n=Xs(t.text),r=yt(t.anchorTaskId,`candidates[${e}].anchorTaskId`),o=yt(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=yt(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||sa("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return M(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function zh(t){Array.isArray(t)||X("candidates must be an array"),t.length>Pc&&X(`candidates must contain at most ${Pc} items`);let e=new Map;for(let[n,r]of t.entries()){let o=Wh(r,n);e.set(o.contentFingerprint,o);}return [...e.values()]}function dr(t){let e=lo(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 Gh(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&X("event payload must be a JSON object"),e}catch(e){throw new l("VALIDATION","event payload must be JSON serializable",e)}}function sr(t,e){return t.select({maxSeq:sql`COALESCE(MAX(${V.seq}), 0)`}).from(V).where(eq(V.thread_id,e)).get()?.maxSeq??0}function ir(t,e){return !!t.select({id:V.id}).from(V).where(eq(V.thread_id,e)).limit(1).get()}function Jt(t,e){Lh.has(e.type)||X(`invalid thread event type: ${String(e.type)}`);let n=He("the");t.insert(V).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:Gh(e.payload),created_at:e.createdAt}).run();let r=t.select().from(V).where(eq(V.id,n)).get();if(!r)throw new l("DB_ERROR","Thread event insert did not return a row");return r}function ar(t,e,n,r,o){let s=dr(e);Jt(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 go(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 fo(t,e,n,r,o,s,i){let d=o==="thread.highlight.created"?go(e):{before:i?go({...e,...i,id:e.id}):void 0,after:go(e)};return Jt(t,{threadId:e.thread_id,seq:s,type:o,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:d})}function Kh(t,e,n,r,o,s){return Jt(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:go(e),...s??{}}})}var Ys=class extends j{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 l("NOT_FOUND","Database not found");if(e){let o=dirname(n);existsSync(o)||mkdirSync(o,{recursive:true});}let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}findThread(e,n,r){let o=eq(w.id,n),s=r===void 0?o:r===null?and(o,isNull(w.workspace_id)):and(o,eq(w.workspace_id,r));return e.select().from(w).where(s).limit(1).get()}findRegenerationRun(e,n,r){let o=e.select().from(B).where(eq(B.id,n)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(M(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:w.workspace_id}).from(w).where(eq(w.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if(M(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,n);return o?dr(o):null}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Fh(e);let n=or(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||rt(`Thread ${e.threadId} not found`);let d=dr(i),c=e.title!==void 0,u=c&&e.title!==d.title,p=c&&i.title_locked!==1,f=e.priority!==void 0&&e.priority!==d.priority,g=e.state!==void 0&&e.state!==d.state,h=u||f||g;if(!h&&!p)return d;let _=i.metadata;(f||g)&&(_=Ks(i.metadata,{priority:e.priority,state:e.state}));let k={};if(h&&(k.metadata=_,k.updated_at=r),u&&(k.title=e.title),c&&(k.title_locked=1),s.update(w).set(k).where(e.workspaceId===void 0?eq(w.id,e.threadId):e.workspaceId===null?and(eq(w.id,e.threadId),isNull(w.workspace_id)):and(eq(w.id,e.threadId),eq(w.workspace_id,e.workspaceId))).run(),!h){let L={...i,title_locked:1};return dr(L)}let T=sr(s,i.id)+1;ir(s,i.id)||(ar(s,i,n,r,T),T+=1),u&&(Jt(s,{threadId:i.id,seq:T,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),T+=1),f&&(Jt(s,{threadId:i.id,seq:T,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),T+=1),g&&Jt(s,{threadId:i.id,seq:T,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let E={...i,title:u?e.title:i.title,metadata:_,title_locked:c?1:i.title_locked,updated_at:r};return dr(E)},{behavior:"immediate"})}catch(s){throw s instanceof l?s:new l("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(M(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(${V.seq}), 0)`}).from(V).where(eq(V.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if(M(e,"threadId"),M(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,[...cs,"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 l?o:new l("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.requestId,"requestId"),M(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&M(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||rt(`Thread ${e.threadId} not found`);let i=o.select().from(B).where(and(eq(B.thread_id,s.id),eq(B.request_id,e.requestId))).orderBy(desc(B.requested_at),desc(B.id)).limit(1).get();if(i)return {run:i,created:!1};let d=o.select().from(B).where(and(eq(B.thread_id,s.id),inArray(B.status,po))).orderBy(asc(B.requested_at),asc(B.id)).limit(1).get();if(d)throw new mo(d);let c=e.runId??He("thr");o.insert(B).values({id:c,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 u=o.select().from(B).where(eq(B.id,c)).get();if(!u)throw new l("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:u,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("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(M(e,"runId"),n!==void 0&&M(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 l?o:new l("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if(M(e,"threadId"),M(n,"workspaceId"),M(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,n)?o.db.select().from(B).where(and(eq(B.thread_id,e),eq(B.request_id,r))).orderBy(desc(B.requested_at),desc(B.id)).limit(1).get()??null:null}catch(s){throw s instanceof l?s:new l("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){M(e,"runId"),n!==void 0&&M(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||rt(`Highlight regeneration run ${e} not found`),Js(i.status)||X(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(B).set({status:"running",started_at:r}).where(and(eq(B.id,i.id),eq(B.status,"queued"))).run();let d=s.select().from(B).where(eq(B.id,i.id)).get();if(!d)throw new l("DB_ERROR","Highlight regeneration run start did not return a row");return d},{behavior:"immediate"})}catch(s){throw s instanceof l?s:new l("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){M(e.runId,"runId"),M(e.errorCode,"errorCode"),e.workspaceId!==void 0&&M(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||rt(`Highlight regeneration run ${e.runId} not found`),Js(s.status)||X(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(B).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(and(eq(B.id,s.id),inArray(B.status,po))).run();let i=o.select().from(B).where(eq(B.id,s.id)).get();if(!i)throw new l("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=Lc){M(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(B).set({status:"failed",completed_at:n,error_code:e}).where(inArray(B.status,po)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){M(e.runId,"runId"),M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.detectorVersion,"detectorVersion");let n=zh(e.candidates),r=or(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let d=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!d||d.thread_id!==e.threadId)&&rt(`Highlight regeneration run ${e.runId} not found`),Js(d.status)||X(`invalid highlight regeneration status: ${d.status}`),d.status==="failed")throw new l("CONFLICT","Highlight regeneration run has already failed");if(d.status==="completed")return {run:d,deletedCount:0,createdCount:0,previousAutoCount:d.previous_auto_count??0,newAutoCount:d.new_auto_count??0};s=!0;let c=this.findThread(i,e.threadId,e.workspaceId);c||rt(`Thread ${e.threadId} not found`),d.detector_version!==e.detectorVersion&&X("detectorVersion does not match the regeneration run");let u=i.select().from(H).where(eq(H.thread_id,c.id)).orderBy(asc(H.created_at),asc(H.id)).all(),p=new Set(n.map(N=>N.contentFingerprint)),f=u.filter(N=>N.source==="auto"&&N.status==="active"&&N.revision===0&&!p.has(N.content_fingerprint??"")),g=u.filter(N=>N.source==="auto"&&N.status==="active").length,h=new Set(u.filter(N=>!f.includes(N)&&N.content_fingerprint).map(N=>N.content_fingerprint)),_=n.filter(N=>!h.has(N.contentFingerprint)),k=new Date().toISOString(),T=sr(i,c.id)+1;ir(i,c.id)||(ar(i,c,r,k,T),T+=1);for(let N of f)i.delete(H).where(eq(H.id,N.id)).run(),Kh(i,N,r,k,T,{runId:e.runId,reason:Dc}),T+=1;let E=0,L=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let N of _){let se=He("thl");i.insert(H).values({id:se,thread_id:c.id,source:"auto",kind:N.kind,status:"active",text:N.text,covers_from_task_id:N.coversFromTaskId,covers_to_task_id:N.coversToTaskId,revision:0,created_at:k,updated_at:k,agent_id:L,source_task_id:N.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:N.contentFingerprint,dismissed_at:null}).run();let xe=i.select().from(H).where(eq(H.id,se)).get();if(!xe)throw new l("DB_ERROR","Regenerated highlight insert did not return a row");fo(i,xe,r,k,"thread.highlight.created",T),T+=1,E+=1;}let R=i.select().from(H).where(eq(H.thread_id,c.id)).all().filter(N=>N.source==="auto"&&N.status==="active").length;Jt(i,{threadId:c.id,seq:T,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:d.id,detectorVersion:e.detectorVersion,previousAutoCount:g,newAutoCount:R,deletedCount:f.length,createdCount:E}}),i.update(B).set({status:"completed",started_at:d.started_at??k,completed_at:k,error_code:null,previous_auto_count:g,new_auto_count:R}).where(and(eq(B.id,d.id),inArray(B.status,po))).run();let O=i.select().from(B).where(eq(B.id,d.id)).get();if(!O)throw new l("DB_ERROR","Highlight regeneration completion did not return a row");return {run:O,deletedCount:f.length,createdCount:E,previousAutoCount:g,newAutoCount:R}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Mc});}catch{}throw i instanceof l?i:new l("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;M(o.threadId,"threadId"),M(o.workspaceId,"workspaceId");let s=qh(o);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let d=i.db.select({maxSeq:sql`COALESCE(MAX(${V.seq}), 0)`}).from(V).where(eq(V.thread_id,o.threadId)).get()?.maxSeq??0,c;o.beforeSeq!==void 0?c=i.db.select().from(V).where(and(eq(V.thread_id,o.threadId),lt$1(V.seq,o.beforeSeq))).orderBy(desc(V.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?c=i.db.select().from(V).where(and(eq(V.thread_id,o.threadId),sql`${V.seq} > ${o.afterSeq}`)).orderBy(asc(V.seq)).limit(s+1).all():c=i.db.select().from(V).where(eq(V.thread_id,o.threadId)).orderBy(desc(V.seq)).limit(s+1).all().reverse();let u=c.length>s,p=o.afterSeq!==void 0?c.slice(0,s):u?c.slice(1):c,f=!1,g=p[0];return g&&(f=!!i.db.select({id:V.id}).from(V).where(and(eq(V.thread_id,o.threadId),lt$1(V.seq,g.seq))).limit(1).get()),{items:p,latestSeq:d,hasMoreOlder:f}}catch(d){throw d instanceof l?d:new l("DB_ERROR","Failed to list thread timeline",d)}finally{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=jh(e),r=or(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);if(d||rt(`Thread ${e.threadId} not found`),n.source==="auto"){let g=i.select().from(H).where(and(eq(H.thread_id,e.threadId),eq(H.source_task_id,n.sourceTaskId),eq(H.detector_version,n.detectorVersion),eq(H.content_fingerprint,n.contentFingerprint))).orderBy(asc(H.created_at),asc(H.id)).limit(1).get();if(g)return g}let c=e.id??He("thl"),u={id:c,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(H).values(u).run();let p=i.select().from(H).where(eq(H.id,c)).get();if(!p)throw new l("DB_ERROR","Highlight insert did not return a row");let f=sr(i,d.id)+1;return ir(i,d.id)||(ar(i,d,r,o,f),f+=1),fo(i,p,r,o,"thread.highlight.created",f),p},{behavior:"immediate"})}catch(i){throw i instanceof l?i:new l("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&X("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&X("highlight update requires at least one field"),e.kind!==void 0&&Qs(e.kind);let n=e.text===void 0?void 0:Xs(e.text),r=or(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);d||rt(`Thread ${e.threadId} not found`);let c=i.select().from(H).where(and(eq(H.id,e.highlightId),eq(H.thread_id,d.id))).limit(1).get();if(c||rt(`Highlight ${e.highlightId} not found`),c.revision!==e.expectedRevision)throw new Sn(d.id,c.id,e.expectedRevision,c.revision);if(c.status!=="active")throw new Sn(d.id,c.id,e.expectedRevision,c.revision);let u=e.kind??c.kind,p=n??c.text,f=e.coversFromTaskId??c.covers_from_task_id,g=e.coversToTaskId??c.covers_to_task_id;(!p||f.length===0||g.length===0)&&X("highlight projection is incomplete");let h=u!==c.kind||p!==c.text||f!==c.covers_from_task_id||g!==c.covers_to_task_id,_=r.actorType==="user"&&c.source==="auto"&&h?"manual":c.source;if(!(h||_!==c.source))return c;let T=c.revision+1;i.update(H).set({source:_,kind:u,text:p,covers_from_task_id:f,covers_to_task_id:g,revision:T,updated_at:o}).where(and(eq(H.id,c.id),eq(H.revision,c.revision))).run();let E=i.select().from(H).where(eq(H.id,c.id)).get();if(!E)throw new l("DB_ERROR","Highlight update did not return a row");let L=sr(i,d.id)+1;return ir(i,d.id)||(ar(i,d,r,o,L),L+=1),fo(i,E,r,o,"thread.highlight.updated",L,c),E},{behavior:"immediate"})}catch(i){throw i instanceof l?i:new l("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){M(e.threadId,"threadId"),M(e.workspaceId,"workspaceId"),M(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&X("expectedRevision must be a non-negative integer");let n=or(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||rt(`Thread ${e.threadId} not found`);let d=s.select().from(H).where(and(eq(H.id,e.highlightId),eq(H.thread_id,i.id))).limit(1).get();if(d||rt(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new Sn(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let c=d.revision+1;s.update(H).set({status:"dismissed",text:null,revision:c,updated_at:r,dismissed_at:r}).where(and(eq(H.id,d.id),eq(H.revision,d.revision))).run();let u=s.select().from(H).where(eq(H.id,d.id)).get();if(!u)throw new l("DB_ERROR","Highlight dismissal did not return a row");let p=sr(s,i.id)+1;return ir(s,i.id)||(ar(s,i,n,r,p),p+=1),fo(s,u,n,r,"thread.highlight.deleted",p,d),u},{behavior:"immediate"})}catch(s){throw s instanceof l?s:new l("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,n,r={}){if(M(e,"threadId"),M(n,"workspaceId"),r.taskId!==void 0&&M(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&M(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&M(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(H).where(and(eq(H.thread_id,e),eq(H.status,"active"))).orderBy(asc(H.created_at),asc(H.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(sql`
|
|
460
460
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
461
461
|
ORDER BY started_at ASC, id ASC
|
|
462
|
-
`),c=new Map(d.map((g,h)=>[g.id,h])),u=r.taskId===void 0?void 0:c.get(r.taskId),p=r.coversFromTaskId===void 0?void 0:c.get(r.coversFromTaskId),f=r.coversToTaskId===void 0?void 0:c.get(r.coversToTaskId);return i.filter(g=>{let h=c.get(g.covers_from_task_id),_=c.get(g.covers_to_task_id);if(h===void 0||_===void 0)return !1;let k=Math.min(h,_),T=Math.max(h,_);return !(u!==void 0&&(u<k||u>T)||p!==void 0&&T<p||f!==void 0&&k>f)})}catch(s){throw s instanceof l?s:new l("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)}};m();ie();fe();ce();pe();ue();var Zs=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}insertSpan(e){let n=this.openHandle(true);try{n.db.insert(mt).values(e).run();}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to insert span",r)}finally{n.close();}}findByTaskId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(mt).where(eq(mt.task_id,e)).all()}catch(r){throw new l("DB_ERROR","Failed to find spans by task id",r)}finally{n.close();}}findById(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(mt).where(eq(mt.id,e)).limit(1).get()??void 0}catch(r){throw new l("DB_ERROR","Failed to find span by id",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var ei=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}insertToolCall(e){let n=this.openHandle(true);try{n.db.insert(it).values(e).run();}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to insert tool call",r)}finally{n.close();}}findByTaskId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(it).where(eq(it.task_id,e)).all()}catch(r){throw new l("DB_ERROR","Failed to find tool calls by task id",r)}finally{n.close();}}aggregateByName(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select({toolName:it.tool_name,count:sql`count(*)`}).from(it).where(eq(it.task_id,e)).groupBy(it.tool_name).all().map(r=>({toolName:r.toolName,count:r.count}))}catch(r){throw new l("DB_ERROR","Failed to aggregate tool calls by name",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var ti=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}ensureThreadExists(e,n){if(!e.db.select({id:w.id}).from(w).where(eq(w.id,n)).limit(1).get())throw new l("NOT_FOUND",`Thread not found: ${n}`)}findByThreadId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return this.ensureThreadExists(n,e),n.db.select().from(We).where(eq(We.thread_id,e)).orderBy(asc(We.seq)).all()}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to find boxes by thread id",r)}finally{n.close();}}findById(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(We).where(and(eq(We.id,n),eq(We.thread_id,e))).limit(1).get()??void 0}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to find box by id",o)}finally{r.close();}}insert(e){let n=this.openHandle(true);try{this.ensureThreadExists(n,e.threadId);try{n.db.insert(We).values({id:e.id,thread_id:e.threadId,seq:e.seq,first_task_id:e.first_task_id,mid_task_id:e.mid_task_id,last_task_id:e.last_task_id,task_count:e.task_count,summary:e.summary??null,source_tokens:e.source_tokens,summary_tokens:e.summary_tokens??null,created_at:e.created_at}).run();}catch(o){throw o instanceof Error&&/UNIQUE constraint failed/i.test(o.message)?new l("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let r=n.db.select().from(We).where(eq(We.id,e.id)).limit(1).get();if(!r)throw new l("DB_ERROR","Insert did not return a row");return r}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to insert thread box",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var ni=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}bulkInsert(e){if(e.length===0)return;let n=this.openHandle(true);try{n.db.transaction(r=>{for(let o of e)r.insert(Xt).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:o.timestamp??new Date().toISOString(),metadata:o.metadata??null}).run();});}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to bulk insert request logs",r)}finally{n.close();}}findRecent(e=100){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(Xt).orderBy(desc(Xt.timestamp)).limit(e).all()}catch(r){throw new l("DB_ERROR","Failed to find recent request logs",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();function Wc(t){return new Date(Math.floor(t/3e5)*3e5).toISOString()}var ri=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}upsert(e){let n=this.openHandle(true);try{let r=Wc(e.bucketStartMs),o=e.accountRef??"default";n.db.insert(_e).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:r,captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,source:e.source,metadata:e.metadata??null}).onConflictDoUpdate({target:[_e.provider,_e.account_ref,_e.limit_window,_e.bucket_start],set:{captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,metadata:e.metadata??null}}).run();}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to upsert usage limit snapshot",r)}finally{n.close();}}getTrends(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=n.db.select({provider:_e.provider,bucket_start:_e.bucket_start,used_percent:_e.used_percent,remaining_percent:_e.remaining_percent,resets_at:_e.resets_at}).from(_e).where(and(eq(_e.limit_window,e.window),gte(_e.bucket_start,e.fromIso),lte(_e.bucket_start,e.toIso))).orderBy(asc(_e.bucket_start)).all(),o=new Map;for(let s of r)o.has(s.provider)||o.set(s.provider,[]),o.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(o.entries()).map(([s,i])=>({provider:s,points:i}))}catch(r){throw new l("DB_ERROR","Failed to get usage limit trends",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var oi=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}publish(e){let n=this.openHandle(true);try{n.db.insert(De).values({id:e.id,workspace_id:e.workspaceId,month:e.month,generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}).onConflictDoUpdate({target:[De.workspace_id,De.month],set:{generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}}).run();let r=n.db.select().from(De).where(and(eq(De.workspace_id,e.workspaceId),eq(De.month,e.month))).limit(1).get();if(!r)throw new l("DB_ERROR","Failed to read back published usage report");return r}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to publish usage report",r)}finally{n.close();}}findByMonth(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(De).where(and(eq(De.workspace_id,e),eq(De.month,n))).limit(1).get()??void 0}catch(o){throw new l("DB_ERROR","Failed to find usage report",o)}finally{r.close();}}listByWorkspace(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(De).where(eq(De.workspace_id,e)).orderBy(desc(De.month)).all()}catch(r){throw new l("DB_ERROR","Failed to list usage reports",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var Xc=500,Qc=50,si=class extends j{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??Xc;}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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}create(e){let n=this.openHandle(true);try{let r=He("ntf"),o=new Date().toISOString();return n.db.insert(q).values({id:r,workspace_id:e.workspaceId,agent_id:e.agentId??null,task_id:e.taskId??null,thread_id:e.threadId??null,source:e.source??"agent",level:e.level??"info",title:e.title,body:e.body??null,target_user_id:e.targetUserId??null,created_at:o,metadata:e.metadata??null}).run(),this.enforceCap(n,e.workspaceId),{id:r}}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to create notification",r)}finally{n.close();}}enforceCap(e,n){let s=(e.db.select({count:sql`count(*)`}).from(q).where(eq(q.workspace_id,n)).get()?.count??0)-this.cap;if(s<=0)return;let d=e.db.select({id:q.id}).from(q).innerJoin(ae,eq(ae.notification_id,q.id)).where(eq(q.workspace_id,n)).groupBy(q.id).orderBy(asc(q.created_at)).limit(s).all().map(c=>c.id);d.length!==0&&(e.db.delete(ae).where(inArray(ae.notification_id,d)).run(),e.db.delete(q).where(inArray(q.id,d)).run());}list(e){if(!this.dbExists())return [];let n=e.limit??Qc,r=this.openHandle(false);try{return r.db.select({id:q.id,workspace_id:q.workspace_id,agent_id:q.agent_id,task_id:q.task_id,thread_id:q.thread_id,source:q.source,level:q.level,title:q.title,body:q.body,target_user_id:q.target_user_id,created_at:q.created_at,metadata:q.metadata,read_at:ae.read_at}).from(q).leftJoin(ae,and(eq(ae.notification_id,q.id),eq(ae.user_id,e.userId))).where(eq(q.workspace_id,e.workspaceId)).orderBy(desc(q.created_at)).limit(n).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new l("DB_ERROR","Failed to list notifications",o)}finally{r.close();}}unreadCount(e){if(!this.dbExists())return 0;let n=this.openHandle(false);try{return n.db.select({count:sql`count(*)`}).from(q).leftJoin(ae,and(eq(ae.notification_id,q.id),eq(ae.user_id,e.userId))).where(and(eq(q.workspace_id,e.workspaceId),isNull(ae.notification_id))).get()?.count??0}catch(r){throw new l("DB_ERROR","Failed to count unread notifications",r)}finally{n.close();}}markRead(e){let n=this.openHandle(true);try{if(!n.db.select({id:q.id}).from(q).where(and(eq(q.id,e.notificationId),eq(q.workspace_id,e.workspaceId))).get())throw new l("NOT_FOUND","Notification not found in workspace");return n.db.insert(ae).values({notification_id:e.notificationId,user_id:e.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to mark notification read",r)}finally{n.close();}}markAllRead(e){let n=this.openHandle(true);try{let r=n.db.select({id:q.id}).from(q).leftJoin(ae,and(eq(ae.notification_id,q.id),eq(ae.user_id,e.userId))).where(and(eq(q.workspace_id,e.workspaceId),isNull(ae.notification_id))).all();if(r.length===0)return 0;let o=new Date().toISOString();return n.db.transaction(s=>{for(let i of r)s.insert(ae).values({notification_id:i.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),r.length}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to mark all notifications read",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var tu=50,ai=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}create(e){let n=this.openHandle(true);try{let r=new Date().toISOString(),o=[],s=e.map(i=>{let d=He("sug");return o.push(d),{id:d,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:r,updated_at:r}});return s.length>0&&n.db.insert(W).values(s).run(),{ids:o}}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to create agent suggestions",r)}finally{n.close();}}findLatestSet(e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({task_id:W.task_id}).from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n))).orderBy(desc(W.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(W.task_id):eq(W.task_id,o.task_id);return r.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n),s)).orderBy(asc(W.created_at)).all()}catch(o){throw new l("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{r.close();}}findSetByTaskId(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n),eq(W.task_id,r))).orderBy(asc(W.created_at)).all()}catch(s){throw new l("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,n,r){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n),eq(W.id,r))).get()??null}catch(s){throw new l("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,n,r){let o=this.openHandle(true);try{let s={status:n,updated_at:new Date().toISOString()};return r!==void 0&&(s.applied_commit_sha=r),o.db.update(W).set(s).where(eq(W.id,e)).run().changes>0}catch(s){throw s instanceof l?s:new l("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,n,r=tu){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n))).orderBy(desc(W.created_at)).limit(r).all()}catch(s){throw new l("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,n,r=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n),eq(W.status,"dismissed"))).orderBy(desc(W.updated_at)).limit(r).all()}catch(s){throw new l("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{ai as AgentSuggestionRepository,vc as BUILTIN_THREAD_STATES,j as BaseSqliteRepository,Rr as COMMON_CODE_COLORS,yr as COMMON_CODE_GROUPS,gi as CREWX_JOURNAL_SIZE_LIMIT_BYTES,Ao as CommonCodeRepository,te as CommonCodeRepositoryError,tu as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Xc as DEFAULT_NOTIFICATION_CAP,Qc as DEFAULT_NOTIFICATION_LIST_LIMIT,la as DEFAULT_PROJECT_STAGES,Lo as DEFAULT_PROJECT_STAGE_KEYS,Ps as DEFAULT_TASK_REAPER_TICK_INTERVAL_MS,Kr as INSTRUCTION_STOP_EPOCH_MISMATCH,Hd as INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED,_s as INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED,Ud as INSTRUCTION_STOP_REQUEST_FAILED,ks as INSTRUCTION_STOP_SETTLE_CAS_FAILED,Md as INSTRUCTION_STOP_TARGET_PID_MISSING,Vr as INSTRUCTION_STOP_WORKSPACE_MISMATCH,ds as LEGACY_TASK_TERMINAL_ERROR_PATTERNS,si as NotificationRepository,Do as ProjectRepository,l as RepositoryError,ni as RequestLogRepository,Zs as SpanRepository,fs as TASK_HEARTBEAT_HARD_STALE_MS,ls as TASK_HEARTBEAT_INTERVAL_MS,ps as TASK_HEARTBEAT_STALE_MS,Zd as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,oo as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,Qd as TASK_LOG_MIGRATION_TERMINAL_STATUSES,Jr as TASK_STOP_DEFAULT_GRACE_MS,Ld as TASK_STOP_DEFAULT_POLL_MS,ys as TASK_STOP_OWNED_PROCESS_MARKERS,xf as TASK_STOP_POLL_INTERVAL_MS,cs as TASK_TERMINAL_STATUSES,Dc as THREAD_HIGHLIGHT_DELETION_REASON_REGENERATION_REPLACED,Mc as THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED,Ph as THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED,Lc as THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED,Ch as THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS,Ic as THREAD_PRIORITIES,Mt as TaskLogRepository,to as TaskRepository,ti as ThreadBoxRepository,bn as ThreadHighlightConflictError,mo as ThreadHighlightRegenerationConflictError,ho as ThreadHistoryConflictError,Ys as ThreadHistoryRepository,Ws as ThreadRepository,Vt as ThreadTitleMetadataPatchError,ei as ToolCallRepository,uc as USAGE_BACKFILL_MAX_LATE_USAGE_AGE_MS,ao as USAGE_BACKFILL_TERMINAL_STATUSES,ri as UsageLimitSnapshotRepository,oi as UsageReportRepository,Co as WorkspaceRepository,Wc as calcBucketStart,_c as classifyUsageAccountingReason,Ac as customStateLabel,vo as generateCommonCodeId,kn as hasRecordedUsage,rc as hasSufficientTaskLogMigrationFreeSpace,Eh as hasThreadTitleKey,tr as isThreadPriority,nr as isThreadState,vh as matchesThreadTitleFilter,eo as mergeTerminalReason,Ks as mergeThreadTitleMeta,At as normalizeTaskStatus,C as openDrizzleDb,Sh as parseThreadPriorityFilter,Ih as parseThreadStateFilter,Jl as pushSchema,lo as readThreadTitleMeta,fu as reclaimTemporaryJournal,Wn as resolveTaskHeartbeatHardStaleMs,Gr as resolveTaskHeartbeatIntervalMs,jt as resolveTaskHeartbeatStaleMs,so as resolveTaskLogMigrationDbPath,ws as resolveTaskStopMethod,us as runHeartbeatTick,Yt as runMigrations,J as runMigrationsOnce,Sg as runTaskLogMigration,uh as runUsageBackfill,Pf as startTaskHeartbeat,Rs as stopTask,xd as stopTaskHeartbeat,pn as taskHeartbeatRegistry,Ig as taskLogBackupName,a as tasks,bh as threadTitleSearchHaystack,Xn as tryCheckpointTaskLogWal};
|
|
462
|
+
`),c=new Map(d.map((g,h)=>[g.id,h])),u=r.taskId===void 0?void 0:c.get(r.taskId),p=r.coversFromTaskId===void 0?void 0:c.get(r.coversFromTaskId),f=r.coversToTaskId===void 0?void 0:c.get(r.coversToTaskId);return i.filter(g=>{let h=c.get(g.covers_from_task_id),_=c.get(g.covers_to_task_id);if(h===void 0||_===void 0)return !1;let k=Math.min(h,_),T=Math.max(h,_);return !(u!==void 0&&(u<k||u>T)||p!==void 0&&T<p||f!==void 0&&k>f)})}catch(s){throw s instanceof l?s:new l("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)}};m();ie();fe();ce();pe();ue();var Zs=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}insertSpan(e){let n=this.openHandle(true);try{n.db.insert(mt).values(e).run();}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to insert span",r)}finally{n.close();}}findByTaskId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(mt).where(eq(mt.task_id,e)).all()}catch(r){throw new l("DB_ERROR","Failed to find spans by task id",r)}finally{n.close();}}findById(e){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(mt).where(eq(mt.id,e)).limit(1).get()??void 0}catch(r){throw new l("DB_ERROR","Failed to find span by id",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var ei=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}insertToolCall(e){let n=this.openHandle(true);try{n.db.insert(it).values(e).run();}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to insert tool call",r)}finally{n.close();}}findByTaskId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(it).where(eq(it.task_id,e)).all()}catch(r){throw new l("DB_ERROR","Failed to find tool calls by task id",r)}finally{n.close();}}aggregateByName(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select({toolName:it.tool_name,count:sql`count(*)`}).from(it).where(eq(it.task_id,e)).groupBy(it.tool_name).all().map(r=>({toolName:r.toolName,count:r.count}))}catch(r){throw new l("DB_ERROR","Failed to aggregate tool calls by name",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var ti=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}ensureThreadExists(e,n){if(!e.db.select({id:w.id}).from(w).where(eq(w.id,n)).limit(1).get())throw new l("NOT_FOUND",`Thread not found: ${n}`)}findByThreadId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return this.ensureThreadExists(n,e),n.db.select().from(We).where(eq(We.thread_id,e)).orderBy(asc(We.seq)).all()}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to find boxes by thread id",r)}finally{n.close();}}findById(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(We).where(and(eq(We.id,n),eq(We.thread_id,e))).limit(1).get()??void 0}catch(o){throw o instanceof l?o:new l("DB_ERROR","Failed to find box by id",o)}finally{r.close();}}insert(e){let n=this.openHandle(true);try{this.ensureThreadExists(n,e.threadId);try{n.db.insert(We).values({id:e.id,thread_id:e.threadId,seq:e.seq,first_task_id:e.first_task_id,mid_task_id:e.mid_task_id,last_task_id:e.last_task_id,task_count:e.task_count,summary:e.summary??null,source_tokens:e.source_tokens,summary_tokens:e.summary_tokens??null,created_at:e.created_at}).run();}catch(o){throw o instanceof Error&&/UNIQUE constraint failed/i.test(o.message)?new l("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let r=n.db.select().from(We).where(eq(We.id,e.id)).limit(1).get();if(!r)throw new l("DB_ERROR","Insert did not return a row");return r}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to insert thread box",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var ni=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}bulkInsert(e){if(e.length===0)return;let n=this.openHandle(true);try{n.db.transaction(r=>{for(let o of e)r.insert(Xt).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:o.timestamp??new Date().toISOString(),metadata:o.metadata??null}).run();});}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to bulk insert request logs",r)}finally{n.close();}}findRecent(e=100){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(Xt).orderBy(desc(Xt.timestamp)).limit(e).all()}catch(r){throw new l("DB_ERROR","Failed to find recent request logs",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();function Wc(t){return new Date(Math.floor(t/3e5)*3e5).toISOString()}var ri=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}upsert(e){let n=this.openHandle(true);try{let r=Wc(e.bucketStartMs),o=e.accountRef??"default";n.db.insert(_e).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:r,captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,source:e.source,metadata:e.metadata??null}).onConflictDoUpdate({target:[_e.provider,_e.account_ref,_e.limit_window,_e.bucket_start],set:{captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,metadata:e.metadata??null}}).run();}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to upsert usage limit snapshot",r)}finally{n.close();}}getTrends(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=n.db.select({provider:_e.provider,bucket_start:_e.bucket_start,used_percent:_e.used_percent,remaining_percent:_e.remaining_percent,resets_at:_e.resets_at}).from(_e).where(and(eq(_e.limit_window,e.window),gte(_e.bucket_start,e.fromIso),lte(_e.bucket_start,e.toIso))).orderBy(asc(_e.bucket_start)).all(),o=new Map;for(let s of r)o.has(s.provider)||o.set(s.provider,[]),o.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(o.entries()).map(([s,i])=>({provider:s,points:i}))}catch(r){throw new l("DB_ERROR","Failed to get usage limit trends",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var oi=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}publish(e){let n=this.openHandle(true);try{n.db.insert(De).values({id:e.id,workspace_id:e.workspaceId,month:e.month,generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}).onConflictDoUpdate({target:[De.workspace_id,De.month],set:{generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}}).run();let r=n.db.select().from(De).where(and(eq(De.workspace_id,e.workspaceId),eq(De.month,e.month))).limit(1).get();if(!r)throw new l("DB_ERROR","Failed to read back published usage report");return r}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to publish usage report",r)}finally{n.close();}}findByMonth(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(De).where(and(eq(De.workspace_id,e),eq(De.month,n))).limit(1).get()??void 0}catch(o){throw new l("DB_ERROR","Failed to find usage report",o)}finally{r.close();}}listByWorkspace(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(De).where(eq(De.workspace_id,e)).orderBy(desc(De.month)).all()}catch(r){throw new l("DB_ERROR","Failed to list usage reports",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var Xc=500,Qc=50,si=class extends j{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??Xc;}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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}create(e){let n=this.openHandle(true);try{let r=He("ntf"),o=new Date().toISOString();return n.db.insert(q).values({id:r,workspace_id:e.workspaceId,agent_id:e.agentId??null,task_id:e.taskId??null,thread_id:e.threadId??null,source:e.source??"agent",level:e.level??"info",title:e.title,body:e.body??null,target_user_id:e.targetUserId??null,created_at:o,metadata:e.metadata??null}).run(),this.enforceCap(n,e.workspaceId),{id:r}}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to create notification",r)}finally{n.close();}}enforceCap(e,n){let s=(e.db.select({count:sql`count(*)`}).from(q).where(eq(q.workspace_id,n)).get()?.count??0)-this.cap;if(s<=0)return;let d=e.db.select({id:q.id}).from(q).innerJoin(ae,eq(ae.notification_id,q.id)).where(eq(q.workspace_id,n)).groupBy(q.id).orderBy(asc(q.created_at)).limit(s).all().map(c=>c.id);d.length!==0&&(e.db.delete(ae).where(inArray(ae.notification_id,d)).run(),e.db.delete(q).where(inArray(q.id,d)).run());}list(e){if(!this.dbExists())return [];let n=e.limit??Qc,r=this.openHandle(false);try{return r.db.select({id:q.id,workspace_id:q.workspace_id,agent_id:q.agent_id,task_id:q.task_id,thread_id:q.thread_id,source:q.source,level:q.level,title:q.title,body:q.body,target_user_id:q.target_user_id,created_at:q.created_at,metadata:q.metadata,read_at:ae.read_at}).from(q).leftJoin(ae,and(eq(ae.notification_id,q.id),eq(ae.user_id,e.userId))).where(eq(q.workspace_id,e.workspaceId)).orderBy(desc(q.created_at)).limit(n).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new l("DB_ERROR","Failed to list notifications",o)}finally{r.close();}}unreadCount(e){if(!this.dbExists())return 0;let n=this.openHandle(false);try{return n.db.select({count:sql`count(*)`}).from(q).leftJoin(ae,and(eq(ae.notification_id,q.id),eq(ae.user_id,e.userId))).where(and(eq(q.workspace_id,e.workspaceId),isNull(ae.notification_id))).get()?.count??0}catch(r){throw new l("DB_ERROR","Failed to count unread notifications",r)}finally{n.close();}}markRead(e){let n=this.openHandle(true);try{if(!n.db.select({id:q.id}).from(q).where(and(eq(q.id,e.notificationId),eq(q.workspace_id,e.workspaceId))).get())throw new l("NOT_FOUND","Notification not found in workspace");return n.db.insert(ae).values({notification_id:e.notificationId,user_id:e.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to mark notification read",r)}finally{n.close();}}markAllRead(e){let n=this.openHandle(true);try{let r=n.db.select({id:q.id}).from(q).leftJoin(ae,and(eq(ae.notification_id,q.id),eq(ae.user_id,e.userId))).where(and(eq(q.workspace_id,e.workspaceId),isNull(ae.notification_id))).all();if(r.length===0)return 0;let o=new Date().toISOString();return n.db.transaction(s=>{for(let i of r)s.insert(ae).values({notification_id:i.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),r.length}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to mark all notifications read",r)}finally{n.close();}}};m();ie();fe();ce();pe();ue();var tu=50,ai=class extends j{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 l("NOT_FOUND","Database not found");let r=C(n);if(e)try{J(r.db,n);}catch(o){throw r.close(),o}return r}create(e){let n=this.openHandle(true);try{let r=new Date().toISOString(),o=[],s=e.map(i=>{let d=He("sug");return o.push(d),{id:d,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:r,updated_at:r}});return s.length>0&&n.db.insert(W).values(s).run(),{ids:o}}catch(r){throw r instanceof l?r:new l("DB_ERROR","Failed to create agent suggestions",r)}finally{n.close();}}findLatestSet(e,n){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({task_id:W.task_id}).from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n))).orderBy(desc(W.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(W.task_id):eq(W.task_id,o.task_id);return r.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n),s)).orderBy(asc(W.created_at)).all()}catch(o){throw new l("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{r.close();}}findSetByTaskId(e,n,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n),eq(W.task_id,r))).orderBy(asc(W.created_at)).all()}catch(s){throw new l("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,n,r){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n),eq(W.id,r))).get()??null}catch(s){throw new l("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,n,r){let o=this.openHandle(true);try{let s={status:n,updated_at:new Date().toISOString()};return r!==void 0&&(s.applied_commit_sha=r),o.db.update(W).set(s).where(eq(W.id,e)).run().changes>0}catch(s){throw s instanceof l?s:new l("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,n,r=tu){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n))).orderBy(desc(W.created_at)).limit(r).all()}catch(s){throw new l("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,n,r=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(W).where(and(eq(W.workspace_id,e),eq(W.agent_id,n),eq(W.status,"dismissed"))).orderBy(desc(W.updated_at)).limit(r).all()}catch(s){throw new l("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{ai as AgentSuggestionRepository,vc as BUILTIN_THREAD_STATES,j as BaseSqliteRepository,Rr as COMMON_CODE_COLORS,yr as COMMON_CODE_GROUPS,gi as CREWX_JOURNAL_SIZE_LIMIT_BYTES,Ao as CommonCodeRepository,te as CommonCodeRepositoryError,tu as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Xc as DEFAULT_NOTIFICATION_CAP,Qc as DEFAULT_NOTIFICATION_LIST_LIMIT,la as DEFAULT_PROJECT_STAGES,Lo as DEFAULT_PROJECT_STAGE_KEYS,Ps as DEFAULT_TASK_REAPER_TICK_INTERVAL_MS,Kr as INSTRUCTION_STOP_EPOCH_MISMATCH,Hd as INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED,_s as INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED,Ud as INSTRUCTION_STOP_REQUEST_FAILED,ks as INSTRUCTION_STOP_SETTLE_CAS_FAILED,Md as INSTRUCTION_STOP_TARGET_PID_MISSING,Vr as INSTRUCTION_STOP_WORKSPACE_MISMATCH,ds as LEGACY_TASK_TERMINAL_ERROR_PATTERNS,si as NotificationRepository,Do as ProjectRepository,l as RepositoryError,ni as RequestLogRepository,Zs as SpanRepository,fs as TASK_HEARTBEAT_HARD_STALE_MS,ls as TASK_HEARTBEAT_INTERVAL_MS,ps as TASK_HEARTBEAT_STALE_MS,Zd as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,oo as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,Qd as TASK_LOG_MIGRATION_TERMINAL_STATUSES,Jr as TASK_STOP_DEFAULT_GRACE_MS,Ld as TASK_STOP_DEFAULT_POLL_MS,ys as TASK_STOP_OWNED_PROCESS_MARKERS,xf as TASK_STOP_POLL_INTERVAL_MS,cs as TASK_TERMINAL_STATUSES,Dc as THREAD_HIGHLIGHT_DELETION_REASON_REGENERATION_REPLACED,Mc as THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED,Ph as THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED,Lc as THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED,Ch as THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS,Ic as THREAD_PRIORITIES,Mt as TaskLogRepository,to as TaskRepository,ti as ThreadBoxRepository,Sn as ThreadHighlightConflictError,mo as ThreadHighlightRegenerationConflictError,ho as ThreadHistoryConflictError,Ys as ThreadHistoryRepository,Ws as ThreadRepository,Vt as ThreadTitleMetadataPatchError,ei as ToolCallRepository,uc as USAGE_BACKFILL_MAX_LATE_USAGE_AGE_MS,ao as USAGE_BACKFILL_TERMINAL_STATUSES,ri as UsageLimitSnapshotRepository,oi as UsageReportRepository,Co as WorkspaceRepository,Wc as calcBucketStart,_c as classifyUsageAccountingReason,Ac as customStateLabel,vo as generateCommonCodeId,kn as hasRecordedUsage,rc as hasSufficientTaskLogMigrationFreeSpace,Eh as hasThreadTitleKey,tr as isThreadPriority,nr as isThreadState,vh as matchesThreadTitleFilter,eo as mergeTerminalReason,Ks as mergeThreadTitleMeta,At as normalizeTaskStatus,C as openDrizzleDb,bh as parseThreadPriorityFilter,Ih as parseThreadStateFilter,Jl as pushSchema,lo as readThreadTitleMeta,fu as reclaimTemporaryJournal,Wn as resolveTaskHeartbeatHardStaleMs,Gr as resolveTaskHeartbeatIntervalMs,jt as resolveTaskHeartbeatStaleMs,so as resolveTaskLogMigrationDbPath,ws as resolveTaskStopMethod,us as runHeartbeatTick,Yt as runMigrations,J as runMigrationsOnce,bg as runTaskLogMigration,uh as runUsageBackfill,Pf as startTaskHeartbeat,Rs as stopTask,xd as stopTaskHeartbeat,pn as taskHeartbeatRegistry,Ig as taskLogBackupName,a as tasks,Sh as threadTitleSearchHaystack,Xn as tryCheckpointTaskLogWal};
|