@crewx/sdk 0.9.0-rc.200 → 0.9.0-rc.202

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.
@@ -1,11 +1,11 @@
1
- 'use strict';var fs$1=require('fs'),he=require('path'),ji=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var he__namespace=/*#__PURE__*/_interopNamespace(he);var ji__default=/*#__PURE__*/_interopDefault(ji);var Uc=Object.defineProperty;var nn=(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 b=(t,e)=>()=>(t&&(e=t(t=0)),e);var qc=(t,e)=>{for(var n in e)Uc(t,n,{get:e[n],enumerable:true});};var g=b(()=>{});var _,kt=b(()=>{g();_=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 Wi(t){if(t===":memory:")return t;let e=he.resolve(t),n=e,r=[];for(;!fs$1.existsSync(n);){let o=he.dirname(n);if(o===n)return e;r.unshift(n.slice(o.length+1)),n=o;}let s=fs$1.realpathSync(n);for(let o of r)s=he.join(s,o);return he.resolve(s)}function Yc(t,e){let n=Wi(t),r=Wi(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Ct(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&Qc.some(e=>Yc(t,he.join(ji__default.default.homedir(),".crewx",e))))throw new Error(`${Xc}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var Xc,Qc,Re,Tt=b(()=>{g();Xc="[crewx] Refusing to open the real CrewX database from a test process";Qc=["crewx.db","logs.db"];Re=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||he.join(ji__default.default.homedir(),".crewx","crewx.db");return Ct(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return fs$1.existsSync(e??this.resolveDbPath())}};});function M(t,e={}){let n=Ct(t),r=nn("better-sqlite3"),{drizzle:s}=nn("drizzle-orm/better-sqlite3"),o=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(o.exec("PRAGMA journal_mode = WAL"),o.exec(`PRAGMA journal_size_limit = ${el}`),o.exec("PRAGMA busy_timeout = 5000"),o.exec("PRAGMA foreign_keys = ON"),o.exec("PRAGMA analysis_limit = 400")),{db:s(o),sqlite:o,runRaw:(i,u=[])=>o.prepare(i).run(...u),close:()=>o.close()}}var el,Dt=b(()=>{g();Tt();el=32*1024*1024;});function sn(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function nl(t,e){if(e>0||!sn(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(s=>s.name));for(let[s,o]of Object.entries(tl))r.has(s)||t.run(`ALTER TABLE tasks ADD COLUMN ${s} ${o}`);}function sl(t,e,n){if(!sn(t,"__drizzle_migrations")||!sn(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(i=>i.hash)),o=JSON.parse(fs$1.readFileSync(he__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let u=rl[i.tag];if(!u)continue;let d=he__namespace.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(d))continue;let c=fs$1.readFileSync(d,"utf-8"),l=crypto.createHash("sha256").update(c).digest("hex");if(s.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),f=new Set(p.map(h=>h.name));for(let[h,m]of Object.entries(u))f.has(h)||(t.run(`ALTER TABLE tasks ADD COLUMN ${h} ${m}`),f.add(h));}}function Ji(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 s=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(s)return {kind:"drop-index",name:s[1]}}function Vi(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function ol(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(o=>o.name===n)}function il(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function Rr(t,e){return e.kind==="add-column"?ol(t,e.table,e.column):il(t,e.name)}function Xi(t,e,n){let r=t;for(let s of Vi(e)){let o=Ji(s);o?.kind==="add-column"&&Rr(r,o)||o?.kind==="create-index"&&Rr(r,o)||o?.kind==="drop-index"&&!Rr(r,o)||r.run(n.raw(s));}}function al(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(i=>i.hash)),o=JSON.parse(fs$1.readFileSync(he__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let u=he__namespace.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(u))continue;let d=fs$1.readFileSync(u,"utf-8"),c=crypto.createHash("sha256").update(d).digest("hex");if(s.has(c))continue;let p=Vi(d).map(Ji);if(p.some(h=>!h))continue;let f=p;f.some(h=>h.kind==="add-column")&&f.some(h=>Rr(t,h))&&(t.transaction(h=>{Xi(h,d,n),h.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);},{behavior:"immediate"}),s.add(c),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function dl(t,e){let{sql:n}=nn("drizzle-orm"),r=JSON.parse(fs$1.readFileSync(he__namespace.default.join(e,"meta/_journal.json"),"utf-8")),o=["0025_task_heartbeat","0025_thread_app_instance_ledger","0026_mcp_action_source","0027_ui_instance_active_unique"].map(i=>{let u=r.entries.find(c=>c.tag===i);if(!u)throw new Error(`Missing release/App compatibility migration: ${i}`);let d=fs$1.readFileSync(he__namespace.default.join(e,`${i}.sql`),"utf-8");return {entry:u,content:d,hash:crypto.createHash("sha256").update(d).digest("hex")}});t.transaction(i=>{let u=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(d=>d.hash));if(u.has(o[0].hash))for(let d of o.slice(1))u.has(d.hash)||(Xi(i,d.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${d.hash}, ${d.entry.when})`),u.add(d.hash),console.error(`[crewx] Replayed release/App migration ${d.entry.tag} safely.`));},{behavior:"immediate"});}function pl(t,e,n,r){let o=JSON.parse(fs$1.readFileSync(he__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===ul);if(!o)return;let i=he__namespace.default.join(e,`${o.tag}.sql`);if(!fs$1.existsSync(i))return;let u=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===u))return;if(!sn(t,"tasks"))return {hash:u,affectedRows:0};let d=t.all("PRAGMA table_info(tasks)"),c=new Set(d.map(p=>p.name));if(!c.has("stop_requested_at")||!c.has("stop_requested_epoch"))return {hash:u,affectedRows:0};let l=t.get(n`
1
+ 'use strict';var Ru=require('fs'),me=require('path'),ea=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ru__namespace=/*#__PURE__*/_interopNamespace(Ru);var me__namespace=/*#__PURE__*/_interopNamespace(me);var ea__namespace=/*#__PURE__*/_interopNamespace(ea);var ol=Object.defineProperty;var rn=(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 N=(t,e)=>()=>(t&&(e=t(t=0)),e);var il=(t,e)=>{for(var n in e)ol(t,n,{get:e[n],enumerable:true});};var g=N(()=>{});var _,wt=N(()=>{g();_=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 Qi(t){if(t===":memory:")return t;let e=me.resolve(t),n=e,r=[];for(;!Ru.existsSync(n);){let o=me.dirname(n);if(o===n)return e;r.unshift(n.slice(o.length+1)),n=o;}let s=Ru.realpathSync(n);for(let o of r)s=me.join(s,o);return me.resolve(s)}function ml(t,e){let n=Qi(t),r=Qi(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Mt(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&kl.some(e=>ml(t,me.join(ea__namespace.default.homedir(),".crewx",e))))throw new Error(`${hl}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var hl,kl,Se,Et=N(()=>{g();hl="[crewx] Refusing to open the real CrewX database from a test process";kl=["crewx.db","logs.db"];Se=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||me.join(ea__namespace.default.homedir(),".crewx","crewx.db");return Mt(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return Ru.existsSync(e??this.resolveDbPath())}};});function M(t,e={}){let n=Mt(t),r=rn("better-sqlite3"),{drizzle:s}=rn("drizzle-orm/better-sqlite3"),o=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(o.exec("PRAGMA journal_mode = WAL"),o.exec(`PRAGMA journal_size_limit = ${yl}`),o.exec("PRAGMA busy_timeout = 5000"),o.exec("PRAGMA foreign_keys = ON"),o.exec("PRAGMA analysis_limit = 400")),{db:s(o),sqlite:o,runRaw:(i,u=[])=>o.prepare(i).run(...u),close:()=>o.close()}}var yl,$t=N(()=>{g();Et();yl=32*1024*1024;});function on(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function El(t,e){if(e>0||!on(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(s=>s.name));for(let[s,o]of Object.entries(wl))r.has(s)||t.run(`ALTER TABLE tasks ADD COLUMN ${s} ${o}`);}function Sl(t,e,n){if(!on(t,"__drizzle_migrations")||!on(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(i=>i.hash)),o=JSON.parse(Ru.readFileSync(me__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let u=Rl[i.tag];if(!u)continue;let d=me__namespace.default.join(e,`${i.tag}.sql`);if(!Ru.existsSync(d))continue;let c=Ru.readFileSync(d,"utf-8"),l=crypto.createHash("sha256").update(c).digest("hex");if(s.has(l))continue;let p=t.all("PRAGMA table_info(tasks)"),f=new Set(p.map(h=>h.name));for(let[h,m]of Object.entries(u))f.has(h)||(t.run(`ALTER TABLE tasks ADD COLUMN ${h} ${m}`),f.add(h));}}function ra(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 s=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(s)return {kind:"drop-index",name:s[1]}}function sa(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function Il(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(o=>o.name===n)}function Al(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function Ar(t,e){return e.kind==="add-column"?Il(t,e.table,e.column):Al(t,e.name)}function oa(t,e,n){let r=t;for(let s of sa(e)){let o=ra(s);o?.kind==="add-column"&&Ar(r,o)||o?.kind==="create-index"&&Ar(r,o)||o?.kind==="drop-index"&&!Ar(r,o)||r.run(n.raw(s));}}function Ol(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),s=new Set(r.map(i=>i.hash)),o=JSON.parse(Ru.readFileSync(me__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of o.entries){let u=me__namespace.default.join(e,`${i.tag}.sql`);if(!Ru.existsSync(u))continue;let d=Ru.readFileSync(u,"utf-8"),c=crypto.createHash("sha256").update(d).digest("hex");if(s.has(c))continue;let p=sa(d).map(ra);if(p.some(h=>!h))continue;let f=p;f.some(h=>h.kind==="add-column")&&f.some(h=>Ar(t,h))&&(t.transaction(h=>{oa(h,d,n),h.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c}, ${i.when})`);},{behavior:"immediate"}),s.add(c),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function Nl(t,e){let{sql:n}=rn("drizzle-orm"),r=JSON.parse(Ru.readFileSync(me__namespace.default.join(e,"meta/_journal.json"),"utf-8")),o=["0025_task_heartbeat","0025_thread_app_instance_ledger","0026_mcp_action_source","0027_ui_instance_active_unique"].map(i=>{let u=r.entries.find(c=>c.tag===i);if(!u)throw new Error(`Missing release/App compatibility migration: ${i}`);let d=Ru.readFileSync(me__namespace.default.join(e,`${i}.sql`),"utf-8");return {entry:u,content:d,hash:crypto.createHash("sha256").update(d).digest("hex")}});t.transaction(i=>{let u=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(d=>d.hash));if(u.has(o[0].hash))for(let d of o.slice(1))u.has(d.hash)||(oa(i,d.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${d.hash}, ${d.entry.when})`),u.add(d.hash),console.error(`[crewx] Replayed release/App migration ${d.entry.tag} safely.`));},{behavior:"immediate"});}function Cl(t,e,n,r){let o=JSON.parse(Ru.readFileSync(me__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===bl);if(!o)return;let i=me__namespace.default.join(e,`${o.tag}.sql`);if(!Ru.existsSync(i))return;let u=crypto.createHash("sha256").update(Ru.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===u))return;if(!on(t,"tasks"))return {hash:u,affectedRows:0};let d=t.all("PRAGMA table_info(tasks)"),c=new Set(d.map(p=>p.name));if(!c.has("stop_requested_at")||!c.has("stop_requested_epoch"))return {hash:u,affectedRows:0};let l=t.get(n`
2
2
  SELECT count(*) AS count
3
3
  FROM tasks
4
4
  WHERE status IN ('success', 'failed')
5
5
  AND (stop_requested_at IS NOT NULL OR stop_requested_epoch IS NOT NULL)
6
- `);return {hash:u,affectedRows:l?.count??0}}function fl(t,e,n,r){let o=JSON.parse(fs$1.readFileSync(he__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===cl);if(!o)return;let i=he__namespace.default.join(e,`${o.tag}.sql`);if(!fs$1.existsSync(i))return;let u=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===u))return;if(!sn(t,"threads"))return {hash:u,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(p=>p.name==="created_by_task_id"))return {hash:u,markedPointers:0};let c=sn(t,zi)?`AND NOT EXISTS (
6
+ `);return {hash:u,affectedRows:l?.count??0}}function Dl(t,e,n,r){let o=JSON.parse(Ru.readFileSync(me__namespace.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:p})=>p===vl);if(!o)return;let i=me__namespace.default.join(e,`${o.tag}.sql`);if(!Ru.existsSync(i))return;let u=crypto.createHash("sha256").update(Ru.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===u))return;if(!on(t,"threads"))return {hash:u,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(p=>p.name==="created_by_task_id"))return {hash:u,markedPointers:0};let c=on(t,na)?`AND NOT EXISTS (
7
7
  SELECT 1
8
- FROM ${zi} AS marked
8
+ FROM ${na} AS marked
9
9
  WHERE marked.thread_id = current.id
10
10
  AND marked.created_by_task_id = current.created_by_task_id
11
11
  )`:"",l=t.get(`SELECT count(*) AS count
@@ -15,50 +15,69 @@
15
15
  SELECT 1
16
16
  FROM sqlite_master
17
17
  WHERE type = 'trigger'
18
- AND name = '${ll}'
18
+ AND name = '${xl}'
19
19
  )
20
- ${c}`);return {hash:u,markedPointers:l?.count??0}}function _l(t){let{migrate:e}=nn("drizzle-orm/better-sqlite3/migrator"),{sql:n}=nn("drizzle-orm"),r=[he__namespace.default.join(__dirname,"../migrations"),he__namespace.default.join(__dirname,"migrations"),he__namespace.default.join(__dirname,"../../../../drizzle/migrations"),he__namespace.default.join(process.cwd(),"drizzle/migrations")],s=r.find(p=>fs$1.existsSync(he__namespace.default.join(p,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
20
+ ${c}`);return {hash:u,markedPointers:l?.count??0}}function Pl(t){let{migrate:e}=rn("drizzle-orm/better-sqlite3/migrator"),{sql:n}=rn("drizzle-orm"),r=[me__namespace.default.join(__dirname,"../migrations"),me__namespace.default.join(__dirname,"migrations"),me__namespace.default.join(__dirname,"../../../../drizzle/migrations"),me__namespace.default.join(process.cwd(),"drizzle/migrations")],s=r.find(p=>Ru.existsSync(me__namespace.default.join(p,"meta/_journal.json")));if(!s)throw new Error(`migrations folder not found. Searched:
21
21
  ${r.join(`
22
- `)}`);let o=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),nl(t,i),o?.cnt&&(dl(t,s),al(t,s,n),sl(t,s,n));let u=pl(t,s,n,!!o?.cnt),d=fl(t,s,n,!!o?.cnt);e(t,{migrationsFolder:s});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let p=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${p} (${l} migration${l>1?"s":""} applied).`);}u&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===u.hash)&&console.error(`[crewx] Task stop-marker cleanup (${u.affectedRows} success/failed row(s) affected).`),d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===d.hash)&&console.error(`[crewx] Thread creator pointer migration (${d.markedPointers} pointer(s) marked unverified).`);}function Pe(t,e){Ki.has(e)||(_l(t),Ki.add(e));}var Ki,tl,rl,ul,cl,ll,zi,Pt=b(()=>{g();Ki=new Set,tl={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",metadata:"TEXT"};rl={"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"},"0044_clammy_bruce_banner":{metadata:"TEXT"}};ul="0027_task_stop_scope_cleanup",cl="0033_thread_creator_boundary_guard",ll="trg_threads_creator_late_fill_guard",zi="thread_creator_unverified";});var ne,Sr=b(()=>{g();ne=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var a,Am,Tl,re,on=b(()=>{g();a=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),actor_kind:sqliteCore.text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:sqliteCore.text("actor_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),pid_started_at:sqliteCore.text("pid_started_at"),heartbeat_at:sqliteCore.text("heartbeat_at"),stop_requested_at:sqliteCore.text("stop_requested_at"),stop_requested_epoch:sqliteCore.integer("stop_requested_epoch"),rendered_prompt:sqliteCore.text("rendered_prompt"),security_key:sqliteCore.text("security_key"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),cwd:sqliteCore.text("cwd"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0),rating:sqliteCore.text("rating",{enum:["up","down"]}),rated_at:sqliteCore.text("rated_at"),workflow_run_id:sqliteCore.text("workflow_run_id"),schedule_id:sqliteCore.text("schedule_id")},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),rating_check:sqliteCore.check("tasks_rating_ck",drizzleOrm.sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:sqliteCore.index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:sqliteCore.index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:sqliteCore.index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(drizzleOrm.sql`${t.rating} IS NOT NULL`)})),{security_key:Am,...Tl}=drizzleOrm.getTableColumns(a),re=Tl;});var lt,ea=b(()=>{g();on();lt=sqliteCore.sqliteTable("task_provider_inputs",{task_id:sqliteCore.text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),run_epoch:sqliteCore.integer("run_epoch").notNull(),input:sqliteCore.text("input").notNull(),key_wrap_skipped:sqliteCore.integer("key_wrap_skipped").notNull().default(0),recorded_at:sqliteCore.text("recorded_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.task_id,t.run_epoch]})}));});var rt,na=b(()=>{g();on();rt=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:sqliteCore.index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var Al,Ol,T,Mn=b(()=>{g();Sr();Al="json_extract(metadata, '$.threadTitle.state')",Ol="json_extract(metadata, '$.threadTitle.priority')",T=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>ne.id,{onDelete:"set null"}),created_by_kind:sqliteCore.text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:sqliteCore.text("created_by_id"),created_by_task_id:sqliteCore.text("created_by_task_id"),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:sqliteCore.index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(Al)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(Ol))}));});var oa=b(()=>{g();sqliteCore.sqliteTable("thread_creator_unverified",{thread_id:sqliteCore.text("thread_id").notNull(),created_by_task_id:sqliteCore.text("created_by_task_id").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var Cl,aa=b(()=>{g();on();Cl=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Cl.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var da=b(()=>{g();on();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));});var ca=b(()=>{g();Mn();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));});var pa=b(()=>{g();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));});var fa=b(()=>{g();sqliteCore.sqliteTable("request_log_daily",{day:sqliteCore.text("day").notNull(),scope:sqliteCore.text("scope").notNull(),ok:sqliteCore.integer("ok").notNull(),client:sqliteCore.integer("client").notNull(),server:sqliteCore.integer("server").notNull(),p50_ms:sqliteCore.integer("p50_ms"),p95_ms:sqliteCore.integer("p95_ms"),computed_at:sqliteCore.text("computed_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.day,t.scope]})}));});var ha=b(()=>{g();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var ma=b(()=>{g();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var Ta=b(()=>{g();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var wa=b(()=>{g();sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var Ea=b(()=>{g();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),app_id:sqliteCore.text("app_id"),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),opened_by_json:sqliteCore.text("opened_by_json"),agent_open_request_json:sqliteCore.text("agent_open_request_json"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("ui_instances_app_id_ck",drizzleOrm.sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:sqliteCore.check("ui_instances_opened_by_json_ck",drizzleOrm.sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:sqliteCore.uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(drizzleOrm.sql`${t.status} = 'active'`)}));});var Sa=b(()=>{g();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),definition_id:sqliteCore.text("definition_id"),definition_version:sqliteCore.integer("definition_version"),definition_hash:sqliteCore.text("definition_hash"),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
22
+ `)}`);let o=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;o?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),El(t,i),o?.cnt&&(Nl(t,s),Ol(t,s,n),Sl(t,s,n));let u=Cl(t,s,n,!!o?.cnt),d=Dl(t,s,n,!!o?.cnt);e(t,{migrationsFolder:s});let l=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let p=o?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${p} (${l} migration${l>1?"s":""} applied).`);}u&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===u.hash)&&console.error(`[crewx] Task stop-marker cleanup (${u.affectedRows} success/failed row(s) affected).`),d&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(f=>f.hash===d.hash)&&console.error(`[crewx] Thread creator pointer migration (${d.markedPointers} pointer(s) marked unverified).`);}function Me(t,e){ta.has(e)||(Pl(t),ta.add(e));}var ta,wl,Rl,bl,vl,xl,na,Ht=N(()=>{g();ta=new Set,wl={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",metadata:"TEXT"};Rl={"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"},"0044_clammy_bruce_banner":{metadata:"TEXT"}};bl="0027_task_stop_scope_cleanup",vl="0033_thread_creator_boundary_guard",xl="trg_threads_creator_late_fill_guard",na="thread_creator_unverified";});var ne,Or=N(()=>{g();ne=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var a,gk,Ul,re,an=N(()=>{g();a=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),actor_kind:sqliteCore.text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:sqliteCore.text("actor_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),pid_started_at:sqliteCore.text("pid_started_at"),heartbeat_at:sqliteCore.text("heartbeat_at"),stop_requested_at:sqliteCore.text("stop_requested_at"),stop_requested_epoch:sqliteCore.integer("stop_requested_epoch"),rendered_prompt:sqliteCore.text("rendered_prompt"),security_key:sqliteCore.text("security_key"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),cwd:sqliteCore.text("cwd"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0),rating:sqliteCore.text("rating",{enum:["up","down"]}),rated_at:sqliteCore.text("rated_at"),workflow_run_id:sqliteCore.text("workflow_run_id"),schedule_id:sqliteCore.text("schedule_id")},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),rating_check:sqliteCore.check("tasks_rating_ck",drizzleOrm.sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:sqliteCore.index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:sqliteCore.index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:sqliteCore.index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(drizzleOrm.sql`${t.rating} IS NOT NULL`)})),{security_key:gk,...Ul}=drizzleOrm.getTableColumns(a),re=Ul;});var _t,ua=N(()=>{g();an();_t=sqliteCore.sqliteTable("task_provider_inputs",{task_id:sqliteCore.text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),run_epoch:sqliteCore.integer("run_epoch").notNull(),input:sqliteCore.text("input").notNull(),key_wrap_skipped:sqliteCore.integer("key_wrap_skipped").notNull().default(0),recorded_at:sqliteCore.text("recorded_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.task_id,t.run_epoch]})}));});var it,la=N(()=>{g();an();it=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:sqliteCore.index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var Kl,zl,T,$n=N(()=>{g();Or();Kl="json_extract(metadata, '$.threadTitle.state')",zl="json_extract(metadata, '$.threadTitle.priority')",T=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>ne.id,{onDelete:"set null"}),created_by_kind:sqliteCore.text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:sqliteCore.text("created_by_id"),created_by_task_id:sqliteCore.text("created_by_task_id"),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:sqliteCore.index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(Kl)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(zl))}));});var _a=N(()=>{g();sqliteCore.sqliteTable("thread_creator_unverified",{thread_id:sqliteCore.text("thread_id").notNull(),created_by_task_id:sqliteCore.text("created_by_task_id").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var Ql,ha=N(()=>{g();an();Ql=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Ql.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var ma=N(()=>{g();an();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>a.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));});var Ta=N(()=>{g();$n();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));});var wa=N(()=>{g();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));});var Ea=N(()=>{g();sqliteCore.sqliteTable("request_log_daily",{day:sqliteCore.text("day").notNull(),scope:sqliteCore.text("scope").notNull(),ok:sqliteCore.integer("ok").notNull(),client:sqliteCore.integer("client").notNull(),server:sqliteCore.integer("server").notNull(),p50_ms:sqliteCore.integer("p50_ms"),p95_ms:sqliteCore.integer("p95_ms"),computed_at:sqliteCore.text("computed_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.day,t.scope]})}));});var Ia=N(()=>{g();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var Aa=N(()=>{g();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var Na=N(()=>{g();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var va=N(()=>{g();sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var xa=N(()=>{g();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),app_id:sqliteCore.text("app_id"),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),opened_by_json:sqliteCore.text("opened_by_json"),agent_open_request_json:sqliteCore.text("agent_open_request_json"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("ui_instances_app_id_ck",drizzleOrm.sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:sqliteCore.check("ui_instances_opened_by_json_ck",drizzleOrm.sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:sqliteCore.uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(drizzleOrm.sql`${t.status} = 'active'`)}));});var Da=N(()=>{g();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),definition_id:sqliteCore.text("definition_id"),definition_version:sqliteCore.integer("definition_version"),definition_hash:sqliteCore.text("definition_hash"),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
23
23
  (${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
24
24
  OR
25
25
  (${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
26
- )`),instanceRequestUnique:sqliteCore.uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:sqliteCore.index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:sqliteCore.index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var Ia=b(()=>{g();sqliteCore.sqliteTable("ui_instance_repins",{instance_id:sqliteCore.text("instance_id").notNull(),from_version:sqliteCore.integer("from_version").notNull(),from_hash:sqliteCore.text("from_hash").notNull(),to_version:sqliteCore.integer("to_version").notNull(),to_hash:sqliteCore.text("to_hash").notNull(),from_revision:sqliteCore.integer("from_revision").notNull(),to_revision:sqliteCore.integer("to_revision"),status:sqliteCore.text("status").notNull(),code:sqliteCore.text("code"),attempts:sqliteCore.integer("attempts").notNull().default(1),first_at:sqliteCore.integer("first_at").notNull(),last_at:sqliteCore.integer("last_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.instance_id,t.to_hash],name:"ui_instance_repins_pk"}),instanceIdCheck:sqliteCore.check("ui_instance_repins_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 5 AND 128 AND ${t.instance_id} GLOB 'uic_*'`),fromVersionCheck:sqliteCore.check("ui_instance_repins_from_version_ck",drizzleOrm.sql`${t.from_version} >= 1`),toVersionCheck:sqliteCore.check("ui_instance_repins_to_version_ck",drizzleOrm.sql`${t.to_version} >= 1`),fromHashCheck:sqliteCore.check("ui_instance_repins_from_hash_ck",drizzleOrm.sql`length(${t.from_hash}) = 64 AND ${t.from_hash} NOT GLOB '*[^0-9a-f]*'`),toHashCheck:sqliteCore.check("ui_instance_repins_to_hash_ck",drizzleOrm.sql`length(${t.to_hash}) = 64 AND ${t.to_hash} NOT GLOB '*[^0-9a-f]*'`),fromRevisionCheck:sqliteCore.check("ui_instance_repins_from_revision_ck",drizzleOrm.sql`${t.from_revision} >= 0`),toRevisionCheck:sqliteCore.check("ui_instance_repins_to_revision_ck",drizzleOrm.sql`${t.to_revision} IS NULL OR ${t.to_revision} >= 0`),statusCheck:sqliteCore.check("ui_instance_repins_status_ck",drizzleOrm.sql`${t.status} IN ('applied', 'deferred', 'failed')`),attemptsCheck:sqliteCore.check("ui_instance_repins_attempts_ck",drizzleOrm.sql`${t.attempts} >= 1`),datesCheck:sqliteCore.check("ui_instance_repins_dates_ck",drizzleOrm.sql`${t.first_at} >= 0 AND ${t.last_at} >= ${t.first_at}`),resultCheck:sqliteCore.check("ui_instance_repins_result_ck",drizzleOrm.sql`(
26
+ )`),instanceRequestUnique:sqliteCore.uniqueIndex("ui_action_receipts_instance_request_uq").on(t.instance_id,t.request_id),instanceIdIdx:sqliteCore.index("ui_action_receipts_instance_id_idx").on(t.instance_id),requestedAtIdx:sqliteCore.index("ui_action_receipts_requested_at_idx").on(t.requested_at)}));});var Pa=N(()=>{g();sqliteCore.sqliteTable("ui_instance_repins",{instance_id:sqliteCore.text("instance_id").notNull(),from_version:sqliteCore.integer("from_version").notNull(),from_hash:sqliteCore.text("from_hash").notNull(),to_version:sqliteCore.integer("to_version").notNull(),to_hash:sqliteCore.text("to_hash").notNull(),from_revision:sqliteCore.integer("from_revision").notNull(),to_revision:sqliteCore.integer("to_revision"),status:sqliteCore.text("status").notNull(),code:sqliteCore.text("code"),attempts:sqliteCore.integer("attempts").notNull().default(1),first_at:sqliteCore.integer("first_at").notNull(),last_at:sqliteCore.integer("last_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.instance_id,t.to_hash],name:"ui_instance_repins_pk"}),instanceIdCheck:sqliteCore.check("ui_instance_repins_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 5 AND 128 AND ${t.instance_id} GLOB 'uic_*'`),fromVersionCheck:sqliteCore.check("ui_instance_repins_from_version_ck",drizzleOrm.sql`${t.from_version} >= 1`),toVersionCheck:sqliteCore.check("ui_instance_repins_to_version_ck",drizzleOrm.sql`${t.to_version} >= 1`),fromHashCheck:sqliteCore.check("ui_instance_repins_from_hash_ck",drizzleOrm.sql`length(${t.from_hash}) = 64 AND ${t.from_hash} NOT GLOB '*[^0-9a-f]*'`),toHashCheck:sqliteCore.check("ui_instance_repins_to_hash_ck",drizzleOrm.sql`length(${t.to_hash}) = 64 AND ${t.to_hash} NOT GLOB '*[^0-9a-f]*'`),fromRevisionCheck:sqliteCore.check("ui_instance_repins_from_revision_ck",drizzleOrm.sql`${t.from_revision} >= 0`),toRevisionCheck:sqliteCore.check("ui_instance_repins_to_revision_ck",drizzleOrm.sql`${t.to_revision} IS NULL OR ${t.to_revision} >= 0`),statusCheck:sqliteCore.check("ui_instance_repins_status_ck",drizzleOrm.sql`${t.status} IN ('applied', 'deferred', 'failed')`),attemptsCheck:sqliteCore.check("ui_instance_repins_attempts_ck",drizzleOrm.sql`${t.attempts} >= 1`),datesCheck:sqliteCore.check("ui_instance_repins_dates_ck",drizzleOrm.sql`${t.first_at} >= 0 AND ${t.last_at} >= ${t.first_at}`),resultCheck:sqliteCore.check("ui_instance_repins_result_ck",drizzleOrm.sql`(
27
27
  (${t.status} = 'applied' AND ${t.code} IS NULL
28
28
  AND ${t.to_revision} = ${t.from_revision} + 1)
29
29
  OR
30
30
  (${t.status} IN ('deferred', 'failed') AND ${t.code} IS NOT NULL
31
31
  AND ${t.to_revision} IS NULL)
32
- )`)}));});var Oa=b(()=>{g();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`)}));});var ba,va=b(()=>{g();ba=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},t=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${t.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${t.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>ba.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>ba.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},t=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var Gs,js,C,Ks=b(()=>{g();Gs=["THREAD_STATE","THREAD_PRIORITY"],js=["gray","blue","violet","green","amber","orange","red","pink"],C=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.code_group,t.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${t.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var xa,Ca,Da,Pa,La,W,q,H,Ma=b(()=>{g();Mn();xa=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Ca=["user","agent","system"],Da=["auto","manual"],Pa=["decision","judgment","issue","result","pivot"],La=["queued","running","completed","failed"],W=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},t=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.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:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),q=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},t=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.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:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(drizzleOrm.sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),H=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},t=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${t.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.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:sqliteCore.index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(drizzleOrm.sql`${t.source} = 'auto'`)}));});var Ha=b(()=>{g();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var ve,Ua=b(()=>{g();ve=sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var Ba,Wa=b(()=>{g();Mn();Sr();sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>ne.id,{onDelete:"cascade"}),revision:sqliteCore.integer("revision").notNull().default(0),rail_collapsed:sqliteCore.integer("rail_collapsed").notNull().default(0),seeded_at:sqliteCore.text("seeded_at").notNull()},t=>({railCollapsedCheck:sqliteCore.check("sidebar_states_rail_collapsed_ck",drizzleOrm.sql`${t.rail_collapsed} IN (0, 1)`)})),Ba=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),name:sqliteCore.text("name").notNull(),color:sqliteCore.text("color").notNull(),collapsed:sqliteCore.integer("collapsed").notNull().default(0),position:sqliteCore.integer("position").notNull()},t=>({colorCheck:sqliteCore.check("sidebar_groups_color_ck",drizzleOrm.sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue')`),collapsedCheck:sqliteCore.check("sidebar_groups_collapsed_ck",drizzleOrm.sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:sqliteCore.index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteCore.sqliteTable("sidebar_tabs",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ba.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteCore.sqliteTable("sidebar_closed_tabs",{id:sqliteCore.integer("id").primaryKey({autoIncrement:true}),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ba.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull(),closed_at:sqliteCore.text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:sqliteCore.index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteCore.sqliteTable("thread_reads",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var Ga=b(()=>{g();sqliteCore.sqliteTable("schedule_runs",{id:sqliteCore.text("id").primaryKey(),schedule_id:sqliteCore.text("schedule_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),mode:sqliteCore.text("mode").notNull(),trigger:sqliteCore.text("trigger").notNull(),occurrence_key:sqliteCore.text("occurrence_key"),task_id:sqliteCore.text("task_id"),app_id:sqliteCore.text("app_id"),schedule_name:sqliteCore.text("schedule_name"),builtin_id:sqliteCore.text("builtin_id"),command:sqliteCore.text("command"),high_frequency:sqliteCore.integer("high_frequency").notNull().default(0),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),exit_code:sqliteCore.integer("exit_code"),signal:sqliteCore.text("signal"),started_at:sqliteCore.text("started_at").notNull(),finished_at:sqliteCore.text("finished_at"),duration_ms:sqliteCore.integer("duration_ms"),pid:sqliteCore.integer("pid"),host_pid:sqliteCore.integer("host_pid"),output_tail:sqliteCore.text("output_tail"),output_bytes:sqliteCore.integer("output_bytes"),output_truncated:sqliteCore.integer("output_truncated").notNull().default(0)},t=>({idx_schedule_runs_workspace_started:sqliteCore.index("idx_schedule_runs_workspace_started").on(t.workspace_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_schedule_started:sqliteCore.index("idx_schedule_runs_schedule_started").on(t.schedule_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_task_id:sqliteCore.index("idx_schedule_runs_task_id").on(t.task_id),idx_schedule_runs_running:sqliteCore.index("idx_schedule_runs_running").on(t.workspace_id,t.started_at).where(drizzleOrm.sql`${t.status} = 'running'`)}));});var ja=b(()=>{g();sqliteCore.sqliteTable("run_column_backfill",{name:sqliteCore.text("name").primaryKey(),cursor:sqliteCore.integer("cursor"),anchor_id:sqliteCore.text("anchor_id"),completed_at:sqliteCore.text("completed_at")});});var Ka=b(()=>{g();sqliteCore.sqliteTable("doc_sync_connect_requests",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),ref:sqliteCore.text("ref").notNull(),sent_hash:sqliteCore.text("sent_hash").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({requestIdCheck:sqliteCore.check("doc_sync_connect_requests_request_id_ck",drizzleOrm.sql`length(${t.request_id}) = 36`),accountKeyCheck:sqliteCore.check("doc_sync_connect_requests_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("doc_sync_connect_requests_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("doc_sync_connect_requests_app_id_ck",drizzleOrm.sql`length(${t.app_id}) BETWEEN 1 AND 128`),refCheck:sqliteCore.check("doc_sync_connect_requests_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),sentHashCheck:sqliteCore.check("doc_sync_connect_requests_sent_hash_ck",drizzleOrm.sql`length(${t.sent_hash}) = 71 AND substr(${t.sent_hash}, 1, 7) = 'sha256:' AND substr(${t.sent_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),createdAtCheck:sqliteCore.check("doc_sync_connect_requests_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),connectUnique:sqliteCore.uniqueIndex("doc_sync_connect_requests_connect_uq").on(t.account_key,t.workspace_id,t.app_id,t.ref)}));});var Ja=b(()=>{g();sqliteCore.sqliteTable("doc_sync_links",{doc_id:sqliteCore.text("doc_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),root_segments:sqliteCore.text("root_segments").notNull(),ref:sqliteCore.text("ref").notNull(),cloud_ref:sqliteCore.text("cloud_ref").notNull(),origin:sqliteCore.text("origin").notNull().default("own"),sync_state:sqliteCore.text("sync_state").notNull().default("ok"),end_reason:sqliteCore.text("end_reason"),file_state:sqliteCore.text("file_state").notNull().default("present"),synced_revision:sqliteCore.integer("synced_revision").notNull(),synced_hash:sqliteCore.text("synced_hash").notNull(),synced_at:sqliteCore.integer("synced_at").notNull(),file_dev_ino:sqliteCore.text("file_dev_ino"),conflict_revision:sqliteCore.integer("conflict_revision"),conflict_hash:sqliteCore.text("conflict_hash"),conflict_at:sqliteCore.integer("conflict_at"),remote_revision:sqliteCore.integer("remote_revision"),remote_checked_at:sqliteCore.integer("remote_checked_at"),published_revision:sqliteCore.integer("published_revision"),bundle_sha256:sqliteCore.text("bundle_sha256"),missing_since:sqliteCore.integer("missing_since"),connected_at:sqliteCore.integer("connected_at").notNull(),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({docIdCheck:sqliteCore.check("doc_sync_links_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("doc_sync_links_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("doc_sync_links_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("doc_sync_links_app_id_ck",drizzleOrm.sql`length(${t.app_id}) BETWEEN 1 AND 128`),rootSegmentsCheck:sqliteCore.check("doc_sync_links_root_segments_ck",drizzleOrm.sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),refCheck:sqliteCore.check("doc_sync_links_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),cloudRefCheck:sqliteCore.check("doc_sync_links_cloud_ref_ck",drizzleOrm.sql`length(${t.cloud_ref}) BETWEEN 1 AND 256`),originCheck:sqliteCore.check("doc_sync_links_origin_ck",drizzleOrm.sql`${t.origin} IN ('own', 'received')`),syncStateCheck:sqliteCore.check("doc_sync_links_sync_state_ck",drizzleOrm.sql`${t.sync_state} IN ('ok', 'conflict', 'ended')`),endReasonCheck:sqliteCore.check("doc_sync_links_end_reason_ck",drizzleOrm.sql`${t.end_reason} IS NULL OR ${t.end_reason} IN ('disconnected', 'cloud_deleted')`),endedMatchesReasonCheck:sqliteCore.check("doc_sync_links_ended_reason_ck",drizzleOrm.sql`(${t.sync_state} = 'ended') = (${t.end_reason} IS NOT NULL)`),fileStateCheck:sqliteCore.check("doc_sync_links_file_state_ck",drizzleOrm.sql`${t.file_state} IN ('present', 'missing', 'root_unavailable')`),syncedRevisionCheck:sqliteCore.check("doc_sync_links_synced_revision_ck",drizzleOrm.sql`${t.synced_revision} >= 0`),syncedHashCheck:sqliteCore.check("doc_sync_links_synced_hash_ck",drizzleOrm.sql`length(${t.synced_hash}) = 71 AND substr(${t.synced_hash}, 1, 7) = 'sha256:' AND substr(${t.synced_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),connectedAtCheck:sqliteCore.check("doc_sync_links_connected_at_ck",drizzleOrm.sql`${t.connected_at} >= 0`),createdAtCheck:sqliteCore.check("doc_sync_links_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("doc_sync_links_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),liveRefUnique:sqliteCore.uniqueIndex("doc_sync_links_live_ref_uq").on(t.workspace_id,t.app_id,t.ref).where(drizzleOrm.sql`${t.sync_state} <> 'ended'`),accountStateIdx:sqliteCore.index("doc_sync_links_account_state_idx").on(t.account_key,t.sync_state),workspaceAppIdx:sqliteCore.index("doc_sync_links_workspace_app_idx").on(t.workspace_id,t.app_id)}));});var Va=b(()=>{g();sqliteCore.sqliteTable("route_states",{route_id:sqliteCore.text("route_id").primaryKey(),config_revision:sqliteCore.text("config_revision").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()}),sqliteCore.sqliteTable("route_sticky_bindings",{route_id:sqliteCore.text("route_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),candidate_id:sqliteCore.text("candidate_id").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({uniq_route_sticky_thread:sqliteCore.uniqueIndex("uniq_route_sticky_thread").on(t.route_id,t.thread_id),idx_route_sticky_candidate:sqliteCore.index("idx_route_sticky_candidate").on(t.route_id,t.candidate_id)})),sqliteCore.sqliteTable("route_decisions",{id:sqliteCore.text("id").primaryKey(),route_id:sqliteCore.text("route_id").notNull(),task_id:sqliteCore.text("task_id").notNull(),config_revision:sqliteCore.text("config_revision").notNull(),candidate_id:sqliteCore.text("candidate_id").notNull(),provider:sqliteCore.text("provider").notNull(),model:sqliteCore.text("model").notNull(),reason:sqliteCore.text("reason").notNull(),eligible_ids:sqliteCore.text("eligible_ids").notNull(),blocked_causes:sqliteCore.text("blocked_causes").notNull(),link_errors:sqliteCore.text("link_errors").notNull(),created_at:sqliteCore.text("created_at").notNull()},t=>({uniq_route_task_decision:sqliteCore.uniqueIndex("uniq_route_task_decision").on(t.route_id,t.task_id),idx_route_decisions_created:sqliteCore.index("idx_route_decisions_created").on(t.created_at)})),sqliteCore.sqliteTable("route_quota_observations",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),model:sqliteCore.text("model"),status:sqliteCore.text("status",{enum:["ok","blocked"]}).notNull(),source:sqliteCore.text("source").notNull(),reset_at:sqliteCore.text("reset_at"),observed_at:sqliteCore.text("observed_at").notNull()},t=>({uniq_route_quota_observation:sqliteCore.uniqueIndex("uniq_route_quota_observation").on(t.provider,t.account_ref,t.model,t.source),idx_route_quota_observations_reset:sqliteCore.index("idx_route_quota_observations_reset").on(t.reset_at)}));});var Wt=b(()=>{g();Sr();on();ea();na();Mn();oa();aa();da();ca();pa();fa();ha();ma();Ta();wa();Ea();Sa();Ia();Oa();va();Ks();Ma();Ha();Ua();Wa();Ga();ja();Ka();Ja();Va();});function Bn(t){return typeof t=="string"&&Et.includes(t)}function Xa(t){if(!t||!t.includes("workflow"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let s=n.workflow;if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let o=s.exec_id;if(typeof o=="string"&&o!=="")return o}return null}var Et,Mr=b(()=>{g();Et=["workflow_card","workflow_ui_instance","workflow_run"];});var un,eo,Ya,to=b(()=>{g();un={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5-5":{input:4,cachedInput:.2,output:20},"claude-opus-5-5-medium":{input:4,cachedInput:.2,output:20},"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-5":{input:2,cachedInput:.1,output:10},"claude-sonnet-5-5-medium":{input:2,cachedInput:.1,output:10},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-5-5":{input:.1,cachedInput:.01,output:.5},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-6.1-sol":{input:2,cachedInput:.1,output:10},"gpt-6.1-terra":{input:1,cachedInput:.05,output:5},"gpt-6-sol":{input:2,cachedInput:.2,output:10},"gpt-6-luna":{input:.1,cachedInput:.01,output:.5},"gpt-5.6-sol":{input:4,cachedInput:.4,output:20},"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.3-flash":{input:.15,cachedInput:.03,output:.5},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"deepseek-v4.1-flash":{input:.3,cachedInput:.006,output:1.2},"qwen3.8-flash":{input:.164,cachedInput:.018,output:.514},"minimax-m3":{input:.3,cachedInput:.06,output:1.2},"kimi-k2.7-code":{input:.95,cachedInput:.19,output: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.7":{input:2,cachedInput:.5,output:6},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},eo=new Set(["gpt-5.3-codex-spark","claude-opus-4-6-thinking","gpt-oss-120b","glm-5.3-flash-free","deepseek-v4.1-flash-free"]),Ya=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-opus-4-6","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7","claude-opus-4-7[1m]","claude-opus-4-8","claude-opus-4-8[1m]","claude-opus-5","claude-opus-5-5","claude-opus-5-5-medium","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","claude-sonnet-5-5-medium","deepseek-v4.1-flash","deepseek-v4.1-flash-free","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","gemini-3.8-flash","gemini-4-argon","glm-5.1","glm-5.2","glm-5.3-flash","glm-5.3-flash-free","gpt-4.1","gpt-4o","gpt-5-mini","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-6-luna","gpt-6-sol","gpt-6.1-sol","gpt-6.1-terra","gpt-oss-120b","grok-4.5","grok-4.6","grok-4.7","kimi-k2.7-code","minimax-m3","qwen3.8-flash"]);});function no(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 Sp(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Wn;let e=no(t),n=Rp[e];if(n)return $r[n]??un[n]??Wn;if($r[e])return $r[e];if(un[e])return un[e];if(eo.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Wn;if(Ya.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Wn;let r={...un,...$r};for(let s of Object.keys(r))if(e.includes(s))return r[s];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Wn}function Ip(t,e,n,r=0,s){let o=Sp(n),i=Math.min(r,t),d=(t-i)*o.input/1e6,c=i*o.cachedInput/1e6,l=e*o.output/1e6;return d+c+l}function Qa(t,e,n,r,s,o){return t&&t>0?t:!e&&!n?0:Ip(e??0,n??0,s,r??0)}var Rp,Wn,$r,Hr=b(()=>{g();to();to();Rp={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"},Wn={input:0,cachedInput:0,output:0},$r={};});function nd(t){if(!t||!t.includes("schedule_id"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.trigger;if(typeof r!="string"||!Ap.includes(r))return null;let s=n.schedule_id;return typeof s=="string"&&s!==""?s:null}var Ap,rd=b(()=>{g();Ap=["cron","cron_manual"];});function so(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function sd(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Ur(t){return Number.isSafeInteger(t)&&t>0}function Cp(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function Dp(t,e,n){let r=n==="win32"?t.toLowerCase():t,s=n==="win32"?e.toLowerCase():e;if(!s.trim())return false;if(s==="agy"){let o=Cp(t).split(/[\\/]/).pop()??"",i=n==="win32"?o.toLowerCase():o;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(s)}function Pp(t,e,n){return e.some(r=>Dp(t,r,n))}function Lp(t,e){try{let n=child_process.spawnSync(t,e,{encoding:"utf8",timeout:ro,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:so(n)}}}function Mp(t,e){return new Promise(n=>{let r;try{r=child_process.spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:so(c)});return}let s="",o="",i=false,u,d=setTimeout(()=>{try{r.kill();}catch{}u({status:null,stdout:s,stderr:o,error:new Error(`Command timed out after ${ro}ms`)});},ro);u=c=>{i||(i=true,clearTimeout(d),n(c));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",c=>{s+=String(c);}),r.stderr?.on("data",c=>{o+=String(c);}),r.once("error",c=>{u({status:null,stdout:s,stderr:o,error:c});}),r.once("close",c=>{u({status:c,stdout:s,stderr:o});});})}async function oo(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):Mp(t,e)}function $p(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function Hp(){return new Promise(t=>{setImmediate(t);})}function Rt(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return sd(n)==="ESRCH"?"not_found":sd(n)==="EPERM"?"alive":"unknown"}}function Up(t,e){let n=Rt(-t,e),r=Rt(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function id(t,e,n,r){let s=Math.max(0,n),o=Math.max(1,r.pollIntervalMs??vp),i=Date.now()+s,u,d=s===0,c=r.sleep?Promise.resolve().then(()=>r.sleep(s)).then(()=>{},()=>{}):new Promise(l=>{u=setTimeout(l,s);});c.then(()=>{d=true;});try{for(await Hp();;){let l=Up(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,$p(Math.min(o,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function od(t,e,n,r,s){let o=await id(t,e,s.hardConfirmMs??xp,{...s,sleep:void 0});return o==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:o==="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 ad(t,e,n={}){if(!Ur(t))return "unknown";let r=n.platform??process.platform,s=r==="win32"?"powershell.exe":"ps",o=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 oo(s,o,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let u=i.stdout.trim();return u?Pp(u,e,r)?"owned":"not_owned":"not_found"}function Wp(t){let e=qp.exec(t.trim());if(!e)return;let[,n="0",r="0",s="0",o="0"]=e;return ((Number(n)*24+Number(r))*60+Number(s))*60+Number(o)}function Gp(t){let e=t.trim(),n=Bp.exec(e);if(n){let[,s,o,i,u,d,c,l,p]=n;return Date.UTC(Number(s),Number(o)-1,Number(i),Number(u),Number(d),Number(c),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function dd(t,e){return e==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(t),"-o","pgid=","-o","etime=","-o","stat="]}}function ud(t,e,n){if(t.error)return {status:"unknown"};let r=t.stdout.trim();if(!r)return t.status===0||t.status===1?{status:"not_found"}:{status:"unknown"};if(t.status!==0)return {status:"unknown"};if(e==="win32"){let i=Gp(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let s=Fp.exec(r),o=s?Wp(s[2]):void 0;return !s||o===void 0?{status:"unknown"}:s[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-o*1e3,groupId:Number(s[1])}}function cd(t,e={}){if(!Ur(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=dd(t,n),o=e.runCommand??Lp,i;try{i=o(r,s);}catch{return {status:"unknown"}}return ud(i,n,Date.now())}async function ld(t,e={}){if(!Ur(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=dd(t,n),o;try{o=await oo(r,s,e);}catch{return {status:"unknown"}}return ud(o,n,Date.now())}async function It(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",s=f=>({status:"failed",pid:t,method:r,error:f});if(!Ur(t))return s("Invalid process ID");let o=e.kill??process.kill,i=Rt(t,o);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return s("Unable to determine whether the process is alive");if(n==="win32"){let f;try{f=await oo("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){f={status:null,stdout:"",stderr:"",error:so(m)};}let h=Rt(t,o);return h==="not_found"?f.status===0&&!f.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:s(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let u,d=e.signal??"SIGKILL";try{o(-t,d);}catch(f){u=f;}if(d==="SIGKILL")return od(t,o,u,r,e);if(await id(t,o,e.graceMs??bp,e)==="not_found")return u?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{o(-t,"SIGKILL");}catch(f){l=f;}let p=await od(t,o,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?u?p:{status:"terminated",pid:t,method:r}:s(p.error??"Process termination failed")}var ro,St,bp,vp,xp,qr,qp,Fp,Bp,Fr=b(()=>{g();ro=3e3,St="SIGINT",bp=2e3,vp=25,xp=100;qr=3e3,qp=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,Fp=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,Bp=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function hd(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new _("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new _("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function _d(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new _("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new _("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,s)=>hd(r,s))}catch(r){throw r instanceof _?new _("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function md(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new _("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new _("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new _("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function gd(t){return {taskId:t.id,source:md(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function Xp(t){if(!Number.isInteger(t)||t<0)throw new _("VALIDATION","Task log tail limit must be a non-negative integer")}var Br,kd=b(()=>{g();Tt();Dt();Pt();kt();Wt();Br=class extends Re{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=he.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?Ct(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=he.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new _("NOT_FOUND","Database not found");let r=M(n);if(e)try{Pe(r.db,n);}catch(s){throw r.close(),s}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(drizzleOrm.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(drizzleOrm.eq(a.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new _("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((o,i)=>hd(o,i));if(r.length===0){let o=this.getLogState(e);if(!o)throw new _("NOT_FOUND",`Task not found: ${e}`);return o}let s=this.openHandle(true);try{return s.db.transaction(i=>{let u=this.requireStateRowInTransaction(i,e),d=md(u);if(d==="blob"){let f=_d(e,u.logs);if(i.update(a).set({logs:JSON.stringify([...f,...r]),log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:u.last_log_seq}}let c=u.last_log_seq+1,l=u.last_log_seq+r.length;if(i.insert(rt).values(r.map((f,h)=>({task_id:e,seq:c+h,timestamp:f.timestamp,level:f.level,message:f.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to append task log",o)}finally{s.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?gd(r):void 0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return Xp(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(s=>{let o=this.findStateRowInTransaction(s,e);if(!o)return;let i=gd(o);if(i.source==="blob"){let l=_d(e,o.logs).map((p,f)=>({...p,seq:f+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=s.select({seq:rt.seq,timestamp:rt.timestamp,level:rt.level,message:rt.message}).from(rt).where(drizzleOrm.eq(rt.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(rt.seq):drizzleOrm.desc(rt.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({seq:l,timestamp:p,level:f,message:h})=>({seq:l,timestamp:p,level:f,message:h}));return n!==void 0&&c.reverse(),{...i,entries:c}},{behavior:"deferred"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read task logs",s)}finally{r.close();}}};});var tf,Wr,yd=b(()=>{g();Tt();Dt();Pt();kt();Wt();tf=50,Wr=class extends Re{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=`${e.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let e=this.resolveDbPath(),n=M(e);try{return Pe(n.db,e),n}catch(r){throw n.close(),r}}recordAccepted(e){if(e.actorKind!=="human"||!e.workspaceId||!e.actorId||!e.agentId)return false;let n;try{n=this.openHandle();let r=e.acceptedAt??new Date().toISOString();return n.db.insert(ve).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[ve.workspace_id,ve.actor_id,ve.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${ve.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(e,n){let r;try{return r=this.openHandle(),r.db.select({agentId:ve.agent_id,lastAcceptedAt:ve.last_accepted_at}).from(ve).where(drizzleOrm.and(drizzleOrm.eq(ve.workspace_id,e),drizzleOrm.eq(ve.actor_id,n))).orderBy(drizzleOrm.desc(ve.last_accepted_at),drizzleOrm.asc(ve.agent_id)).limit(tf).all()}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to find recent agent sends",s)}finally{r?.close();}}};});var wd=b(()=>{g();});var j,Gt=b(()=>{g();j=class extends Error{constructor(n,r,s){super(n);this.providerStr=r;this.name="ProviderError",this.code=s?.code??"UNKNOWN",this.kind=s?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=s?.retryAfterMs;}providerStr;code;kind;retryAfterMs;stdout};});var jt,io=b(()=>{g();Gt();jt=class extends j{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function Gr(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${we}]`),e=rf(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${we}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,we),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,we),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,we),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,we),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,we),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,we),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,we),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,we),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,we),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${we}${r}${we}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${we}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,Ed),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,Ed),e=e.replace(/[\r\n]{3,}/g,`
32
+ )`)}));});var Ma=N(()=>{g();sqliteCore.sqliteTable("ui_definition_archive",{definition_hash:sqliteCore.text("definition_hash").primaryKey().notNull(),definition_json:sqliteCore.text("definition_json").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({definitionHashCheck:sqliteCore.check("ui_definition_archive_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),definitionJsonCheck:sqliteCore.check("ui_definition_archive_definition_json_ck",drizzleOrm.sql`json_valid(${t.definition_json}) AND json_type(${t.definition_json}) = 'object'`),createdAtCheck:sqliteCore.check("ui_definition_archive_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`)}));});var Ha,Ua=N(()=>{g();Ha=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},t=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${t.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${t.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${t.stages_json}) AND json_type(${t.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${t.stage_index} >= 1`)})),sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>Ha.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${t.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${t.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${t.evidence_json}) AND json_type(${t.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(t.project_id,t.position)})),sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>Ha.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},t=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${t.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(t.project_id,t.seq)}));});var Xs,Ys,C,Qs=N(()=>{g();Xs=["THREAD_STATE","THREAD_PRIORITY"],Ys=["gray","blue","violet","green","amber","orange","red","pink"],C=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.code_group,t.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${t.metadata} IS NULL OR (json_valid(${t.metadata}) AND json_type(${t.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${t.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${t.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(t.code_group,t.is_archived,t.sort_order)}));});var qa,Fa,Ba,Wa,Ga,G,F,H,ja=N(()=>{g();$n();qa=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],Fa=["user","agent","system"],Ba=["auto","manual"],Wa=["decision","judgment","issue","result","pivot"],Ga=["queued","running","completed","failed"],G=sqliteCore.sqliteTable("thread_events",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),type:sqliteCore.text("type").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),payload_json:sqliteCore.text("payload_json").notNull(),created_at:sqliteCore.text("created_at").notNull(),actor_id:sqliteCore.text("actor_id"),task_id:sqliteCore.text("task_id"),highlight_id:sqliteCore.text("highlight_id")},t=>({typeCheck:sqliteCore.check("thread_events_type_ck",drizzleOrm.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:sqliteCore.check("thread_events_actor_type_ck",drizzleOrm.sql`${t.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:sqliteCore.check("thread_events_payload_json_ck",drizzleOrm.sql`json_valid(${t.payload_json}) AND json_type(${t.payload_json}) = 'object'`),threadSeqIndex:sqliteCore.index("idx_thread_events_thread_seq").on(t.thread_id,t.seq),threadCreatedIndex:sqliteCore.index("idx_thread_events_thread_created").on(t.thread_id,t.created_at),threadSeqUnique:sqliteCore.uniqueIndex("thread_events_thread_seq_uq").on(t.thread_id,t.seq)})),F=sqliteCore.sqliteTable("thread_highlight_runs",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),request_id:sqliteCore.text("request_id").notNull(),status:sqliteCore.text("status").notNull(),detector_version:sqliteCore.text("detector_version").notNull(),requested_at:sqliteCore.text("requested_at").notNull(),started_at:sqliteCore.text("started_at"),completed_at:sqliteCore.text("completed_at"),error_code:sqliteCore.text("error_code"),previous_auto_count:sqliteCore.integer("previous_auto_count"),new_auto_count:sqliteCore.integer("new_auto_count")},t=>({statusCheck:sqliteCore.check("thread_highlight_runs_status_ck",drizzleOrm.sql`${t.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:sqliteCore.check("thread_highlight_runs_counts_ck",drizzleOrm.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:sqliteCore.uniqueIndex("thread_highlight_runs_thread_request_uq").on(t.thread_id,t.request_id),inProgressThreadUnique:sqliteCore.uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(t.thread_id).where(drizzleOrm.sql`${t.status} IN ('queued', 'running')`),threadStatusRequestedIndex:sqliteCore.index("idx_thread_highlight_runs_thread_status_requested").on(t.thread_id,t.status,t.requested_at)})),H=sqliteCore.sqliteTable("thread_highlights",{id:sqliteCore.text("id").primaryKey().notNull(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),source:sqliteCore.text("source").notNull(),kind:sqliteCore.text("kind").notNull(),status:sqliteCore.text("status").notNull().default("active"),text:sqliteCore.text("text"),covers_from_task_id:sqliteCore.text("covers_from_task_id").notNull(),covers_to_task_id:sqliteCore.text("covers_to_task_id").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),agent_id:sqliteCore.text("agent_id"),source_task_id:sqliteCore.text("source_task_id"),detector_version:sqliteCore.text("detector_version"),content_fingerprint:sqliteCore.text("content_fingerprint"),dismissed_at:sqliteCore.text("dismissed_at")},t=>({sourceCheck:sqliteCore.check("thread_highlights_source_ck",drizzleOrm.sql`${t.source} IN ('auto', 'manual')`),kindCheck:sqliteCore.check("thread_highlights_kind_ck",drizzleOrm.sql`${t.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:sqliteCore.check("thread_highlights_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'dismissed')`),activeTextCheck:sqliteCore.check("thread_highlights_active_text_ck",drizzleOrm.sql`${t.status} = 'dismissed' OR (${t.text} IS NOT NULL AND length(${t.text}) > 0)`),coversCheck:sqliteCore.check("thread_highlights_covers_ck",drizzleOrm.sql`length(${t.covers_from_task_id}) > 0 AND length(${t.covers_to_task_id}) > 0`),autoKeyCheck:sqliteCore.check("thread_highlights_auto_key_ck",drizzleOrm.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:sqliteCore.index("idx_thread_highlights_thread_status_created").on(t.thread_id,t.status,t.created_at),threadCoversIndex:sqliteCore.index("idx_thread_highlights_thread_covers").on(t.thread_id,t.covers_from_task_id,t.covers_to_task_id),autoIdempotencyUnique:sqliteCore.uniqueIndex("thread_highlights_auto_idempotency_uq").on(t.thread_id,t.source_task_id,t.detector_version,t.content_fingerprint).where(drizzleOrm.sql`${t.source} = 'auto'`)}));});var za=N(()=>{g();sqliteCore.sqliteTable("storage_metadata",{source_kind:sqliteCore.text("source_kind").notNull(),source_id:sqliteCore.text("source_id").notNull(),utc_ts:sqliteCore.text("utc_ts"),bytes:sqliteCore.integer("bytes").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.source_kind,t.source_id]}),kindTimestampBytesIndex:sqliteCore.index("idx_storage_metadata_kind_ts_bytes").on(t.source_kind,t.utc_ts,t.bytes)})),sqliteCore.sqliteTable("storage_metadata_state",{unit:sqliteCore.text("unit").primaryKey().notNull(),cursor_rowid:sqliteCore.integer("cursor_rowid").notNull().default(0),end_rowid:sqliteCore.integer("end_rowid"),complete:sqliteCore.integer("complete").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()});});var xe,Ja=N(()=>{g();xe=sqliteCore.sqliteTable("agent_send_history",{workspace_id:sqliteCore.text("workspace_id").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),last_accepted_at:sqliteCore.text("last_accepted_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.actor_id,t.agent_id]}),recentIndex:sqliteCore.index("idx_agent_send_history_recent").on(t.workspace_id,t.actor_id,t.last_accepted_at,t.agent_id)}));});var Ya,Qa=N(()=>{g();$n();Or();sqliteCore.sqliteTable("sidebar_states",{workspace_id:sqliteCore.text("workspace_id").primaryKey().references(()=>ne.id,{onDelete:"cascade"}),revision:sqliteCore.integer("revision").notNull().default(0),rail_collapsed:sqliteCore.integer("rail_collapsed").notNull().default(0),seeded_at:sqliteCore.text("seeded_at").notNull()},t=>({railCollapsedCheck:sqliteCore.check("sidebar_states_rail_collapsed_ck",drizzleOrm.sql`${t.rail_collapsed} IN (0, 1)`)})),Ya=sqliteCore.sqliteTable("sidebar_groups",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),name:sqliteCore.text("name").notNull(),color:sqliteCore.text("color").notNull(),collapsed:sqliteCore.integer("collapsed").notNull().default(0),position:sqliteCore.integer("position").notNull()},t=>({colorCheck:sqliteCore.check("sidebar_groups_color_ck",drizzleOrm.sql`${t.color} IN ('cyan', 'orange', 'purple', 'blue')`),collapsedCheck:sqliteCore.check("sidebar_groups_collapsed_ck",drizzleOrm.sql`${t.collapsed} IN (0, 1)`),idxSidebarGroupsWorkspacePosition:sqliteCore.index("idx_sidebar_groups_workspace_position").on(t.workspace_id,t.position)})),sqliteCore.sqliteTable("sidebar_tabs",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ya.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})})),sqliteCore.sqliteTable("sidebar_closed_tabs",{id:sqliteCore.integer("id").primaryKey({autoIncrement:true}),workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),group_id:sqliteCore.text("group_id").references(()=>Ya.id,{onDelete:"set null"}),position:sqliteCore.integer("position").notNull(),closed_at:sqliteCore.text("closed_at").notNull()},t=>({idxSidebarClosedTabsWorkspaceId:sqliteCore.index("idx_sidebar_closed_tabs_workspace_id").on(t.workspace_id,t.id)})),sqliteCore.sqliteTable("thread_reads",{workspace_id:sqliteCore.text("workspace_id").notNull().references(()=>ne.id,{onDelete:"cascade"}),thread_id:sqliteCore.text("thread_id").notNull().references(()=>T.id,{onDelete:"cascade"}),read_through_at:sqliteCore.text("read_through_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.workspace_id,t.thread_id]})}));});var Za=N(()=>{g();sqliteCore.sqliteTable("schedule_runs",{id:sqliteCore.text("id").primaryKey(),schedule_id:sqliteCore.text("schedule_id").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),mode:sqliteCore.text("mode").notNull(),trigger:sqliteCore.text("trigger").notNull(),occurrence_key:sqliteCore.text("occurrence_key"),task_id:sqliteCore.text("task_id"),app_id:sqliteCore.text("app_id"),schedule_name:sqliteCore.text("schedule_name"),builtin_id:sqliteCore.text("builtin_id"),command:sqliteCore.text("command"),high_frequency:sqliteCore.integer("high_frequency").notNull().default(0),status:sqliteCore.text("status").notNull(),error_code:sqliteCore.text("error_code"),exit_code:sqliteCore.integer("exit_code"),signal:sqliteCore.text("signal"),started_at:sqliteCore.text("started_at").notNull(),finished_at:sqliteCore.text("finished_at"),duration_ms:sqliteCore.integer("duration_ms"),pid:sqliteCore.integer("pid"),host_pid:sqliteCore.integer("host_pid"),output_tail:sqliteCore.text("output_tail"),output_bytes:sqliteCore.integer("output_bytes"),output_truncated:sqliteCore.integer("output_truncated").notNull().default(0)},t=>({idx_schedule_runs_workspace_started:sqliteCore.index("idx_schedule_runs_workspace_started").on(t.workspace_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_schedule_started:sqliteCore.index("idx_schedule_runs_schedule_started").on(t.schedule_id,drizzleOrm.sql`${t.started_at} DESC`),idx_schedule_runs_task_id:sqliteCore.index("idx_schedule_runs_task_id").on(t.task_id),idx_schedule_runs_running:sqliteCore.index("idx_schedule_runs_running").on(t.workspace_id,t.started_at).where(drizzleOrm.sql`${t.status} = 'running'`)}));});var ed=N(()=>{g();sqliteCore.sqliteTable("run_column_backfill",{name:sqliteCore.text("name").primaryKey(),cursor:sqliteCore.integer("cursor"),anchor_id:sqliteCore.text("anchor_id"),completed_at:sqliteCore.text("completed_at")});});var td=N(()=>{g();sqliteCore.sqliteTable("doc_sync_connect_requests",{request_id:sqliteCore.text("request_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),ref:sqliteCore.text("ref").notNull(),sent_hash:sqliteCore.text("sent_hash").notNull(),created_at:sqliteCore.integer("created_at").notNull()},t=>({requestIdCheck:sqliteCore.check("doc_sync_connect_requests_request_id_ck",drizzleOrm.sql`length(${t.request_id}) = 36`),accountKeyCheck:sqliteCore.check("doc_sync_connect_requests_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("doc_sync_connect_requests_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("doc_sync_connect_requests_app_id_ck",drizzleOrm.sql`length(${t.app_id}) BETWEEN 1 AND 128`),refCheck:sqliteCore.check("doc_sync_connect_requests_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),sentHashCheck:sqliteCore.check("doc_sync_connect_requests_sent_hash_ck",drizzleOrm.sql`length(${t.sent_hash}) = 71 AND substr(${t.sent_hash}, 1, 7) = 'sha256:' AND substr(${t.sent_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),createdAtCheck:sqliteCore.check("doc_sync_connect_requests_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),connectUnique:sqliteCore.uniqueIndex("doc_sync_connect_requests_connect_uq").on(t.account_key,t.workspace_id,t.app_id,t.ref)}));});var rd=N(()=>{g();sqliteCore.sqliteTable("doc_sync_links",{doc_id:sqliteCore.text("doc_id").primaryKey().notNull(),account_key:sqliteCore.text("account_key").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),app_id:sqliteCore.text("app_id").notNull(),root_segments:sqliteCore.text("root_segments").notNull(),ref:sqliteCore.text("ref").notNull(),cloud_ref:sqliteCore.text("cloud_ref").notNull(),origin:sqliteCore.text("origin").notNull().default("own"),sync_state:sqliteCore.text("sync_state").notNull().default("ok"),end_reason:sqliteCore.text("end_reason"),file_state:sqliteCore.text("file_state").notNull().default("present"),synced_revision:sqliteCore.integer("synced_revision").notNull(),synced_hash:sqliteCore.text("synced_hash").notNull(),synced_at:sqliteCore.integer("synced_at").notNull(),file_dev_ino:sqliteCore.text("file_dev_ino"),conflict_revision:sqliteCore.integer("conflict_revision"),conflict_hash:sqliteCore.text("conflict_hash"),conflict_at:sqliteCore.integer("conflict_at"),remote_revision:sqliteCore.integer("remote_revision"),remote_checked_at:sqliteCore.integer("remote_checked_at"),published_revision:sqliteCore.integer("published_revision"),bundle_sha256:sqliteCore.text("bundle_sha256"),missing_since:sqliteCore.integer("missing_since"),connected_at:sqliteCore.integer("connected_at").notNull(),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({docIdCheck:sqliteCore.check("doc_sync_links_doc_id_ck",drizzleOrm.sql`length(${t.doc_id}) BETWEEN 1 AND 128`),accountKeyCheck:sqliteCore.check("doc_sync_links_account_key_ck",drizzleOrm.sql`length(${t.account_key}) = 64 AND ${t.account_key} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("doc_sync_links_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("doc_sync_links_app_id_ck",drizzleOrm.sql`length(${t.app_id}) BETWEEN 1 AND 128`),rootSegmentsCheck:sqliteCore.check("doc_sync_links_root_segments_ck",drizzleOrm.sql`json_valid(${t.root_segments}) AND json_type(${t.root_segments}) = 'array'`),refCheck:sqliteCore.check("doc_sync_links_ref_ck",drizzleOrm.sql`length(${t.ref}) BETWEEN 1 AND 256`),cloudRefCheck:sqliteCore.check("doc_sync_links_cloud_ref_ck",drizzleOrm.sql`length(${t.cloud_ref}) BETWEEN 1 AND 256`),originCheck:sqliteCore.check("doc_sync_links_origin_ck",drizzleOrm.sql`${t.origin} IN ('own', 'received')`),syncStateCheck:sqliteCore.check("doc_sync_links_sync_state_ck",drizzleOrm.sql`${t.sync_state} IN ('ok', 'conflict', 'ended')`),endReasonCheck:sqliteCore.check("doc_sync_links_end_reason_ck",drizzleOrm.sql`${t.end_reason} IS NULL OR ${t.end_reason} IN ('disconnected', 'cloud_deleted')`),endedMatchesReasonCheck:sqliteCore.check("doc_sync_links_ended_reason_ck",drizzleOrm.sql`(${t.sync_state} = 'ended') = (${t.end_reason} IS NOT NULL)`),fileStateCheck:sqliteCore.check("doc_sync_links_file_state_ck",drizzleOrm.sql`${t.file_state} IN ('present', 'missing', 'root_unavailable')`),syncedRevisionCheck:sqliteCore.check("doc_sync_links_synced_revision_ck",drizzleOrm.sql`${t.synced_revision} >= 0`),syncedHashCheck:sqliteCore.check("doc_sync_links_synced_hash_ck",drizzleOrm.sql`length(${t.synced_hash}) = 71 AND substr(${t.synced_hash}, 1, 7) = 'sha256:' AND substr(${t.synced_hash}, 8) NOT GLOB '*[^0-9a-f]*'`),connectedAtCheck:sqliteCore.check("doc_sync_links_connected_at_ck",drizzleOrm.sql`${t.connected_at} >= 0`),createdAtCheck:sqliteCore.check("doc_sync_links_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("doc_sync_links_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),liveRefUnique:sqliteCore.uniqueIndex("doc_sync_links_live_ref_uq").on(t.workspace_id,t.app_id,t.ref).where(drizzleOrm.sql`${t.sync_state} <> 'ended'`),accountStateIdx:sqliteCore.index("doc_sync_links_account_state_idx").on(t.account_key,t.sync_state),workspaceAppIdx:sqliteCore.index("doc_sync_links_workspace_app_idx").on(t.workspace_id,t.app_id)}));});var sd=N(()=>{g();sqliteCore.sqliteTable("route_states",{route_id:sqliteCore.text("route_id").primaryKey(),config_revision:sqliteCore.text("config_revision").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),updated_at:sqliteCore.text("updated_at").notNull()}),sqliteCore.sqliteTable("route_sticky_bindings",{route_id:sqliteCore.text("route_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),candidate_id:sqliteCore.text("candidate_id").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({uniq_route_sticky_thread:sqliteCore.uniqueIndex("uniq_route_sticky_thread").on(t.route_id,t.thread_id),idx_route_sticky_candidate:sqliteCore.index("idx_route_sticky_candidate").on(t.route_id,t.candidate_id)})),sqliteCore.sqliteTable("route_decisions",{id:sqliteCore.text("id").primaryKey(),route_id:sqliteCore.text("route_id").notNull(),task_id:sqliteCore.text("task_id").notNull(),config_revision:sqliteCore.text("config_revision").notNull(),candidate_id:sqliteCore.text("candidate_id").notNull(),provider:sqliteCore.text("provider").notNull(),model:sqliteCore.text("model").notNull(),reason:sqliteCore.text("reason").notNull(),eligible_ids:sqliteCore.text("eligible_ids").notNull(),blocked_causes:sqliteCore.text("blocked_causes").notNull(),link_errors:sqliteCore.text("link_errors").notNull(),created_at:sqliteCore.text("created_at").notNull()},t=>({uniq_route_task_decision:sqliteCore.uniqueIndex("uniq_route_task_decision").on(t.route_id,t.task_id),idx_route_decisions_created:sqliteCore.index("idx_route_decisions_created").on(t.created_at)})),sqliteCore.sqliteTable("route_quota_observations",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),model:sqliteCore.text("model"),status:sqliteCore.text("status",{enum:["ok","blocked"]}).notNull(),source:sqliteCore.text("source").notNull(),reset_at:sqliteCore.text("reset_at"),observed_at:sqliteCore.text("observed_at").notNull()},t=>({uniq_route_quota_observation:sqliteCore.uniqueIndex("uniq_route_quota_observation").on(t.provider,t.account_ref,t.model,t.source),idx_route_quota_observations_reset:sqliteCore.index("idx_route_quota_observations_reset").on(t.reset_at)}));});var zt=N(()=>{g();Or();an();ua();la();$n();_a();ha();ma();Ta();wa();Ea();Ia();Aa();Na();va();xa();Da();Pa();Ma();Ua();Qs();ja();za();Ja();Qa();Za();ed();td();rd();sd();});function Wn(t){return typeof t=="string"&&It.includes(t)}function od(t){if(!t||!t.includes("workflow"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.workflowRunId;if(typeof r=="string"&&r!=="")return r;let s=n.workflow;if(typeof s=="object"&&s!==null&&!Array.isArray(s)){let o=s.exec_id;if(typeof o=="string"&&o!=="")return o}return null}var It,Ur=N(()=>{g();It=["workflow_card","workflow_ui_instance","workflow_run"];});var cn,io,id,ao=N(()=>{g();cn={"claude-fable-5-1":{input:10,cachedInput:.25,output:50},"claude-fable-5":{input:10,cachedInput:1,output:50},"claude-opus-5-5":{input:4,cachedInput:.2,output:20},"claude-opus-5-5-medium":{input:4,cachedInput:.2,output:20},"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-5":{input:2,cachedInput:.1,output:10},"claude-sonnet-5-5-medium":{input:2,cachedInput:.1,output:10},"claude-sonnet-5":{input:2,cachedInput:.2,output:10},"claude-sonnet-4-6":{input:3,cachedInput:.3,output:15},"claude-haiku-5-5":{input:.1,cachedInput:.01,output:.5},"claude-haiku-4-5":{input:1,cachedInput:.1,output:5},"gpt-6-astra":{input:10,cachedInput:1,output:50},"gpt-6.1-sol":{input:2,cachedInput:.1,output:10},"gpt-6.1-terra":{input:1,cachedInput:.05,output:5},"gpt-6-sol":{input:2,cachedInput:.2,output:10},"gpt-6-luna":{input:.1,cachedInput:.01,output:.5},"gpt-5.6-sol":{input:4,cachedInput:.4,output:20},"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.3-flash":{input:.15,cachedInput:.03,output:.5},"glm-5.2":{input:1.4,cachedInput:.26,output:4.4},"glm-5.1":{input:1.4,cachedInput:.26,output:4.4},"deepseek-v4.1-flash":{input:.3,cachedInput:.006,output:1.2},"qwen3.8-flash":{input:.164,cachedInput:.018,output:.514},"minimax-m3":{input:.3,cachedInput:.06,output:1.2},"kimi-k2.7-code":{input:.95,cachedInput:.19,output: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.7":{input:2,cachedInput:.5,output:6},"grok-4.6":{input:2,cachedInput:.5,output:6},"grok-4.5":{input:2,cachedInput:.3,output:6}},io=new Set(["gpt-5.3-codex-spark","claude-opus-4-6-thinking","gpt-oss-120b","glm-5.3-flash-free","deepseek-v4.1-flash-free"]),id=new Set(["auto","claude-fable-5","claude-fable-5-1","claude-haiku-4-5","claude-haiku-5-5","claude-opus-4-6","claude-opus-4-6-thinking","claude-opus-4-6[1m]","claude-opus-4-7","claude-opus-4-7[1m]","claude-opus-4-8","claude-opus-4-8[1m]","claude-opus-5","claude-opus-5-5","claude-opus-5-5-medium","claude-sonnet-4-6","claude-sonnet-4-6[1m]","claude-sonnet-5","claude-sonnet-5-5","claude-sonnet-5-5-medium","deepseek-v4.1-flash","deepseek-v4.1-flash-free","gemini-3.1-pro","gemini-3.6-flash","gemini-3.7-flash","gemini-3.8-flash","gemini-4-argon","glm-5.1","glm-5.2","glm-5.3-flash","glm-5.3-flash-free","gpt-4.1","gpt-4o","gpt-5-mini","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-6-luna","gpt-6-sol","gpt-6.1-sol","gpt-6.1-terra","gpt-oss-120b","grok-4.5","grok-4.6","grok-4.7","kimi-k2.7-code","minimax-m3","qwen3.8-flash"]);});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 Gp(t){if(!t)return console.warn("[pricing] missing model id; cost is being recorded as 0"),Gn;let e=uo(t),n=Wp[e];if(n)return qr[n]??cn[n]??Gn;if(qr[e])return qr[e];if(cn[e])return cn[e];if(io.has(e))return console.warn(`[pricing] unpublished model pricing: ${t}, cost_usd=0`),Gn;if(id.has(e))return console.warn(`[pricing] missing catalog pricing: ${t}, cost_usd=0`),Gn;let r={...cn,...qr};for(let s of Object.keys(r))if(e.includes(s))return r[s];return console.warn(`[pricing] Unknown model: ${t}, cost_usd=0`),Gn}function jp(t,e,n,r=0,s){let o=Gp(n),i=Math.min(r,t),d=(t-i)*o.input/1e6,c=i*o.cachedInput/1e6,l=e*o.output/1e6;return d+c+l}function ad(t,e,n,r,s,o){return t&&t>0?t:!e&&!n?0:jp(e??0,n??0,s,r??0)}var Wp,Gn,qr,Fr=N(()=>{g();ao();ao();Wp={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"},Gn={input:0,cachedInput:0,output:0},qr={};});function ld(t){if(!t||!t.includes("schedule_id"))return null;let e;try{e=JSON.parse(t);}catch{return null}if(typeof e!="object"||e===null||Array.isArray(e))return null;let n=e,r=n.trigger;if(typeof r!="string"||!Kp.includes(r))return null;let s=n.schedule_id;return typeof s=="string"&&s!==""?s:null}var Kp,pd=N(()=>{g();Kp=["cron","cron_manual"];});function lo(t){return t instanceof Error?t:t===void 0?void 0:new Error(String(t))}function fd(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function Br(t){return Number.isSafeInteger(t)&&t>0}function Qp(t){let e=t.trim();if(!e)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(e);return n?.[1]??n?.[2]??e.split(/\s+/,1)[0]??""}function Zp(t,e,n){let r=n==="win32"?t.toLowerCase():t,s=n==="win32"?e.toLowerCase():e;if(!s.trim())return false;if(s==="agy"){let o=Qp(t).split(/[\\/]/).pop()??"",i=n==="win32"?o.toLowerCase():o;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return r.includes(s)}function ef(t,e,n){return e.some(r=>Zp(t,r,n))}function tf(t,e){try{let n=child_process.spawnSync(t,e,{encoding:"utf8",timeout:co,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:lo(n)}}}function nf(t,e){return new Promise(n=>{let r;try{r=child_process.spawn(t,e,{windowsHide:!0});}catch(c){n({status:null,stdout:"",stderr:"",error:lo(c)});return}let s="",o="",i=false,u,d=setTimeout(()=>{try{r.kill();}catch{}u({status:null,stdout:s,stderr:o,error:new Error(`Command timed out after ${co}ms`)});},co);u=c=>{i||(i=true,clearTimeout(d),n(c));},r.stdout?.setEncoding("utf8"),r.stderr?.setEncoding("utf8"),r.stdout?.on("data",c=>{s+=String(c);}),r.stderr?.on("data",c=>{o+=String(c);}),r.once("error",c=>{u({status:null,stdout:s,stderr:o,error:c});}),r.once("close",c=>{u({status:c,stdout:s,stderr:o});});})}async function po(t,e,n){return n.runCommandAsync?n.runCommandAsync(t,e):n.runCommand?n.runCommand(t,e):nf(t,e)}function rf(t){return new Promise(e=>{setTimeout(e,Math.max(0,t));})}function sf(){return new Promise(t=>{setImmediate(t);})}function At(t,e=process.kill){try{return e(t,0),"alive"}catch(n){return fd(n)==="ESRCH"?"not_found":fd(n)==="EPERM"?"alive":"unknown"}}function of(t,e){let n=At(-t,e),r=At(t,e);return n==="alive"||r==="alive"?"alive":n==="unknown"||r==="unknown"?"unknown":"not_found"}async function gd(t,e,n,r){let s=Math.max(0,n),o=Math.max(1,r.pollIntervalMs??Xp),i=Date.now()+s,u,d=s===0,c=r.sleep?Promise.resolve().then(()=>r.sleep(s)).then(()=>{},()=>{}):new Promise(l=>{u=setTimeout(l,s);});c.then(()=>{d=true;});try{for(await sf();;){let l=of(t,e);if(l==="not_found")return l;let p=i-Date.now();if(d||p<=0)return l;await Promise.race([c,rf(Math.min(o,p))]);}}finally{u!==void 0&&clearTimeout(u);}}async function _d(t,e,n,r,s){let o=await gd(t,e,s.hardConfirmMs??Yp,{...s,sleep:void 0});return o==="not_found"?n?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r}:o==="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 hd(t,e,n={}){if(!Br(t))return "unknown";let r=n.platform??process.platform,s=r==="win32"?"powershell.exe":"ps",o=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 po(s,o,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let u=i.stdout.trim();return u?ef(u,e,r)?"owned":"not_owned":"not_found"}function cf(t){let e=af.exec(t.trim());if(!e)return;let[,n="0",r="0",s="0",o="0"]=e;return ((Number(n)*24+Number(r))*60+Number(s))*60+Number(o)}function lf(t){let e=t.trim(),n=uf.exec(e);if(n){let[,s,o,i,u,d,c,l,p]=n;return Date.UTC(Number(s),Number(o)-1,Number(i),Number(u),Number(d),Number(c),Math.trunc(Number(l)/1e3))-Number(p)*6e4}let r=Date.parse(e);return Number.isFinite(r)?r:void 0}function md(t,e){return e==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${t}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(t),"-o","pgid=","-o","etime=","-o","stat="]}}function kd(t,e,n){if(t.error)return {status:"unknown"};let r=t.stdout.trim();if(!r)return t.status===0||t.status===1?{status:"not_found"}:{status:"unknown"};if(t.status!==0)return {status:"unknown"};if(e==="win32"){let i=lf(r);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let s=df.exec(r),o=s?cf(s[2]):void 0;return !s||o===void 0?{status:"unknown"}:s[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-o*1e3,groupId:Number(s[1])}}function Td(t,e={}){if(!Br(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=md(t,n),o=e.runCommand??tf,i;try{i=o(r,s);}catch{return {status:"unknown"}}return kd(i,n,Date.now())}async function yd(t,e={}){if(!Br(t))return {status:"unknown"};let n=e.platform??process.platform,{command:r,args:s}=md(t,n),o;try{o=await po(r,s,e);}catch{return {status:"unknown"}}return kd(o,n,Date.now())}async function Nt(t,e={}){let n=e.platform??process.platform,r=n==="win32"?"taskkill":"process-group",s=f=>({status:"failed",pid:t,method:r,error:f});if(!Br(t))return s("Invalid process ID");let o=e.kill??process.kill,i=At(t,o);if(i==="not_found")return {status:"not_found",pid:t,method:r};if(i!=="alive")return s("Unable to determine whether the process is alive");if(n==="win32"){let f;try{f=await po("taskkill",["/PID",String(t),"/T","/F"],e);}catch(m){f={status:null,stdout:"",stderr:"",error:lo(m)};}let h=At(t,o);return h==="not_found"?f.status===0&&!f.error?{status:"terminated",pid:t,method:r}:{status:"not_found",pid:t,method:r}:s(h==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let u,d=e.signal??"SIGKILL";try{o(-t,d);}catch(f){u=f;}if(d==="SIGKILL")return _d(t,o,u,r,e);if(await gd(t,o,e.graceMs??Vp,e)==="not_found")return u?{status:"not_found",pid:t,method:r}:{status:"terminated",pid:t,method:r};let l;try{o(-t,"SIGKILL");}catch(f){l=f;}let p=await _d(t,o,l,r,e);return p.status==="terminated"?p:p.status==="not_found"?u?p:{status:"terminated",pid:t,method:r}:s(p.error??"Process termination failed")}var co,Ot,Vp,Xp,Yp,Wr,af,df,uf,Gr=N(()=>{g();co=3e3,Ot="SIGINT",Vp=2e3,Xp=25,Yp=100;Wr=3e3,af=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,df=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,uf=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;});function Id(t,e){let n=e===void 0?"":` at index ${e}`;if(!t||typeof t!="object")throw new _("VALIDATION",`Task log entry${n} must be an object`);if(typeof t.timestamp!="string"||typeof t.level!="string"||typeof t.message!="string")throw new _("VALIDATION",`Task log entry${n} must contain string timestamp, level, and message fields`);return {timestamp:t.timestamp,level:t.level,message:t.message}}function Rd(t,e){if(e===null||e.trim()==="")return [];let n;try{n=JSON.parse(e);}catch(r){throw new _("DB_ERROR",`Malformed legacy task logs: ${t}`,r)}if(!Array.isArray(n))throw new _("DB_ERROR",`Malformed legacy task logs: ${t} (expected an array)`);try{return n.map((r,s)=>Id(r,s))}catch(r){throw r instanceof _?new _("DB_ERROR",`Malformed legacy task logs: ${t}`,r):r}}function Ad(t){if(t.log_storage!=="blob"&&t.log_storage!=="events")throw new _("DB_ERROR",`Invalid task log storage for task: ${t.id}`);if(!Number.isInteger(t.last_log_seq)||t.last_log_seq<0)throw new _("DB_ERROR",`Invalid task log sequence for task: ${t.id}`);if(!Number.isInteger(t.log_revision)||t.log_revision<0)throw new _("DB_ERROR",`Invalid task log revision for task: ${t.id}`);return t.log_storage}function Sd(t){return {taskId:t.id,source:Ad(t),revision:t.log_revision,lastSeq:t.last_log_seq}}function mf(t){if(!Number.isInteger(t)||t<0)throw new _("VALIDATION","Task log tail limit must be a non-negative integer")}var jr,Od=N(()=>{g();Et();$t();Ht();wt();zt();jr=class extends Se{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=me.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?Mt(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=me.dirname(n);Ru.existsSync(s)||Ru.mkdirSync(s,{recursive:true});}else if(!Ru.existsSync(n))throw new _("NOT_FOUND","Database not found");let r=M(n);if(e)try{Me(r.db,n);}catch(s){throw r.close(),s}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(drizzleOrm.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(drizzleOrm.eq(a.id,n)).limit(1).get()}requireStateRowInTransaction(e,n){let r=this.findStateRowInTransaction(e,n);if(!r)throw new _("NOT_FOUND",`Task not found: ${n}`);return r}appendLog(e,n){return this.appendLogs(e,[n])}appendLogs(e,n){let r=n.map((o,i)=>Id(o,i));if(r.length===0){let o=this.getLogState(e);if(!o)throw new _("NOT_FOUND",`Task not found: ${e}`);return o}let s=this.openHandle(true);try{return s.db.transaction(i=>{let u=this.requireStateRowInTransaction(i,e),d=Ad(u);if(d==="blob"){let f=Rd(e,u.logs);if(i.update(a).set({logs:JSON.stringify([...f,...r]),log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:u.last_log_seq}}let c=u.last_log_seq+1,l=u.last_log_seq+r.length;if(i.insert(it).values(r.map((f,h)=>({task_id:e,seq:c+h,timestamp:f.timestamp,level:f.level,message:f.message}))).run(),i.update(a).set({last_log_seq:l,log_revision:drizzleOrm.sql`${a.log_revision} + 1`}).where(drizzleOrm.eq(a.id,e)).run().changes!==1)throw new _("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:d,revision:u.log_revision+1,lastSeq:l}},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to append task log",o)}finally{s.close();}}getLogState(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=this.findStateRow(n,e);return r?Sd(r):void 0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to read task log state",r)}finally{n.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,n){return mf(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(s=>{let o=this.findStateRowInTransaction(s,e);if(!o)return;let i=Sd(o);if(i.source==="blob"){let l=Rd(e,o.logs).map((p,f)=>({...p,seq:f+1}));return {...i,entries:n===void 0?l:l.slice(Math.max(0,l.length-n))}}let u=s.select({seq:it.seq,timestamp:it.timestamp,level:it.level,message:it.message}).from(it).where(drizzleOrm.eq(it.task_id,e)).orderBy(n===void 0?drizzleOrm.asc(it.seq):drizzleOrm.desc(it.seq)),c=(n===void 0?u.all():u.limit(n).all()).map(({seq:l,timestamp:p,level:f,message:h})=>({seq:l,timestamp:p,level:f,message:h}));return n!==void 0&&c.reverse(),{...i,entries:c}},{behavior:"deferred"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read task logs",s)}finally{r.close();}}};});var Ef,Kr,bd=N(()=>{g();Et();$t();Ht();wt();zt();Ef=50,Kr=class extends Se{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=`${e.dbRoot}/.crewx/crewx.db`);}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(){let e=this.resolveDbPath(),n=M(e);try{return Me(n.db,e),n}catch(r){throw n.close(),r}}recordAccepted(e){if(e.actorKind!=="human"||!e.workspaceId||!e.actorId||!e.agentId)return false;let n;try{n=this.openHandle();let r=e.acceptedAt??new Date().toISOString();return n.db.insert(xe).values({workspace_id:e.workspaceId,actor_id:e.actorId,agent_id:e.agentId,last_accepted_at:r}).onConflictDoUpdate({target:[xe.workspace_id,xe.actor_id,xe.agent_id],set:{last_accepted_at:drizzleOrm.sql`MAX(${xe.last_accepted_at}, excluded.last_accepted_at)`}}).run(),!0}catch(r){return console.error("[AgentSendHistoryRepository] Failed to record accepted agent send",r),false}finally{n?.close();}}findRecentAgents(e,n){let r;try{return r=this.openHandle(),r.db.select({agentId:xe.agent_id,lastAcceptedAt:xe.last_accepted_at}).from(xe).where(drizzleOrm.and(drizzleOrm.eq(xe.workspace_id,e),drizzleOrm.eq(xe.actor_id,n))).orderBy(drizzleOrm.desc(xe.last_accepted_at),drizzleOrm.asc(xe.agent_id)).limit(Ef).all()}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to find recent agent sends",s)}finally{r?.close();}}};});var vd=N(()=>{g();});var Rf,U,bt=N(()=>{g();Rf=new Set(["ACCOUNT_SETTING_REQUIRED","MODEL_RETIRED","SUBSCRIPTION_REQUIRED"]),U=class extends Error{constructor(n,r,s){super(n);this.providerStr=r;this.name="ProviderError",this.code=s?.code??"UNKNOWN",this.kind=Rf.has(this.code)?"config":s?.kind??(this.code==="UNKNOWN"?"transient":void 0),this.retryAfterMs=s?.retryAfterMs,this.settingReason=s?.settingReason,this.replacementModel=s?.replacementModel,this.providerReason=s?.providerReason;}providerStr;code;kind;retryAfterMs;settingReason;replacementModel;providerReason;stdout};});var Jt,fo=N(()=>{g();bt();Jt=class extends U{name="RateLimitError";constructor(e,n="cli/claude"){super(e,n,{code:"QUOTA_EXHAUSTED",kind:"transient"});}};});function zr(t){if(typeof t!="string")return;let e=t.trim();if(e)return e=e.replace(/^\s*at\s+[^\r\n]+(?:\r?\n|$)/gim,""),e=e.replace(/(^|[\r\n])\s*(?:authorization|proxy-authorization|x-api-key|x-goog-api-key|x-auth-token|cookie|set-cookie)\s*:\s*[^\r\n]*/gim,`$1[HTTP HEADER ${Ee}]`),e=If(e),e=e.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\-/]+=*/gi,`${Ee}`),e=e.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9_-]*/g,Ee),e=e.replace(/\bghp_[A-Za-z0-9][A-Za-z0-9_-]*/g,Ee),e=e.replace(/\bxoxb-[A-Za-z0-9-]+/g,Ee),e=e.replace(/\bxoxp-[A-Za-z0-9-]+/g,Ee),e=e.replace(/\bAKIA[0-9A-Z]{12,}\b/g,Ee),e=e.replace(/\bgithub_pat_[A-Za-z0-9_]+/g,Ee),e=e.replace(/\bgho_[A-Za-z0-9_]+/g,Ee),e=e.replace(/\bAIza[A-Za-z0-9_-]{20,}\b/g,Ee),e=e.replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,Ee),e=e.replace(/\b(?:authorization|api[_ -]?key|access[_ -]?token|auth[_ -]?token|refresh[_ -]?token|token|secret|password)\s*([:=])\s*["']?[^\s,;&"']+/gi,(n,r)=>`${Ee}${r}${Ee}`),e=e.replace(/([?&](?:api[_-]?key|access[_-]?token|token)=)[^&\s]+/gi,`$1${Ee}`),e=e.replace(/(?:\/(?:Users|home|private|var\/folders|tmp|workspace|workspaces|Volumes|opt|etc|srv|Applications)\/[^\s"'`),;]+)/g,xd),e=e.replace(/\b[A-Z]:\\(?:Users|home|Windows|Program Files|workspace|workspaces)\\[^\s"'`),;]*/gi,xd),e=e.replace(/[\r\n]{3,}/g,`
33
33
 
34
- `).trim(),nf(e,1024)||void 0}function nf(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",s=0;for(let o of t){let i=n.encode(o).byteLength;if(s+i>e)break;r+=o,s+=i;}return r}function rf(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,s;for(;(s=e.exec(t))!==null;){if(s.index<r)continue;let o=s.index+s[0].length,i=sf(t,o),u=i>=0?i:t.indexOf(`
34
+ `).trim(),Sf(e,1024)||void 0}function Sf(t,e){let n=new TextEncoder;if(n.encode(t).byteLength<=e)return t;let r="",s=0;for(let o of t){let i=n.encode(o).byteLength;if(s+i>e)break;r+=o,s+=i;}return r}function If(t){let e=/\b(?:request|response|http)?\s*body\s*[:=]\s*/gim,n="",r=0,s;for(;(s=e.exec(t))!==null;){if(s.index<r)continue;let o=s.index+s[0].length,i=Af(t,o),u=i>=0?i:t.indexOf(`
35
35
  `,o)>=0?t.indexOf(`
36
- `,o):t.length;n+=t.slice(r,s.index),n+=`[HTTP BODY ${we}]`,r=u;}return n+t.slice(r)}function sf(t,e){let n=t[e];if(n==='"'||n==="'")return of(t,e,n);if(n!=="{"&&n!=="[")return -1;let r=[],s,o=false;for(let i=e;i<t.length;i+=1){let u=t[i];if(s){o?o=false:u==="\\"?o=true:u===s&&(s=void 0);continue}if(u==='"'||u==="'"){s=u;continue}if(u==="{"||u==="["){r.push(u);continue}if(u!=="}"&&u!=="]")continue;let d=r.pop();if(u==="}"&&d!=="{"||u==="]"&&d!=="[")return -1;if(r.length===0)return i+1}return -1}function of(t,e,n){let r=false;for(let s=e+1;s<t.length;s+=1){let o=t[s];if(r)r=false;else if(o==="\\")r=true;else if(o===n)return s+1}return -1}var we,Ed,ao=b(()=>{g();we="[REDACTED]",Ed="[PATH]";});function co(t){if(!jr(t)||t.type!=="item.started"||!Sd(t)||!Rd(t))return false;let e=t.item;return !jr(e)||!Sd(e)||!Rd(e)||!uo(e.id)?false:e.type==="web_search"?e.query===""&&jr(e.action)&&e.action.type==="other":e.type==="file_change"?e.status!=="in_progress"||!Array.isArray(e.changes)||e.changes.length===0?false:e.changes.every(n=>jr(n)&&uo(n.path)&&uo(n.kind)):false}function jr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Id(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function uo(t){return typeof t=="string"&&t.trim().length>0}function Rd(t){return !Id(t,"status")||t.status==="in_progress"}function Sd(t){for(let e of ["error","errors","isError","is_error"])if(Id(t,e))return false;return true}var lo=b(()=>{g();});function cn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ln(t){return typeof t=="string"&&t.trim().length>0}function po(t){return typeof t=="string"?t.trim().length>0:cn(t)?ln(t.code)||ln(t.message)||ln(t.error)||ln(t.reason):false}function jn(t){let e;try{e=JSON.parse(t);}catch{return}if(cn(e))switch(e.event){case "init":return cn(e.init)?{kind:"init",envelope:e,init:e.init}:void 0;case "step_update":{if(!cn(e.step_update))return;let n=e.step_update;return !ln(n.conversation_id)||!Number.isSafeInteger(n.step_index)||n.state!=="ACTIVE"&&n.state!=="DONE"&&!(n.state==="ERROR"&&n.step_type==="tool")||!ln(n.step_type)?void 0:{kind:"step_update",envelope:e,step:n}}case "result":return cn(e.result)?{kind:"result",envelope:e,result:e.result}:void 0;case "AGY_ERROR":{let n=po(e)?e:e.error;return po(n)?{kind:"agy_error",envelope:e,error:n}:void 0}default:return (e.status==="SUCCESS"||e.status==="ERROR")&&typeof e.response=="string"&&(typeof e.conversation_id=="string"||po(e.error)||cn(e.usage))?{kind:"legacy_result",envelope:e,result:e}:void 0}}function Ad(t){return jn(t)!==void 0}function Kn(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.trim())continue;let r=jn(n);r&&e.push(r);}return e}var fo=b(()=>{g();});function af(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let s=typeof r.type=="string"?r.type:"",o=e?gf[e]:void 0;return o?o(r,s):s?Object.values(Nd).some(i=>i(r,s)):false}function at(t,e){let n=t.split(`
37
- `).filter(r=>r.trim());return n.length===0?false:n.every(r=>af(r,e))}function Ie(t){return typeof t=="object"&&t!==null}function Od(t,e){if(e==="assistant"||e==="user"){let n=t.message;return Ie(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||Ie(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?Ie(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function df(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Od(t,e)}function uf(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Ie(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 Ie(n)&&typeof n.type=="string"}return false}function cf(t,e){if(e==="step_start"||e==="step_finish")return typeof t.stepID=="string"||typeof t.sessionID=="string"||Ie(t.part);if(e==="text"||e==="tool_use")return Ie(t.part);if(e==="error"){let n=t.error;return Ie(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function lf(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||Ie(t.part)||e==="result"&&typeof t.result=="string")}function pf(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?Ie(t.data):e==="result"?typeof t.result=="string":false}function ff(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 _f(t,e){return e==="available_commands"?Ie(t.tools)||Ie(t.commands):e==="usage"?Ie(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||Ie(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var Nd,gf,pn=b(()=>{g();lo();fo();Nd={claude:Od,codex:uf,opencode:cf,copilot:pf,gemini:ff},gf={...Nd,claude:df,opencode:lf,grok:_f,antigravity:t=>Ad(JSON.stringify(t))};});function dt(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function ut(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 fn=b(()=>{g();});function kf(t){let e=Tf(t),n=e.map((o,i)=>({line:o,index:i})).filter(({line:o})=>wf(o.value)),r=yf(e);return {result:n.length===1&&n[0].index===r?Ef(n[0].line.value):null,resultPreview:If(e,n),hasReservedLine:n.length>0}}function Ge(t,e){let n=kf(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function Tf(t){let e=[],n=0;for(let r=0;r<t.length;r++){let s=t[r];if(s!==`
36
+ `,o):t.length;n+=t.slice(r,s.index),n+=`[HTTP BODY ${Ee}]`,r=u;}return n+t.slice(r)}function Af(t,e){let n=t[e];if(n==='"'||n==="'")return Of(t,e,n);if(n!=="{"&&n!=="[")return -1;let r=[],s,o=false;for(let i=e;i<t.length;i+=1){let u=t[i];if(s){o?o=false:u==="\\"?o=true:u===s&&(s=void 0);continue}if(u==='"'||u==="'"){s=u;continue}if(u==="{"||u==="["){r.push(u);continue}if(u!=="}"&&u!=="]")continue;let d=r.pop();if(u==="}"&&d!=="{"||u==="]"&&d!=="[")return -1;if(r.length===0)return i+1}return -1}function Of(t,e,n){let r=false;for(let s=e+1;s<t.length;s+=1){let o=t[s];if(r)r=false;else if(o==="\\")r=true;else if(o===n)return s+1}return -1}var Ee,xd,_o=N(()=>{g();Ee="[REDACTED]",xd="[PATH]";});function ho(t){if(!Jr(t)||t.type!=="item.started"||!Dd(t)||!Cd(t))return false;let e=t.item;return !Jr(e)||!Dd(e)||!Cd(e)||!go(e.id)?false:e.type==="web_search"?e.query===""&&Jr(e.action)&&e.action.type==="other":e.type==="file_change"?e.status!=="in_progress"||!Array.isArray(e.changes)||e.changes.length===0?false:e.changes.every(n=>Jr(n)&&go(n.path)&&go(n.kind)):false}function Jr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pd(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function go(t){return typeof t=="string"&&t.trim().length>0}function Cd(t){return !Pd(t,"status")||t.status==="in_progress"}function Dd(t){for(let e of ["error","errors","isError","is_error"])if(Pd(t,e))return false;return true}var mo=N(()=>{g();});function ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pn(t){return typeof t=="string"&&t.trim().length>0}function ko(t){return typeof t=="string"?t.trim().length>0:ln(t)?pn(t.code)||pn(t.message)||pn(t.error)||pn(t.reason):false}function Kn(t){let e;try{e=JSON.parse(t);}catch{return}if(ln(e))switch(e.event){case "init":return ln(e.init)?{kind:"init",envelope:e,init:e.init}:void 0;case "step_update":{if(!ln(e.step_update))return;let n=e.step_update;return !pn(n.conversation_id)||!Number.isSafeInteger(n.step_index)||n.state!=="ACTIVE"&&n.state!=="DONE"&&!(n.state==="ERROR"&&n.step_type==="tool")||!pn(n.step_type)?void 0:{kind:"step_update",envelope:e,step:n}}case "result":return ln(e.result)?{kind:"result",envelope:e,result:e.result}:void 0;case "AGY_ERROR":{let n=ko(e)?e:e.error;return ko(n)?{kind:"agy_error",envelope:e,error:n}:void 0}default:return (e.status==="SUCCESS"||e.status==="ERROR")&&typeof e.response=="string"&&(typeof e.conversation_id=="string"||ko(e.error)||ln(e.usage))?{kind:"legacy_result",envelope:e,result:e}:void 0}}function Ld(t){return Kn(t)!==void 0}function zn(t){let e=[];for(let n of t.split(/\r?\n/)){if(!n.trim())continue;let r=Kn(n);r&&e.push(r);}return e}var To=N(()=>{g();});function Nf(t,e){let n=t.trimStart();if(!n.startsWith("{"))return false;let r;try{r=JSON.parse(n);}catch{return false}let s=typeof r.type=="string"?r.type:"",o=e?Mf[e]:void 0;return o?o(r,s):s?Object.values($d).some(i=>i(r,s)):false}function ct(t,e){let n=t.split(`
37
+ `).filter(r=>r.trim());return n.length===0?false:n.every(r=>Nf(r,e))}function Ae(t){return typeof t=="object"&&t!==null}function Md(t,e){if(e==="assistant"||e==="user"){let n=t.message;return Ae(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||Ae(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?Ae(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function bf(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:Md(t,e)}function vf(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Ae(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 Ae(n)&&typeof n.type=="string"}return false}function xf(t,e){if(e==="step_start"||e==="step_finish")return typeof t.stepID=="string"||typeof t.sessionID=="string"||Ae(t.part);if(e==="text"||e==="tool_use")return Ae(t.part);if(e==="error"){let n=t.error;return Ae(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function Cf(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||Ae(t.part)||e==="result"&&typeof t.result=="string")}function Df(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?Ae(t.data):e==="result"?typeof t.result=="string":false}function Pf(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 Lf(t,e){return e==="available_commands"?Ae(t.tools)||Ae(t.commands):e==="usage"?Ae(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||Ae(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var $d,Mf,fn=N(()=>{g();mo();To();$d={claude:Md,codex:vf,opencode:xf,copilot:Df,gemini:Pf},Mf={...$d,claude:bf,opencode:Cf,grok:Lf,antigravity:t=>Ld(JSON.stringify(t))};});function lt(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function pt(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 _n=N(()=>{g();});function Uf(t){let e=qf(t),n=e.map((o,i)=>({line:o,index:i})).filter(({line:o})=>Bf(o.value)),r=Ff(e);return {result:n.length===1&&n[0].index===r?Wf(n[0].line.value):null,resultPreview:Kf(e,n),hasReservedLine:n.length>0}}function ze(t,e){let n=Uf(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function qf(t){let e=[],n=0;for(let r=0;r<t.length;r++){let s=t[r];if(s!==`
38
38
  `&&s!=="\r")continue;let o=s==="\r"&&t[r+1]===`
39
39
  `?`\r
40
- `:s;e.push({value:t.slice(n,r),separator:o}),r+=o.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function yf(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function wf(t){return t.trimStart().startsWith(hf)}function Ef(t){let e=t.trim();if(!e.startsWith(bd)||!e.endsWith("]]"))return null;let n=e.slice(bd.length,-2);if(!n)return null;try{return Rf(JSON.parse(n))}catch{return null}}function Rf(t){return Sf(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function Sf(t){if(!Af(t)||Object.keys(t).some(r=>!mf.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?vd(t.taskId)&&vd(t.agentId):t.isError===true}function If(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,s)=>n.has(s)?"":r.value+r.separator).join("")}function vd(t){return typeof t=="string"&&t.trim().length>0}function Af(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var bd,hf,mf,_n=b(()=>{g();bd="[[crewx:delegation-result ",hf="[[crewx:delegation-result",mf=new Set(["schema","taskId","agentId","isError"]);});function je(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 gn=b(()=>{g();});var xd,Kr,_o,zr=b(()=>{g();xd=["none","minimal","low","medium","high","xhigh","max","ultra"],Kr={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},_o={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-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5-5",name:"Claude Sonnet 5.5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{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-5-5",name:"Claude Haiku 5.5",contextWindowTokens:1e6,tier:"speed"},{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-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5-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-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",contextWindowTokens:5e5,tier:"balanced"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,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"],defaultEffort:"xhigh"},"gpt-6.1-sol":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-6.1-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"max"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"max"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"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:[],suggestedModels:[{id:"opencode-go/glm-5.3-flash",name:"GLM-5.3 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/qwen3.8-flash",name:"Qwen3.8 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/minimax-m3",name:"MiniMax M3",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"opencode-go/kimi-k2.7-code",name:"Kimi K2.7 Code",contextWindowTokens:262144,tier:"balanced",recommended:true}],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"}],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.8-flash",name:"Gemini 3.8 Flash",tier:"balanced"},{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.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-5-5-medium",name:"Claude Sonnet 5.5",tier:"balanced"},{id:"claude-opus-5-5-medium",name:"Claude Opus 5.5",tier:"flagship"},{id:"gemini-4-argon",name:"Gemini 4 Argon",tier:"flagship"}],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.8-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"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-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"claude-opus-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-4-argon":{effort:["low","medium","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.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{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.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"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(_o).map(([t,e])=>[t,e.models]));});function go(t){return Nf[t]??t}function vf(t){return bf.get(t)??t}function ho(t){if(!t)return {};let e=Cf.get(t);return e?{...e}:{model:t}}function mo(t,e){return t==="antigravity"||t==="cli/antigravity"?ho(e):e===void 0?{}:{model:vf(e)}}var Of,Nf,bf,xf,Cf,zn=b(()=>{g();Of=[{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]"}],Nf={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};bf=new Map(Of.map(({baseModelId:t,catalogModelId:e})=>[t,e]));xf=[{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"}],Cf=new Map(xf.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Pf(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function At(t){return Jr(t).models}function Jr(t){let e=Df[t],n=_o[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??Pf()}function Jn(t,e){let n=Jr(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=mo(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Cd(t){return Jr(t).modelOverrides}function Dd(){return At("claude")}function Pd(){return At("codex")}function Ld(){return At("copilot")}function Md(){return At("antigravity")}var Df,Kt=b(()=>{g();zr();Hr();zn();Df={};});function $d(t){return Lf[t]??t}var Lf,Hd=b(()=>{g();Kt();zn();Lf={auto:"default"};});function Vr(t,e){return (Kr[t]??[]).includes(e)}function Ot(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Mf.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Ud(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 ["-c","sandbox_mode=workspace-write"];default:return []}}function qd(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 Fd(t){return !t||!Vr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Bd(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=$d(t);return e.has(n)?["--permission-mode",n]:[]}function Wd(t){return t?Vr("claude",t)?["--effort",t]:[]:[]}function Gd(t){return t==="default"?[]:t&&$f.has(t)?["--permission-mode",t]:[]}function jd(t){return t===true?["--always-approve"]:[]}function Kd(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 zd(t){return t?Vr("grok",t)?["--effort",t]:[]:[]}function Jd(t){if(!t)return [];switch(go(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Vd(t){return t?Vr("antigravity",t)?["--effort",t]:[]:[]}var Mf,$f,Vn=b(()=>{g();Hd();zn();zr();Mf=new Set(xd);$f=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function Hf(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),s="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,o="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=s!==void 0?s:o??0;return {inputTokens:s!==void 0?e+s:e,outputTokens:n,cachedInputTokens:i}}function Uf(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),s=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,u="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:u??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:s,cachedInputTokens:d}}function qf(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),s=Number(n.output??0)+Number(n.reasoning??0),o=n.cache,i=o?Number(o.read??0):0;return {inputTokens:r+i,outputTokens:s,cachedInputTokens:i}}function Xd(t){let e=new Map,n;for(let o of t.split(`
41
- `))if(o.trim())try{let i=JSON.parse(o);if(i.type!=="assistant")continue;let u=i.message,d=u?.id,c=u?.usage;if(typeof d!="string"||!c)continue;let l=Number(c.input_tokens??0),p=Number(c.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let f=u?.model;typeof f=="string"&&f&&(n=f);}catch{}if(e.size===0)return;let r=0,s=0;for(let o of e.values())r+=o.inputTokens,s+=o.cachedInputTokens;return {inputTokens:r,cachedInputTokens:s,model:n}}function hn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
42
- `))if(r.trim())try{let s=JSON.parse(r),o=qf(s);if(o){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=o.inputTokens,n.outputTokens+=o.outputTokens,n.cachedInputTokens+=o.cachedInputTokens;continue}let i=Hf(s)??Uf(s);i&&(e=i);}catch{}return n||(e??void 0)}var Xn=b(()=>{g();});function Ke(t,e){if(typeof t!="object"||t===null||Array.isArray(t))return e;let n=t.timestamp;return typeof n!="string"||!Number.isFinite(Date.parse(n))?e:new Date(n).toISOString()}var zt=b(()=>{g();});var Xr,Yd=b(()=>{g();Xr=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function Qd(t){let e=t.split(`
43
- `).filter(s=>s.trim()),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="assistant"&&Array.isArray(o.message?.content))for(let i of o.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Zd(t){let e=t.split(`
44
- `).filter(n=>n.trim());for(let n of e.reverse())try{let r=JSON.parse(n);if(typeof r=="object"&&r!==null&&r.type==="result")return r}catch{}}function mn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function su(t){let e=mn(t.rate_limit_info);if(t.type==="rate_limit_event"&&e?.status==="rejected")return `Claude rate limit: ${typeof e.rateLimitType=="string"?e.rateLimitType:"unknown"} (status: rejected)`;if(t.error==="rate_limit"){let n=Kf(t);return n?`Claude rate limit: ${n}`:"Claude rate limit"}if(t.type==="result"&&t.is_error===true){let n=typeof t.result=="string"?t.result:"";if(zf(n))return `Claude rate limit: ${n}`}}function Wf(t){for(let e of t.split(`
45
- `)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=mn(JSON.parse(n));if(r?.type==="result"&&r.is_error===!0&&typeof r.result=="string"&&r.result.startsWith("Not logged in"))return r.result}catch{}}}}function Gf(t){let e=mn(t);if(e?.type!=="rate_limit_event")return;let n=mn(mn(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=eu(n.five_hour),s=eu(n.seven_day);if(!(!r&&!s))return {...r?{five_hour:r}:{},...s?{seven_day:s}:{}}}function eu(t){let e=mn(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function tu(t){if(t?.is_error===true)return Gr(t.result)}function jf(t){let e=su(t);if(e)return e;if(t.type!=="result"||t.is_error!==true)return;let n=typeof t.result=="string"?t.result:"";if(n.trim())return n;let r=typeof t.subtype=="string"?t.subtype:"unknown",s=typeof t.terminal_reason=="string"?t.terminal_reason:"unknown";return `Claude ended without an answer (subtype=${r}, terminal_reason=${s})`}function Kf(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
40
+ `:s;e.push({value:t.slice(n,r),separator:o}),r+=o.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Ff(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Bf(t){return t.trimStart().startsWith($f)}function Wf(t){let e=t.trim();if(!e.startsWith(Hd)||!e.endsWith("]]"))return null;let n=e.slice(Hd.length,-2);if(!n)return null;try{return Gf(JSON.parse(n))}catch{return null}}function Gf(t){return jf(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function jf(t){if(!zf(t)||Object.keys(t).some(r=>!Hf.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?Ud(t.taskId)&&Ud(t.agentId):t.isError===true}function Kf(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,s)=>n.has(s)?"":r.value+r.separator).join("")}function Ud(t){return typeof t=="string"&&t.trim().length>0}function zf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Hd,$f,Hf,gn=N(()=>{g();Hd="[[crewx:delegation-result ",$f="[[crewx:delegation-result",Hf=new Set(["schema","taskId","agentId","isError"]);});function Je(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 hn=N(()=>{g();});var qd,Vr,yo,Xr=N(()=>{g();qd=["none","minimal","low","medium","high","xhigh","max","ultra"],Vr={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},yo={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-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5-5",name:"Claude Sonnet 5.5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{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-5-5",name:"Claude Haiku 5.5",contextWindowTokens:1e6,tier:"speed"},{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-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5-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-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",contextWindowTokens:5e5,tier:"balanced"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,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"],defaultEffort:"xhigh"},"gpt-6.1-sol":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-6.1-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"max"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"max"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"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:[],suggestedModels:[{id:"opencode-go/glm-5.3-flash",name:"GLM-5.3 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/qwen3.8-flash",name:"Qwen3.8 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/minimax-m3",name:"MiniMax M3",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"opencode-go/kimi-k2.7-code",name:"Kimi K2.7 Code",contextWindowTokens:262144,tier:"balanced",recommended:true}],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"}],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.8-flash",name:"Gemini 3.8 Flash",tier:"balanced"},{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.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-5-5-medium",name:"Claude Sonnet 5.5",tier:"balanced"},{id:"claude-opus-5-5-medium",name:"Claude Opus 5.5",tier:"flagship"},{id:"gemini-4-argon",name:"Gemini 4 Argon",tier:"flagship"}],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.8-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"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-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"claude-opus-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-4-argon":{effort:["low","medium","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.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{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.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"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(yo).map(([t,e])=>[t,e.models]));});function wo(t){return Vf[t]??t}function Yf(t){return Xf.get(t)??t}function Eo(t){if(!t)return {};let e=Zf.get(t);return e?{...e}:{model:t}}function Ro(t,e){return t==="antigravity"||t==="cli/antigravity"?Eo(e):e===void 0?{}:{model:Yf(e)}}var Jf,Vf,Xf,Qf,Zf,Jn=N(()=>{g();Jf=[{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]"}],Vf={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};Xf=new Map(Jf.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Qf=[{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"}],Zf=new Map(Qf.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function t_(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function vt(t){return Yr(t).models}function Yr(t){let e=e_[t],n=yo[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??t_()}function Vn(t,e){let n=Yr(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Ro(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Fd(t){return Yr(t).modelOverrides}function Bd(){return vt("claude")}function Wd(){return vt("codex")}function Gd(){return vt("copilot")}function jd(){return vt("antigravity")}var e_,Vt=N(()=>{g();Xr();Fr();Jn();e_={};});function Kd(t){return n_[t]??t}var n_,zd=N(()=>{g();Vt();Jn();n_={auto:"default"};});function Qr(t,e){return (Vr[t]??[]).includes(e)}function xt(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return r_.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Jd(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 ["-c","sandbox_mode=workspace-write"];default:return []}}function Vd(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 Xd(t){return !t||!Qr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Yd(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Kd(t);return e.has(n)?["--permission-mode",n]:[]}function Qd(t){return t?Qr("claude",t)?["--effort",t]:[]:[]}function Zd(t){return t==="default"?[]:t&&s_.has(t)?["--permission-mode",t]:[]}function eu(t){return t===true?["--always-approve"]:[]}function tu(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 nu(t){return t?Qr("grok",t)?["--effort",t]:[]:[]}function ru(t){if(!t)return [];switch(wo(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function su(t){return t?Qr("antigravity",t)?["--effort",t]:[]:[]}var r_,s_,Xn=N(()=>{g();zd();Jn();Xr();r_=new Set(qd);s_=new Set(["default","acceptEdits","auto","dontAsk","bypassPermissions","plan"]);});function o_(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),s="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,o="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=s!==void 0?s:o??0;return {inputTokens:s!==void 0?e+s:e,outputTokens:n,cachedInputTokens:i}}function i_(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),s=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,u="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,d=i!==void 0?i:u??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:s,cachedInputTokens:d}}function a_(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),s=Number(n.output??0)+Number(n.reasoning??0),o=n.cache,i=o?Number(o.read??0):0;return {inputTokens:r+i,outputTokens:s,cachedInputTokens:i}}function ou(t){let e=new Map,n;for(let o of t.split(`
41
+ `))if(o.trim())try{let i=JSON.parse(o);if(i.type!=="assistant")continue;let u=i.message,d=u?.id,c=u?.usage;if(typeof d!="string"||!c)continue;let l=Number(c.input_tokens??0),p=Number(c.cache_read_input_tokens??0);e.set(d,{inputTokens:l+p,cachedInputTokens:p});let f=u?.model;typeof f=="string"&&f&&(n=f);}catch{}if(e.size===0)return;let r=0,s=0;for(let o of e.values())r+=o.inputTokens,s+=o.cachedInputTokens;return {inputTokens:r,cachedInputTokens:s,model:n}}function mn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
42
+ `))if(r.trim())try{let s=JSON.parse(r),o=a_(s);if(o){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=o.inputTokens,n.outputTokens+=o.outputTokens,n.cachedInputTokens+=o.cachedInputTokens;continue}let i=o_(s)??i_(s);i&&(e=i);}catch{}return n||(e??void 0)}var Yn=N(()=>{g();});function Ve(t,e){if(typeof t!="object"||t===null||Array.isArray(t))return e;let n=t.timestamp;return typeof n!="string"||!Number.isFinite(Date.parse(n))?e:new Date(n).toISOString()}var Xt=N(()=>{g();});var Zr,iu=N(()=>{g();Zr=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function au(t){let e=t.split(`
43
+ `).filter(s=>s.trim()),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="assistant"&&Array.isArray(o.message?.content))for(let i of o.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function du(t){let e=t.split(`
44
+ `).filter(n=>n.trim());for(let n of e.reverse())try{let r=JSON.parse(n);if(typeof r=="object"&&r!==null&&r.type==="result")return r}catch{}}function kn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function fu(t){let e=kn(t.rate_limit_info);if(t.type==="rate_limit_event"&&e?.status==="rejected")return `Claude rate limit: ${typeof e.rateLimitType=="string"?e.rateLimitType:"unknown"} (status: rejected)`;if(t.error==="rate_limit"){let n=f_(t);return n?`Claude rate limit: ${n}`:"Claude rate limit"}if(t.type==="result"&&t.is_error===true){let n=typeof t.result=="string"?t.result:"";if(__(n))return `Claude rate limit: ${n}`}}function c_(t){for(let e of t.split(`
45
+ `)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=kn(JSON.parse(n));if(r?.type==="result"&&r.is_error===!0&&typeof r.result=="string"&&r.result.startsWith("Not logged in"))return r.result}catch{}}}}function l_(t){let e=kn(t);if(e?.type!=="rate_limit_event")return;let n=kn(kn(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=uu(n.five_hour),s=uu(n.seven_day);if(!(!r&&!s))return {...r?{five_hour:r}:{},...s?{seven_day:s}:{}}}function uu(t){let e=kn(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function cu(t){if(t?.is_error===true)return zr(t.result)}function p_(t){let e=fu(t);if(e)return e;if(t.type!=="result"||t.is_error!==true)return;let n=typeof t.result=="string"?t.result:"";if(n.trim())return n;let r=typeof t.subtype=="string"?t.subtype:"unknown",s=typeof t.terminal_reason=="string"?t.terminal_reason:"unknown";return `Claude ended without an answer (subtype=${r}, terminal_reason=${s})`}function f_(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
46
46
 
47
- `):""}function zf(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function ru(t){return t.replace(/\s+/g," ").trim()}function Jf(t,e){let n=t?.description;if(typeof n!="string")return;let r=ru(n);if(!r||r===ru(e))return;if(r.length<=nu)return r;let s=r.slice(0,nu-1);return /[\uD800-\uDBFF]$/.test(s)&&(s=s.slice(0,-1)),`${s}\u2026`}function Vf(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),s=e.id,o=e.input,i=je(o);if(r==="Bash"&&dt(i))return ut(t,i,s);let u=Jf(o,i);return {timestamp:t,type:"tool_use",toolUseId:s,toolName:r,toolInput:i,...u?{toolTitle:u}:{}}}if(n==="tool_result"){let r=!!e.is_error,s=e.tool_use_id,o=e.output??e.content??"",i;return typeof o=="string"?i=o:Array.isArray(o)?i=o.filter(u=>u.type==="text"&&typeof u.text=="string").map(u=>u.text).join(`
48
- `):i=JSON.stringify(o),{timestamp:t,type:"tool_result",toolUseId:s,...Ge(i,r)}}return null}var Ff,Bf,Yr,nu,ko=b(()=>{g();io();Gt();ao();pn();fn();_n();gn();Vn();Kt();Xn();zt();Yd();Ff=new Set(["tool_progress"]),Bf="cli/claude";Yr={command:"claude",meta:{displayName:"Claude",models:Dd(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=Ot(e.model),o=e.effort??s,i=Bd(e.mode),u=Wd(o),d=r?["--model",r]:[],c=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let p=[...e.additionalArgs];return p.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...c,...i,...u,...d,...p],stdinMessage:t,env:Xr}:{args:["--output-format","stream-json","--verbose",...c,...i,...u,...d,...p],stdinMessage:t,env:Xr}}return {args:["-p","--output-format","stream-json","--verbose",...c,...i,...u,...d],stdinMessage:t,env:Xr}},extractText(t){let e=Zd(t);if(e?.is_error===true){let s=Yr.extractFailure(JSON.stringify(e));if(s)throw s;let o=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new j(tu(e)??`Claude ended without an answer (subtype=${o}, terminal_reason=${i})`,Bf,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=Qd(t);if(n)return n;let r=t.trim();return at(r,"claude")?"":r},extractPartialText(t){return Qd(t)},extractFailure(t){try{let e=JSON.parse(t),n=su(e);if(n)return new jt(n)}catch{}return null},interpretExit(t,e,n){let r=Wf(n??"");if(r)return new j(`Claude is not logged in (exit ${t}): ${r}. Sign in to this account with the official "claude auth login".`,"cli/claude",{code:"AUTH_REQUIRED",kind:"config"});let s=tu(Zd(n??""));return s?new j(s,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return Gf(e)}catch{return}},parseResultMeta(t){let e=t.split(`
49
- `);for(let r of e)if(r.trim())try{let s=JSON.parse(r);if(s.type==="result"){let o=s.usage,i=o?{inputTokens:Number(o.input_tokens??0)+Number(o.cache_read_input_tokens??0),outputTokens:Number(o.output_tokens??0),cachedInputTokens:Number(o.cache_read_input_tokens??0),costUsd:Number(s.total_cost_usd??0)}:null,u=s.modelUsage,d=u?Object.keys(u)[0]??null:null;return {usage:i,model:d}}}catch{}let n=Xd(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 s=Ke(n,e??new Date().toISOString()),o=jf(n);if(o)return [{timestamp:s,type:"error",content:o,errorMessage:o}];let i=n.output_file,u=n.summary;if(r==="system"&&n.subtype==="task_notification"&&n.status==="completed"&&typeof i=="string"&&i.trim().length>0&&typeof u=="string"&&u.trim().length>0)return [{timestamp:s,type:"text",content:u}];if(r!=="assistant"&&r!=="user")return [];let c=n.message?.content;if(!Array.isArray(c))return [];let l=[];for(let p of c){let f=Vf(s,p);f&&l.push(f);}return l},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Ff.has(r):!1}catch{return false}}};nu=200;});function ou(t){let e=t.split(`
50
- `).filter(s=>s.trim()),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="assistant.message"&&typeof o.data?.content=="string"){let i=o.data.content;i.trim()&&n.push(i.trim());}o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var Xf,To,yo=b(()=>{g();pn();Xn();fn();gn();_n();Kt();zr();zt();Xf=new Set(["interactive","plan","autopilot"]);To={command:"copilot",meta:{displayName:"Copilot",models:Ld()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&Xf.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Kr.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=ou(t);if(e)return e;let n=t.trim();return at(n,"copilot")?"":n},extractPartialText(t){return ou(t)},parseResultMeta(t){let e=hn(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 s=n.data;if(!s)return [];let o=Ke(n,e??new Date().toISOString()),i=s.toolCallId;if(r==="tool.execution_start"){let u=String(s.toolName||""),d=s.arguments,c=je(d);return (u==="bash"||u==="Bash")&&dt(c)?[ut(o,c,i)]:[{timestamp:o,type:"tool_use",toolName:u,toolInput:c,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let u=s.error;if(u)return [{timestamp:o,type:"tool_result",...i&&{toolUseId:i},...Ge(String(u.message||""),true)}];let d=s.result,c=String(d?.content||"");return [{timestamp:o,type:"tool_result",...i&&{toolUseId:i},...Ge(c,false)}]}if(r==="assistant.message"){let u=String(s.content||"");return u?[{timestamp:o,type:"text",content:u}]:[]}return []}};});function Zf(t){let e=[],n=0,r=false,s=false,o=0;for(let u=0;u<t.length;u++){let d=t[u];if(s){s=false;continue}if(d==="\\"&&r){s=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let c=t.slice(o,u+1).trim();c&&e.push(c),o=u+1;}}}let i=t.slice(o).trim();return i&&e.push(i),e}function e_(t){return t[0]==="exec"?t.slice(1):t}function iu(t){let e=t.split(`
51
- `).map(s=>s.trim()).filter(Boolean),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="item.completed"&&(o.item?.type==="message"||o.item?.type==="agent_message")&&typeof o.item?.text=="string"){let i=o.item.text;i.trim()&&n.push(i.trim());}o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function du(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Nt(t.error)}function uu(t){let e=Nt(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 t_(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Nt(n)&&du(n))return uu(n)}}function au(t,e,n,r){if(!n||t.type!=="command_execution"&&t.type!=="mcp_tool_call"||typeof t.id!="string"||!t.id.trim()||t.type==="mcp_tool_call"&&e==="item.started"&&(typeof t.server!="string"||typeof t.tool!="string"))return;let s=n.state.get("codex.pending");s||(s=new Map,n.state.set("codex.pending",s));let o=JSON.stringify([t.type,t.id]);if(e==="item.started"){let d=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,c=s.get(o)??[];return c.push(d),s.set(o,c),d}let i=s.get(o),u=i?.pop();return i?.length||s.delete(o),u}function n_(t,e,n){let r=e.type;if(r==="command_execution"){let s=String(e.command||"");return dt(s)?[ut(t,s,n)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:s,...n?{toolUseId:n}:{}}]}return r==="mcp_tool_call"?typeof e.server!="string"||typeof e.tool!="string"?[]:[{timestamp:t,type:"tool_use",toolName:`${e.server}/${e.tool}`,toolInput:je(e.arguments),...n?{toolUseId:n}:{}}]:[]}function r_(t,e,n){let r=e.type;if(r==="message"||r==="text"){let s=e.content;if(Array.isArray(s))for(let o of s){let i=s_(t,o);if(i)return i}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(r==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(r==="reasoning"){let s=typeof e.text=="string"?e.text.trim():"";return s?{timestamp:t,type:"thinking",content:s}:null}if(r==="command_execution"){let s=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:t,type:"tool_result",...Ge(s,o),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let s=Nt(e.result)?e.result:void 0,i=(Array.isArray(s?.content)?s.content:[]).filter(d=>Nt(d)&&d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
52
- `),u=typeof e.error=="string"?e.error:Nt(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||u,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let s=String(e.name||e.tool_name||""),o=e.input,i=je(o);return s==="Bash"&&dt(i)?ut(t,i):{timestamp:t,type:"tool_use",toolName:s,toolInput:i}}if(r==="tool_result"){let s=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...Ge(o,s)}}if(r==="web_search"){let s=e.action,o;if(s?.type==="search"){let i=s.queries;o=String(s.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else o=e.query?"open: "+String(e.query):"";return !o&&!(Nt(s)&&s.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:o}}if(r==="file_change"){let s=e.changes;if(!Array.isArray(s)||s.length===0)return null;let o=s.map(u=>String(u.path||"")).filter(Boolean);if(o.length===0)return null;let i=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:i}}return null}function s_(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||""),s=e.input,o=je(s);return r==="Bash"&&dt(o)?ut(t,o):{timestamp:t,type:"tool_use",toolName:r,toolInput:o}}return null}var Yf,Qf,wo,Eo=b(()=>{g();Gt();pn();Xn();fn();gn();lo();_n();Vn();Kt();zt();Yf=new Set(["turn.started","turn.completed","item.updated"]),Qf="cli/codex";wo={command:"codex",meta:{displayName:"Codex",models:Pd(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=Ot(e.model),o=e.effort??s,i=e.resumeSessionId?qd(e.mode):Ud(e.mode),u=Fd(o),d=r?["-m",r]:[],c=e_(e.additionalArgs??[]),p=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...i,...u,...d,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...i,...u,...d,...c],stdinMessage:t}},extractText(t){let e=t_(t);if(e)throw new j(e,Qf);let n=iu(t);if(n)return n;let r=t.trim();return at(r,"codex")?"":r},extractPartialText(t){return iu(t)},parseResultMeta(t){let e=hn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e,n){let r=e??new Date().toISOString(),s=[],o;try{JSON.parse(t),o=[t];}catch{o=Zf(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,u]of o.entries()){let d;try{d=JSON.parse(u);}catch{continue}if(!Nt(d))continue;let c=d.type;if(!c)continue;let l=Ke(d,r);if(du(d)){let f=uu(d);s.push({timestamp:l,type:"error",content:f,errorMessage:f});continue}if(!c.startsWith("item.")&&!c.startsWith("turn.")&&!c.startsWith("thread.")||co(d))continue;c==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(c==="item.started"){s.push(...n_(l,p,au(p,c,n,i)));continue}if(c==="item.completed"){let f=r_(l,p,au(p,c,n,i));f&&s.push(f);continue}}}return s},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Yf.has(r):!1}catch{return false}}};});function d_(t){return t?a_[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function Jt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function _u(t){let e=[],n=0,r=false,s=false,o=0;for(let u=0;u<t.length;u++){let d=t[u];if(s){s=false;continue}if(d==="\\"&&r){s=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let c=t.slice(o,u+1).trim();c&&e.push(c),o=u+1;}}}let i=t.slice(o).trim();return i&&e.push(i),e}function Xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function u_(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let s=r.trim();if(!s)continue;try{let i=JSON.parse(s);Xt(i)?e.push(i):n=!0;continue}catch{}let o=_u(s);o.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of o)try{let u=JSON.parse(i);Xt(u)?e.push(u):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Vt(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,fu).trim()}function Ro(t){let e=Xt(t.error)?t.error:void 0,n=e&&Xt(e.data)?e.data:void 0,r=Vt(e?.name),s=Vt(n?.message)??Vt(e?.message)??Vt(t.message)??Vt(t.errorMessage)??Vt(t.error),o=Vt(t.ref),i=r&&s&&r!==s?`${r}: ${s}`:r??s??pu;return (o?`${i} (ref: ${o})`:i).slice(0,fu)}function cu(t){let e=Xt(t.error)?t.error:void 0,n=typeof e?.type=="string"?e.type:void 0,r=typeof e?.status=="number"?e.status:Number(e?.status),s=Ro(t);return n==="provider.auth"||r===401||r===403?new j(`OpenCode authentication is required: ${s}`,ft,{code:"AUTH_REQUIRED",kind:"config"}):n==="provider.free-limit"||r===429?new j(`OpenCode rate limit reached: ${s}`,ft,{code:"RATE_LIMITED",kind:"transient"}):n==="provider.no-route"?new j(`OpenCode model or variant unavailable: ${s}`,ft,{code:"MODEL_UNAVAILABLE",kind:"config"}):new j(`OpenCode error: ${s}`,ft,{code:"PROVIDER_CRASHED",kind:"transient"})}function lu(t){let e=u_(t),n=[],r=null,s=0,o=[],i=[],u,d=false;for(let c of e.events){let l=typeof c.type=="string"?c.type:void 0;if(l){if(l==="text"){let p=Xt(c.part)?c.part:void 0,f=typeof p?.text=="string"?p.text:void 0;f?.trim()&&n.push(f.trim());continue}if(l==="result"){typeof c.result=="string"&&(r=c.result);continue}if(l==="tool_use"){s++;continue}if(l==="error"){o.push(c),i.push(Ro(c));continue}if(l==="step_finish"){d=true;let p=Xt(c.part)?c.part:void 0;u=typeof p?.reason=="string"?p.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:s,errorEvents:o,errorMessages:i,terminalReason:u,hasTerminal:d}}function gu(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function c_(){return new j("OpenCode returned no assistant output.",ft,{code:"EMPTY_OUTPUT",kind:"transient"})}function l_(){return new j("OpenCode emitted malformed JSON output.",ft,{code:"PROVIDER_CRASHED",kind:"transient"})}function p_(t,e){switch(gu(t)){case "length":return new j("OpenCode stopped because the context window was exceeded.",ft,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new j("OpenCode stopped because the content filter blocked the response.",ft,{code:"UNKNOWN",kind:"permanent"});case "error":return new j(`${pu} while generating a response.`,ft,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var o_,ft,pu,fu,i_,a_,So,Io=b(()=>{g();Gt();Xn();gn();zt();o_=new Set(["step_start","step_finish"]),ft="cli/opencode",pu="OpenCode provider error",fu=240,i_="Follow the instructions provided on standard input.",a_={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};So={command:"opencode",meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,s=r!==void 0?[...r]:["run"];Jt(s,"--format")||s.push("--format","json"),!Jt(s,"--standalone")&&!Jt(s,"--server")&&s.push("--standalone"),e.resumeSessionId&&!s.includes("-s")&&!s.includes("--session")&&s.push("-s",e.resumeSessionId);let{agent:o,autoApprove:i}=d_(e.mode);Jt(s,"--agent")||o!==void 0&&s.push("--agent",o),i&&!Jt(s,"--auto")&&s.push("--auto");let u=Jt(s,"--model")||Jt(s,"-m");if(e.model&&!u){let d=e.effort?`${e.model}#${e.effort}`:e.model;s.push("--model",d);}else e.effort&&!e.model&&!u&&console.debug("[opencode] ignoring effort because no model is configured");return s.push(i_),{args:s,stdinMessage:t}},extractText(t){let e=lu(t),n=e.errorEvents[0];if(n)throw cu(n);let r=p_(e.terminalReason??"");if(r)throw r;let s=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(s!==void 0)return s;if(e.resultText?.trim())return e.resultText;if(e.malformed)throw l_();let o=gu(e.terminalReason);if(e.hasTerminal&&o==="tool-calls"&&e.toolUseCount>0)return "";throw c_()},interpretExit(t,e,n=""){if(t===0)return null;let s=lu(n).errorEvents[0];return s?cu(s):null},parseResultMeta(t){let e=hn(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=[],s;try{JSON.parse(t),s=[t];}catch{s=_u(t),s.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let o of s){let i;try{i=JSON.parse(o);}catch{continue}let u=Ke(i,n),d=i.type;if(d){if(d==="text"){let l=i.part?.text;l&&r.push({timestamp:u,type:"text",content:l});continue}if(d==="tool_use"){let c=i.part;if(!c)continue;let l=String(c.tool||""),p=String(c.callID||c.id||""),f=c.state,h=String(f?.status||""),m=f?.input,k=je(m);if(r.push({timestamp:u,type:"tool_use",toolName:l,toolUseId:p,toolInput:k}),h==="completed"&&f?.output!==void 0){let E=f.output,v=typeof E=="string"?E:JSON.stringify(E);r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:v,isError:false});}else h==="error"&&r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:String(f?.error||"tool error"),isError:true});continue}if(d==="error"){let c=Ro(i);r.push({timestamp:u,type:"error",content:c,errorMessage:c});continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?o_.has(r):!1}catch{return false}}};});var hu=b(()=>{g();});function Qr(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function m_(t,e){let n=[];for(let r=0;r<t.length;r+=1){let s=t[r],o=[...e].find(i=>s===i||s.startsWith(`${i}=`));o?s===o&&r+1<t.length&&(r+=1):n.push(s);}return n}function k_(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],s=r.indexOf("="),o=s>0?r.slice(0,s):r;if(!g_.has(o)){e.push(r);continue}r===o&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function $e(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function T_(t,e){if(!(t?__.has(t)||At(Ao).some(o=>o.id===t):false)||!t)return e;let r=Jn(Ao,t),s=Cd(Ao)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:s&&r.includes(s)?s:void 0:s}function _t(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function bo(t){return t.kind==="step_update"?typeof t.step.conversation_id=="string"?t.step.conversation_id:void 0:typeof t.envelope.conversation_id=="string"?t.envelope.conversation_id:void 0}function vo(t){return t.step.step_index}function ee(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Gr(e)?.slice(0,500).trim()||void 0}function y_(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&h_.has(n))return n;let r=`${n} ${e??""}`.toLowerCase();return /quota|resource_exhausted|usage[ _-]?limit|credits?.{0,20}exhaust/.test(r)?"QUOTA_EXHAUSTED":/rate[ _-]?limit|throttl/.test(r)?"RATE_LIMITED":/auth|sign[ _-]?in|log(?:ged)?[ _-]?in|unauthori[sz]ed|credential/.test(r)?"AUTH_REQUIRED":[/unknown (?:flag|option)/,/flag provided but not defined/,/unrecognized (?:flag|option)/,/invalid value for (?:flag|option)/,/invalid (?:flag|option)/].some(o=>o.test(r))?"INVALID_PROVIDER_FORMAT":/invalid.{0,24}model|model.{0,24}(unknown|unavailable|not found|not recognized)|config/.test(r)?"MODEL_UNAVAILABLE":"UNKNOWN"}function w_(t){return t==="AUTH_REQUIRED"||t==="TIMEOUT_IDLE"||t==="TIMEOUT_TOTAL"||t==="TIMEOUT_RESUME"||t==="PROVIDER_CRASHED"?"permanent":t==="MODEL_UNAVAILABLE"||t==="INVALID_PROVIDER_FORMAT"||t==="PROVIDER_NOT_FOUND"?"config":"transient"}function Tu(t){let e=$e(t)?t:void 0,n=e&&$e(e.error)?e.error:void 0,r=e?ee(e.code)??ee(e.error_code)??ee(n?.code)??ee(n?.error_code):void 0,s=typeof t=="string"?ee(t):e?ee(e.message)??ee(e.error)??ee(e.reason)??ee(n?.message)??ee(n?.error)??ee(n?.reason):void 0,o=y_(r,s),i=e?_t(e.retry_after_ms)??_t(e.retryAfterMs)??_t(n?.retry_after_ms)??_t(n?.retryAfterMs):void 0;return {code:o,kind:w_(o),message:s??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function es(t){let e=Tu(t);return new j(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function xo(t){return new j(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function E_(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=No))throw new j(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${No} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function Oo(){return new j("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"})}function ts(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function ns(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n&&(n.kind==="result"||n.kind==="legacy_result"||n.kind==="agy_error"))return {event:n,index:e}}}function R_(t){let e=ns(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||ts(e.event)?.status!=="SUCCESS"||Zr(t))return false;let r=new Map;for(let s of t){if(s.kind!=="step_update"||s.step.step_type!=="agent_response")continue;let o=bo(s),i=vo(s);!o||!Number.isSafeInteger(i)||r.set(JSON.stringify([o,i]),s.step);}if(r.size===0)return false;for(let s of r.values())if(s.state!=="DONE"||!$e(s.usage)||_t(s.usage.input_tokens)===void 0||_t(s.usage.output_tokens)===void 0)return false;return true}function S_(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function I_(t,e){return $e(t)&&$e(e)?{...e,...t}:$e(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&$e(e)?{...e,message:t}:t??e}function A_(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let o of e){let i=$e(o)?o:void 0,u=typeof o=="string"?ee(o):ee(i?.display_name)??ee(i?.action);u&&!n.includes(u)&&n.length<5&&n.push(u.slice(0,80));}let r=Math.max(0,e.length-n.length),s=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"";return new j(`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${s}.`,"cli/antigravity",{code:"UNKNOWN",kind:"permanent"})}function Zr(t){let e=ns(t);if(!e)return;if(e.event.kind==="agy_error")return es(e.event.error);let n=ts(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return A_(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return xo("Antigravity returned a result with an unsupported status.");let r=n.error,s=I_(r==null||r===""?n:r,S_(t,e.index));return es(s)}function yu(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function O_(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function N_(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function wu(t){let e=yu(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function b_(t){let e=$e(t)?t:void 0,n=e&&$e(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,s=(ee(e?.type)??ee(e?.code)??ee(e?.error_type)??ee(n?.type)??ee(n?.code)??ee(n?.error_type)??ee(r)??"TOOL_ERROR").slice(0,60),o=Tu(t).message.slice(0,250);return wu({type:s,message:o})??"Antigravity reported a tool error."}function mu(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function ku(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var Ao,__,g_,No,h_,Co,Do=b(()=>{g();Gt();hu();ao();zn();Kt();Vn();fo();Ao="antigravity",__=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),g_=new Set(["--conversation","--resume","--continue"]),No=18e4,h_=new Set(["QUOTA_EXHAUSTED","RATE_LIMITED","EMPTY_OUTPUT","AUTH_REQUIRED","MODEL_UNAVAILABLE","TIMEOUT_IDLE","TIMEOUT_TOTAL","TIMEOUT_RESUME","PROVIDER_NOT_FOUND","INVALID_PROVIDER_FORMAT","PROVIDER_CRASHED","UNKNOWN"]);Co={command:"agy",maxInitialInputBytes:No,meta:{displayName:"Antigravity",models:Md(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=jn(t);if(e?.kind!=="init")return null;let n=e.envelope.conversation_id;return typeof n=="string"&&n.trim().length>0?n.trim():null},buildArgs(t,e,n){E_(t);let{model:r,effort:s}=Ot(e.model),o=ho(r),i=o.model,u=e.effort??s??o.effort,d=T_(i,u),c=e.additionalArgs??[],l=k_(m_(c,new Set(["--input-format","--output-format"]))),p=i&&!Qr(c,"--model")?["--model",i]:[],f=Qr(c,"--effort")?[]:Vd(d),h=Qr(c,"--mode")||Qr(c,"--dangerously-skip-permissions")?[]:Jd(e.mode),m=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...p,...f,...h,...m,...l],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
53
- `,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=Kn(t),n=ns(e)?.event,r=Zr(e);if(r)throw r;let s=n?ts(n):void 0;if(s){if(s.status!=="SUCCESS")throw xo("Antigravity returned a result with an unsupported status.");if(typeof s.response!="string")throw xo("Antigravity returned a successful result without a response string.");if(!s.response.trim())throw Oo();return s.response}if(e.length>0)throw Oo();let o=t.trim();if(!o)throw Oo();return o},extractPartialText(t){let e=Kn(t),n=ns(e)?.event;if(!n||n.kind==="agy_error")return;let r=ts(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=Kn(n??""),s=Zr(r);return s||(t!==0&&e.trim()?es(e):null)},parseResultMeta(t){let e=Kn(t),n=0,r=0,s=0,o=0,i=new Set;for(let d of e){if(d.kind!=="step_update"||d.step.state!=="DONE"||!$e(d.step.usage))continue;let c=bo(d),l=vo(d);if(!c||!Number.isSafeInteger(l))continue;let p=JSON.stringify([c,l]);if(i.has(p))continue;let f=d.step.usage,h=_t(f.input_tokens),m=_t(f.output_tokens);h===void 0||m===void 0||(i.add(p),n+=h,r+=m,s+=_t(f.cache_read_tokens)??0,o+=1);}return {usage:o===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:s,costUsd:0,complete:R_(e)},model:null}},parseEvent(t,e,n){let r=jn(t);if(!r)return [];let s=e??new Date().toISOString();if(r.kind==="agy_error")return [ku(s,es(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let h=Zr([r]);return h?[ku(s,h)]:[]}if(r.kind!=="step_update")return [];let{step:o}=r,i=bo(r)??"unknown",u=vo(r),d=`${i}:${u}`;if((o.state==="DONE"||o.state==="ERROR")&&mu(n,`antigravity:terminal:${d}`))return [];if(o.step_type==="agent_response")return typeof o.text_delta=="string"&&o.text_delta.length>0?[{timestamp:s,type:"text",content:o.text_delta}]:[];if(o.step_type!=="tool")return [];let c=$e(o.tool_info)?o.tool_info:void 0,l=N_(o,c);if(!l)return [];let p=O_(o);if(o.state==="ACTIVE"){if(mu(n,`antigravity:active:${d}`))return [];let h=yu(c?.parameters);return [{timestamp:s,type:"tool_use",toolName:l,toolUseId:p,...h===void 0?{}:{toolInput:h}}]}let f=o.state==="ERROR"?b_(c?.error):wu(c?.output);return [{timestamp:s,type:"tool_result",toolName:l,toolUseId:p,...f===void 0?{}:{resultPreview:f},...o.state==="ERROR"?{isError:true}:{}}]}};});var Eu=b(()=>{g();fn();gn();_n();zt();});function kn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Tn(t){return kn(t)?t:void 0}function Ae(t){return typeof t=="string"?t:void 0}function Qt(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function P_(t){let e=[],n=-1,r=0,s=false,o=false;for(let i=0;i<t.length;i+=1){let u=t[i];if(n===-1){(u==="{"||u==="[")&&(n=i,r=1);continue}if(o){o=false;continue}if(u==="\\"&&s){o=true;continue}if(u==='"'){s=!s;continue}s||(u==="{"||u==="["?r+=1:(u==="}"||u==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function Yn(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return kn(n)?[n]:[]}catch{return P_(e).flatMap(n=>{try{let r=JSON.parse(n);return kn(r)?[r]:[]}catch{return []}})}}function Ou(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Yt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Yt).filter(n=>n!==void 0);return e.length>0?e.join(`
54
- `):void 0}if(kn(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=Yt(t[e]);if(n!==void 0)return n}}}function L_(t){let e=i=>Array.isArray(i)&&i.every(u=>Number.isInteger(u)&&u>=0&&u<=255),n=i=>typeof i=="string"&&i.trim().length>0?i:void 0,r=i=>new TextDecoder("utf-8",{fatal:false}).decode(Uint8Array.from(i)),s=i=>{let u=JSON.stringify(i,(d,c)=>e(c)?`<bytes:${c.length}>`:c);return u===void 0?String(i):u},o=t.rawOutput;if(o!=null){let i=Tn(o);if(!i)return n(Yt(o))??s(o);let u;if(e(i.output)&&i.output.length>0&&(u=n(r(i.output))),!u&&e(i.stdout)&&i.stdout.length>0&&(u=n(r(i.stdout))),!u){let l=Tn(i.Result);u=n(i.output)??n(l?.output)??n(Yt(o));}let d=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(d!==void 0)if(u){let l=u.endsWith(`
47
+ `):""}function __(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function pu(t){return t.replace(/\s+/g," ").trim()}function g_(t,e){let n=t?.description;if(typeof n!="string")return;let r=pu(n);if(!r||r===pu(e))return;if(r.length<=lu)return r;let s=r.slice(0,lu-1);return /[\uD800-\uDBFF]$/.test(s)&&(s=s.slice(0,-1)),`${s}\u2026`}function h_(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),s=e.id,o=e.input,i=Je(o);if(r==="Bash"&&lt(i))return pt(t,i,s);let u=g_(o,i);return {timestamp:t,type:"tool_use",toolUseId:s,toolName:r,toolInput:i,...u?{toolTitle:u}:{}}}if(n==="tool_result"){let r=!!e.is_error,s=e.tool_use_id,o=e.output??e.content??"",i;return typeof o=="string"?i=o:Array.isArray(o)?i=o.filter(u=>u.type==="text"&&typeof u.text=="string").map(u=>u.text).join(`
48
+ `):i=JSON.stringify(o),{timestamp:t,type:"tool_result",toolUseId:s,...ze(i,r)}}return null}var d_,u_,es,lu,So=N(()=>{g();fo();bt();_o();fn();_n();gn();hn();Xn();Vt();Yn();Xt();iu();d_=new Set(["tool_progress"]),u_="cli/claude";es={command:"claude",meta:{displayName:"Claude",models:Bd(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=xt(e.model),o=e.effort??s,i=Yd(e.mode),u=Qd(o),d=r?["--model",r]:[],c=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let p=[...e.additionalArgs];return p.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...c,...i,...u,...d,...p],stdinMessage:t,env:Zr}:{args:["--output-format","stream-json","--verbose",...c,...i,...u,...d,...p],stdinMessage:t,env:Zr}}return {args:["-p","--output-format","stream-json","--verbose",...c,...i,...u,...d],stdinMessage:t,env:Zr}},extractText(t){let e=du(t);if(e?.is_error===true){let s=es.extractFailure(JSON.stringify(e));if(s)throw s;let o=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new U(cu(e)??`Claude ended without an answer (subtype=${o}, terminal_reason=${i})`,u_,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=au(t);if(n)return n;let r=t.trim();return ct(r,"claude")?"":r},extractPartialText(t){return au(t)},extractFailure(t){try{let e=JSON.parse(t),n=fu(e);if(n)return new Jt(n)}catch{}return null},interpretExit(t,e,n){let r=c_(n??"");if(r)return new U(`Claude is not logged in (exit ${t}): ${r}. Sign in to this account with the official "claude auth login".`,"cli/claude",{code:"AUTH_REQUIRED",kind:"config"});let s=cu(du(n??""));return s?new U(s,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return l_(e)}catch{return}},parseResultMeta(t){let e=t.split(`
49
+ `);for(let r of e)if(r.trim())try{let s=JSON.parse(r);if(s.type==="result"){let o=s.usage,i=o?{inputTokens:Number(o.input_tokens??0)+Number(o.cache_read_input_tokens??0),outputTokens:Number(o.output_tokens??0),cachedInputTokens:Number(o.cache_read_input_tokens??0),costUsd:Number(s.total_cost_usd??0)}:null,u=s.modelUsage,d=u?Object.keys(u)[0]??null:null;return {usage:i,model:d}}}catch{}let n=ou(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 s=Ve(n,e??new Date().toISOString()),o=p_(n);if(o)return [{timestamp:s,type:"error",content:o,errorMessage:o}];let i=n.output_file,u=n.summary;if(r==="system"&&n.subtype==="task_notification"&&n.status==="completed"&&typeof i=="string"&&i.trim().length>0&&typeof u=="string"&&u.trim().length>0)return [{timestamp:s,type:"text",content:u}];if(r!=="assistant"&&r!=="user")return [];let c=n.message?.content;if(!Array.isArray(c))return [];let l=[];for(let p of c){let f=h_(s,p);f&&l.push(f);}return l},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?d_.has(r):!1}catch{return false}}};lu=200;});function _u(t){let e=t.split(`
50
+ `).filter(s=>s.trim()),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="assistant.message"&&typeof o.data?.content=="string"){let i=o.data.content;i.trim()&&n.push(i.trim());}o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var m_,Io,Ao=N(()=>{g();fn();Yn();_n();hn();gn();Vt();Xr();Xt();m_=new Set(["interactive","plan","autopilot"]);Io={command:"copilot",meta:{displayName:"Copilot",models:Gd()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&m_.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Vr.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=_u(t);if(e)return e;let n=t.trim();return ct(n,"copilot")?"":n},extractPartialText(t){return _u(t)},parseResultMeta(t){let e=mn(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 s=n.data;if(!s)return [];let o=Ve(n,e??new Date().toISOString()),i=s.toolCallId;if(r==="tool.execution_start"){let u=String(s.toolName||""),d=s.arguments,c=Je(d);return (u==="bash"||u==="Bash")&&lt(c)?[pt(o,c,i)]:[{timestamp:o,type:"tool_use",toolName:u,toolInput:c,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let u=s.error;if(u)return [{timestamp:o,type:"tool_result",...i&&{toolUseId:i},...ze(String(u.message||""),true)}];let d=s.result,c=String(d?.content||"");return [{timestamp:o,type:"tool_result",...i&&{toolUseId:i},...ze(c,false)}]}if(r==="assistant.message"){let u=String(s.content||"");return u?[{timestamp:o,type:"text",content:u}]:[]}return []}};});function y_(t){let e=[],n=0,r=false,s=false,o=0;for(let u=0;u<t.length;u++){let d=t[u];if(s){s=false;continue}if(d==="\\"&&r){s=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let c=t.slice(o,u+1).trim();c&&e.push(c),o=u+1;}}}let i=t.slice(o).trim();return i&&e.push(i),e}function w_(t){return t[0]==="exec"?t.slice(1):t}function gu(t){let e=t.split(`
51
+ `).map(s=>s.trim()).filter(Boolean),n=[],r=null;for(let s of e)try{let o=JSON.parse(s);if(o.type==="item.completed"&&(o.item?.type==="message"||o.item?.type==="agent_message")&&typeof o.item?.text=="string"){let i=o.item.text;i.trim()&&n.push(i.trim());}o.type==="result"&&typeof o.result=="string"&&(r=o.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Ct(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function mu(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Ct(t.error)}function ku(t){let e=Ct(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 E_(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Ct(n)&&mu(n))return ku(n)}}function hu(t,e,n,r){if(!n||t.type!=="command_execution"&&t.type!=="mcp_tool_call"||typeof t.id!="string"||!t.id.trim()||t.type==="mcp_tool_call"&&e==="item.started"&&(typeof t.server!="string"||typeof t.tool!="string"))return;let s=n.state.get("codex.pending");s||(s=new Map,n.state.set("codex.pending",s));let o=JSON.stringify([t.type,t.id]);if(e==="item.started"){let d=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,c=s.get(o)??[];return c.push(d),s.set(o,c),d}let i=s.get(o),u=i?.pop();return i?.length||s.delete(o),u}function R_(t,e,n){let r=e.type;if(r==="command_execution"){let s=String(e.command||"");return lt(s)?[pt(t,s,n)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:s,...n?{toolUseId:n}:{}}]}return r==="mcp_tool_call"?typeof e.server!="string"||typeof e.tool!="string"?[]:[{timestamp:t,type:"tool_use",toolName:`${e.server}/${e.tool}`,toolInput:Je(e.arguments),...n?{toolUseId:n}:{}}]:[]}function S_(t,e,n){let r=e.type;if(r==="message"||r==="text"){let s=e.content;if(Array.isArray(s))for(let o of s){let i=I_(t,o);if(i)return i}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(r==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(r==="reasoning"){let s=typeof e.text=="string"?e.text.trim():"";return s?{timestamp:t,type:"thinking",content:s}:null}if(r==="command_execution"){let s=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:t,type:"tool_result",...ze(s,o),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let s=Ct(e.result)?e.result:void 0,i=(Array.isArray(s?.content)?s.content:[]).filter(d=>Ct(d)&&d.type==="text"&&typeof d.text=="string").map(d=>d.text).join(`
52
+ `),u=typeof e.error=="string"?e.error:Ct(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||u,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let s=String(e.name||e.tool_name||""),o=e.input,i=Je(o);return s==="Bash"&&lt(i)?pt(t,i):{timestamp:t,type:"tool_use",toolName:s,toolInput:i}}if(r==="tool_result"){let s=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...ze(o,s)}}if(r==="web_search"){let s=e.action,o;if(s?.type==="search"){let i=s.queries;o=String(s.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else o=e.query?"open: "+String(e.query):"";return !o&&!(Ct(s)&&s.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:o}}if(r==="file_change"){let s=e.changes;if(!Array.isArray(s)||s.length===0)return null;let o=s.map(u=>String(u.path||"")).filter(Boolean);if(o.length===0)return null;let i=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:i}}return null}function I_(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||""),s=e.input,o=Je(s);return r==="Bash"&&lt(o)?pt(t,o):{timestamp:t,type:"tool_use",toolName:r,toolInput:o}}return null}var k_,T_,Oo,No=N(()=>{g();bt();fn();Yn();_n();hn();mo();gn();Xn();Vt();Xt();k_=new Set(["turn.started","turn.completed","item.updated"]),T_="cli/codex";Oo={command:"codex",meta:{displayName:"Codex",models:Wd(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:s}=xt(e.model),o=e.effort??s,i=e.resumeSessionId?Vd(e.mode):Jd(e.mode),u=Xd(o),d=r?["-m",r]:[],c=w_(e.additionalArgs??[]),p=c.includes("--json")||c.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...p,...i,...u,...d,...c,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...p,...i,...u,...d,...c],stdinMessage:t}},extractText(t){let e=E_(t);if(e)throw new U(e,T_);let n=gu(t);if(n)return n;let r=t.trim();return ct(r,"codex")?"":r},extractPartialText(t){return gu(t)},parseResultMeta(t){let e=mn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e,n){let r=e??new Date().toISOString(),s=[],o;try{JSON.parse(t),o=[t];}catch{o=y_(t),o.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,u]of o.entries()){let d;try{d=JSON.parse(u);}catch{continue}if(!Ct(d))continue;let c=d.type;if(!c)continue;let l=Ve(d,r);if(mu(d)){let f=ku(d);s.push({timestamp:l,type:"error",content:f,errorMessage:f});continue}if(!c.startsWith("item.")&&!c.startsWith("turn.")&&!c.startsWith("thread.")||ho(d))continue;c==="thread.started"&&n&&n.state.delete("codex.pending");let p=d.item;if(p){if(c==="item.started"){s.push(...R_(l,p,hu(p,c,n,i)));continue}if(c==="item.completed"){let f=S_(l,p,hu(p,c,n,i));f&&s.push(f);continue}}}return s},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?k_.has(r):!1}catch{return false}}};});function Ue(t,e=240){if(typeof t!="string")return;let n=t.split(/\r?\n/).map(r=>r.trim()).find(r=>r&&!/^at\s+/.test(r));if(n)return n.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").replace(/(^|[\s"'(=])((?:[A-Za-z]:[\\/]|\/)(?:[^\s"'`()\[\]{}]+[\\/])*[^\s"'`()\[\]{}]+)/g,"$1[path]").slice(0,e).trim()}function Qn(t){let e=Ue(t);if(e)return Ue(e.replace(/^Upstream request failed:\s*/i,""),200)}var Tu=N(()=>{g();});function O_(t,e){let n={};for(let[r,s]of Object.entries(t))s!==void 0&&(e.includes(r)||(n[r]=s));return n}function yu(t){return O_(t,A_)}var A_,wu=N(()=>{g();A_=["CREWX_ASSIGNED_TASK_ID","CREWX_DETACHED_RUNNER"];});function ts(){if(process.env.CREWX_HOME){let t=me__namespace.resolve(process.env.CREWX_HOME);try{return Ru__namespace.realpathSync(t)}catch(e){if(e instanceof Error&&"code"in e&&e.code==="ENOENT")return t;throw e}}return process.platform!=="win32"&&process.env.XDG_CONFIG_HOME?me__namespace.join(process.env.XDG_CONFIG_HOME,"crewx"):me__namespace.join(ea__namespace.homedir(),".crewx")}var Su=N(()=>{g();});function rs(t=ts()){let e=me.join(t,"opencode-xdg");return {XDG_DATA_HOME:me.join(e,"data"),XDG_STATE_HOME:me.join(e,"state")}}function x_(t=ts()){return me.join(rs(t).XDG_DATA_HOME,"opencode")}async function C_(){return (await import('better-sqlite3')).default}function D_(t){return me.join(t,"opencode.db")}function P_(t){let e=t??process.env.XDG_DATA_HOME??me.join(ea.homedir(),".local","share");return me.join(me.resolve(e),"opencode","opencode.db")}function Au(t,e){return !!t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)}function L_(t){let e;try{e=typeof t=="string"?JSON.parse(t):t;}catch{return false}if(!e||typeof e!="object"||Array.isArray(e))return false;let n=e;return n.type==="key"&&typeof n.key=="string"&&!("refresh"in n)&&!("refresh_token"in n)&&!("expires"in n)&&!("expires_at"in n)&&!("expires_in"in n)}function M_(t,e){if(!Ru.existsSync(e))return [];let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),Au(n,"credential")?n.prepare(`
53
+ SELECT id, integration_id, label, value, connector_id, method_id, active, time_created, time_updated
54
+ FROM credential
55
+ `).all().filter(s=>s.integration_id!==null&&L_(s.value)):[]}catch{return []}finally{n?.close();}}function Iu(t,e){if(!Ru.existsSync(e))return false;let n;try{return n=new t(e,{readonly:!0,fileMustExist:!0}),Au(n,"credential")}catch{return false}finally{n?.close();}}function $_(t){return new Promise((e,n)=>{child_process.execFile("opencode",["auth","list","--standalone"],{timeout:15e3,maxBuffer:1024*1024,encoding:"utf8",env:{...yu(process.env),...t}},r=>{r?n(r):e();});})}function H_(t,e,n){let r=new t(e,{fileMustExist:true});try{let s=r.prepare(`
56
+ INSERT INTO credential (
57
+ id, integration_id, label, value, connector_id, method_id, active, time_created, time_updated
58
+ ) VALUES (
59
+ @id, @integration_id, @label, @value, @connector_id, @method_id, @active, @time_created, @time_updated
60
+ )
61
+ ON CONFLICT(id) DO UPDATE SET
62
+ integration_id = excluded.integration_id,
63
+ label = excluded.label,
64
+ value = excluded.value,
65
+ connector_id = excluded.connector_id,
66
+ method_id = excluded.method_id,
67
+ active = excluded.active,
68
+ time_created = excluded.time_created,
69
+ time_updated = excluded.time_updated
70
+ `);r.transaction(i=>{for(let u of i)s.run(u);})(n);}finally{r.close();}}function U_(t){if(!t)return [];let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="-s"||r==="--session"){let s=t[n+1],o=s!==void 0&&!s.startsWith("-");e.push({sessionId:o?s:void 0}),o&&(n+=1);continue}(r.startsWith("--session=")||r.startsWith("-s="))&&e.push({sessionId:r.slice(r.indexOf("=")+1)||void 0});}return e}function q_(t){if(!t)return;let e=[];for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="-s"||r==="--session"){t[n+1]!==void 0&&!t[n+1].startsWith("-")&&(n+=1);continue}r.startsWith("--session=")||r.startsWith("-s=")||e.push(r);}return e}function ns(t){let e=q_(t.additionalArgs);return {...t,...e===void 0?{}:{additionalArgs:e},resumeSessionId:void 0}}function F_(t,e){try{return !!t.prepare("SELECT id FROM session_v2 WHERE id = ?").get(e)}catch(n){if(n instanceof Error&&/no such table: session_v2/i.test(n.message))return false;throw n}}function B_(t,e,n){let r=new t(e,{readonly:true,fileMustExist:true});try{return F_(r,n)}finally{r.close();}}async function Ou(t,e={}){let n;try{n=await(e.loadSqlite??C_)();}catch{throw new U("OpenCode isolation requires the optional better-sqlite3 dependency. Install it and retry.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}let r=e.crewxHome??ts(),s=rs(r),o=x_(r),i=D_(o),u=P_(e.userDataHome),d=M_(n,u);if(d.length>0){if(!Iu(n,i))try{await(e.initializeDatabase??$_)(s);}catch{throw new U("Could not initialize the isolated OpenCode credential database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}if(!Iu(n,i))throw new U("The isolated OpenCode credential database is unavailable.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"});try{H_(n,i,d);}catch{throw new U("Could not copy API-key credentials into the isolated OpenCode database.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}let c=U_(t.additionalArgs),l=c.map(f=>f.sessionId),p=c.length>0?l[l.length-1]:t.resumeSessionId;if(!p)return c.length>0?ns(t):t;if(l.some(f=>f!==p)||!Ru.existsSync(i))return ns(t);try{return B_(n,i,p)?{...t,resumeSessionId:p}:ns(t)}catch{throw new U("Could not read the isolated OpenCode session database safely.","cli/opencode",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}}var Nu=N(()=>{g();bt();wu();Su();});function z_(t){return t?K_[t]??{agent:"build",autoApprove:false}:{agent:void 0,autoApprove:false}}function ht(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Du(t){let e=[],n=0,r=false,s=false,o=0;for(let u=0;u<t.length;u++){let d=t[u];if(s){s=false;continue}if(d==="\\"&&r){s=true;continue}if(d==='"'){r=!r;continue}if(!r){if(d==="{")n++;else if(d==="}"&&(n--,n===0)){let c=t.slice(o,u+1).trim();c&&e.push(c),o=u+1;}}}let i=t.slice(o).trim();return i&&e.push(i),e}function de(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function J_(t){let e=[],n=false;for(let r of t.split(/\r?\n/)){let s=r.trim();if(!s)continue;try{let i=JSON.parse(s);de(i)?e.push(i):n=!0;continue}catch{}let o=Du(s);o.length>1&&console.warn("[opencode] extractText: falling back to concatenated-JSON split for a malformed line");for(let i of o)try{let u=JSON.parse(i);de(u)?e.push(u):n=!0;}catch{n=true;}}return {events:e,malformed:n}}function Co(t){let e=de(t.error)?t.error:void 0,n=e&&de(e.data)?e.data:void 0,r=Pu(e),s=Ue(e?.name),o=Ue(n?.message)??Ue(e?.message)??vo(r)??Ue(t.message)??Ue(t.errorMessage)??Ue(t.error),i=Ue(t.ref),u=s&&o&&s!==o?`${s}: ${o}`:s??o??Cu;return (i?`${u} (ref: ${i})`:u).slice(0,G_)}function bu(t){let e=de(t.error)?t.error:void 0,n=typeof e?.type=="string"?e.type:void 0,r=typeof e?.status=="number"?e.status:Number(e?.status),s=Co(t),o=Pu(e),i=o&&de(o.error)?o.error:void 0,u=typeof i?.type=="string"?i.type:void 0,d=[s,vo(o)].filter(Boolean).join(`
71
+ `);if(r===402||V_(d))return new U(`OpenCode subscription is required: ${s}`,Ce,{code:"SUBSCRIPTION_REQUIRED",kind:"config",providerReason:Qn(s)});if(r===403&&(u==="RegionError"||u==="FreeTierError"))return new U(`OpenCode account settings are required: ${s}`,Ce,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:"access",providerReason:Qn(s)});if(n==="provider.auth"||r===401||r===403)return new U(`OpenCode authentication is required: ${s}`,Ce,{code:"AUTH_REQUIRED",kind:"config"});if(r===410||u==="ModelDeprecated")return new U(`OpenCode model has been retired: ${s}`,Ce,{code:"MODEL_RETIRED",kind:"config",replacementModel:X_(o,e,t),providerReason:Qn(s)});if(n==="provider.free-limit"||r===429){let c=Y_(e);return new U(`OpenCode rate limit reached: ${s}`,Ce,{code:"RATE_LIMITED",kind:"transient",...c===void 0?{}:{retryAfterMs:c}})}if(n==="provider.no-route")return new U(`OpenCode model or variant unavailable: ${s}`,Ce,{code:"MODEL_UNAVAILABLE",kind:"config"});if(n==="provider.invalid-request"&&r===400){let c=[s,vo(o)].filter(h=>h!==void 0),l=c.find(h=>/requires global regions/i.test(h)),p=c.find(h=>/trains on request data/i.test(h)),f=l?"region":p?"training_consent":void 0;if(f)return new U(`OpenCode account settings are required: ${s}`,Ce,{code:"ACCOUNT_SETTING_REQUIRED",kind:"config",settingReason:f,providerReason:Qn(l??p)})}return new U(`OpenCode error: ${s}`,Ce,{code:"PROVIDER_CRASHED",kind:"transient"})}function Pu(t){let n=(t&&de(t.response)?t.response:void 0)?.body;if(de(n))return n;if(typeof n=="string")try{let r=JSON.parse(n);return de(r)?r:void 0}catch{return}}function vo(t){let e=t&&de(t.error)?t.error:void 0;return Ue(e?.message)??Ue(t?.message)}function V_(t){return /insufficient\s+(?:balance|account funds)|credit\s+limit\s+exceeded|payment\s+required|account invoice is overdue|billing_error|please add or update your payment method|(?:GLM Coding Plan|enterprise) package has expired|your current subscription plan does not yet include access to/i.test(t)}function X_(t,e,n){let r=t&&de(t.metadata)?t.metadata:void 0,s=typeof r?.replacement=="string"?r.replacement.trim():void 0;if(!s)return;let o=[r?.model,e?.model,n.model,n.modelID].find(d=>typeof d=="string"&&d.trim().length>0)?.trim(),i=o&&o.includes("/")?o.slice(0,o.indexOf("/")):"opencode-go",u=s.includes("/")?s:`${i}/${s}`;return /^[A-Za-z0-9._/-]{1,128}$/.test(u)?u:void 0}function Y_(t){let e=t?.retryAfterMs;if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return e;let r=(t&&de(t.response)?t.response:void 0)?.body,s=typeof r=="string"?Q_(r):de(r)?r:void 0;if(s){let o=xo(s);if(o)return vu(o.value,o.key==="retryafterms")}if(typeof r=="string"){let o=r.match(/retry[-_]after(?:\s*[:=]\s*|\s+)["']?([^"'\s,;}]+)/i);if(o?.[1])return vu(o[1],false)}}function Q_(t){try{let e=JSON.parse(t);return de(e)?e:void 0}catch{return}}function xo(t){if(Array.isArray(t)){for(let e of t){let n=xo(e);if(n)return n}return}if(de(t)){for(let[e,n]of Object.entries(t)){let r=e.toLowerCase().replace(/[-_]/g,"");if(r==="retryafterms"||r==="retryafter")return {value:n,key:r}}for(let e of Object.values(t)){let n=xo(e);if(n)return n}}}function vu(t,e){if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return e?t:Math.round(t*1e3);if(typeof t!="string"||!t.trim())return;let n=Number(t);if(Number.isFinite(n)&&n>=0)return e?n:Math.round(n*1e3);if(e)return;let r=Date.parse(t);return Number.isFinite(r)?Math.max(0,r-Date.now()):void 0}function xu(t){let e=J_(t),n=[],r=null,s=0,o=[],i=[],u,d=false;for(let c of e.events){let l=typeof c.type=="string"?c.type:void 0;if(l){if(l==="text"){let p=de(c.part)?c.part:void 0,f=typeof p?.text=="string"?p.text:void 0;f?.trim()&&n.push(f.trim());continue}if(l==="result"){typeof c.result=="string"&&(r=c.result);continue}if(l==="tool_use"){s++;continue}if(l==="error"){o.push(c),i.push(Co(c));continue}if(l==="step_finish"){d=true;let p=de(c.part)?c.part:void 0;u=typeof p?.reason=="string"?p.reason:void 0;}}}return {...e,texts:n,resultText:r,toolUseCount:s,errorEvents:o,errorMessages:i,terminalReason:u,hasTerminal:d}}function Lu(t){return (t??"unknown").trim().toLowerCase().replace(/_/g,"-")}function Z_(){return new U("OpenCode returned no assistant output.",Ce,{code:"EMPTY_OUTPUT",kind:"transient"})}function eg(){return new U("OpenCode emitted malformed JSON output.",Ce,{code:"PROVIDER_CRASHED",kind:"transient"})}function tg(t,e){switch(Lu(t)){case "length":return new U("OpenCode stopped because the context window was exceeded.",Ce,{code:"UNKNOWN",kind:"permanent"});case "content-filter":return new U("OpenCode stopped because the content filter blocked the response.",Ce,{code:"UNKNOWN",kind:"permanent"});case "error":return new U(`${Cu} while generating a response.`,Ce,{code:"PROVIDER_CRASHED",kind:"transient"});default:return null}}var W_,Ce,Cu,G_,j_,K_,Do,Po=N(()=>{g();bt();Tu();Yn();hn();Xt();Nu();W_=new Set(["step_start","step_finish"]),Ce="cli/opencode",Cu="OpenCode provider error",G_=240,j_="Follow the instructions provided on standard input.",K_={build:{agent:"build",autoApprove:false},"build-auto":{agent:"build",autoApprove:true},plan:{agent:"plan",autoApprove:false},"plan-auto":{agent:"plan",autoApprove:true}};Do={command:"opencode",prepare:Ou,meta:{displayName:"OpenCode",capabilities:{resume:true}},buildArgs(t,e,n){let r=e.additionalArgs,s=r!==void 0?[...r]:["run"];ht(s,"--format")||s.push("--format","json"),!ht(s,"--standalone")&&!ht(s,"--server")&&s.push("--standalone"),e.resumeSessionId&&!ht(s,"-s")&&!ht(s,"--session")&&s.push("-s",e.resumeSessionId);let{agent:o,autoApprove:i}=z_(e.mode);ht(s,"--agent")||o!==void 0&&s.push("--agent",o),i&&!ht(s,"--auto")&&s.push("--auto");let u=ht(s,"--model")||ht(s,"-m");if(e.model&&!u){let d=e.effort?`${e.model}#${e.effort}`:e.model;s.push("--model",d);}else e.effort&&!e.model&&!u&&console.debug("[opencode] ignoring effort because no model is configured");return s.push(j_),{args:s,stdinMessage:t,env:rs()}},extractText(t){let e=xu(t),n=e.errorEvents[0];if(n)throw bu(n);let r=tg(e.terminalReason??"");if(r)throw r;let s=e.texts.length>0?e.texts[e.texts.length-1]:void 0;if(s!==void 0)return s;if(e.resultText?.trim())return e.resultText;if(e.malformed)throw eg();let o=Lu(e.terminalReason);if(e.hasTerminal&&o==="tool-calls"&&e.toolUseCount>0)return "";throw Z_()},interpretExit(t,e,n=""){if(t===0)return null;let s=xu(n).errorEvents[0];return s?bu(s):null},parseResultMeta(t){let e=mn(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=[],s;try{JSON.parse(t),s=[t];}catch{s=Du(t),s.length>1&&console.warn("[opencode] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let o of s){let i;try{i=JSON.parse(o);}catch{continue}let u=Ve(i,n),d=i.type;if(d){if(d==="text"){let l=i.part?.text;l&&r.push({timestamp:u,type:"text",content:l});continue}if(d==="tool_use"){let c=i.part;if(!c)continue;let l=String(c.tool||""),p=String(c.callID||c.id||""),f=c.state,h=String(f?.status||""),m=f?.input,k=Je(m);if(r.push({timestamp:u,type:"tool_use",toolName:l,toolUseId:p,toolInput:k}),h==="completed"&&f?.output!==void 0){let E=f.output,v=typeof E=="string"?E:JSON.stringify(E);r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:v,isError:false});}else h==="error"&&r.push({timestamp:u,type:"tool_result",toolUseId:p,resultPreview:String(f?.error||"tool error"),isError:true});continue}if(d==="error"){let c=Co(i);r.push({timestamp:u,type:"error",content:c,errorMessage:c});continue}}}return r},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?W_.has(r):!1}catch{return false}}};});var Mu=N(()=>{g();});function ss(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function ig(t,e){let n=[];for(let r=0;r<t.length;r+=1){let s=t[r],o=[...e].find(i=>s===i||s.startsWith(`${i}=`));o?s===o&&r+1<t.length&&(r+=1):n.push(s);}return n}function ag(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],s=r.indexOf("="),o=s>0?r.slice(0,s):r;if(!sg.has(o)){e.push(r);continue}r===o&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function dg(t,e){if(!(t?rg.has(t)||vt(Lo).some(o=>o.id===t):false)||!t)return e;let r=Vn(Lo,t),s=Fd(Lo)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:s&&r.includes(s)?s:void 0:s}function mt(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function Ho(t){return t.kind==="step_update"?typeof t.step.conversation_id=="string"?t.step.conversation_id:void 0:typeof t.envelope.conversation_id=="string"?t.envelope.conversation_id:void 0}function Uo(t){return t.step.step_index}function ee(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&zr(e)?.slice(0,500).trim()||void 0}function ug(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&og.has(n))return n;let r=`${n} ${e??""}`.toLowerCase();return /quota|resource_exhausted|usage[ _-]?limit|credits?.{0,20}exhaust/.test(r)?"QUOTA_EXHAUSTED":/rate[ _-]?limit|throttl/.test(r)?"RATE_LIMITED":/auth|sign[ _-]?in|log(?:ged)?[ _-]?in|unauthori[sz]ed|credential/.test(r)?"AUTH_REQUIRED":[/unknown (?:flag|option)/,/flag provided but not defined/,/unrecognized (?:flag|option)/,/invalid value for (?:flag|option)/,/invalid (?:flag|option)/].some(o=>o.test(r))?"INVALID_PROVIDER_FORMAT":/invalid.{0,24}model|model.{0,24}(unknown|unavailable|not found|not recognized)|config/.test(r)?"MODEL_UNAVAILABLE":"UNKNOWN"}function cg(t){return t==="AUTH_REQUIRED"||t==="TIMEOUT_IDLE"||t==="TIMEOUT_TOTAL"||t==="TIMEOUT_RESUME"||t==="PROVIDER_CRASHED"?"permanent":t==="MODEL_UNAVAILABLE"||t==="INVALID_PROVIDER_FORMAT"||t==="PROVIDER_NOT_FOUND"?"config":"transient"}function Uu(t){let e=qe(t)?t:void 0,n=e&&qe(e.error)?e.error:void 0,r=e?ee(e.code)??ee(e.error_code)??ee(n?.code)??ee(n?.error_code):void 0,s=typeof t=="string"?ee(t):e?ee(e.message)??ee(e.error)??ee(e.reason)??ee(n?.message)??ee(n?.error)??ee(n?.reason):void 0,o=ug(r,s),i=e?mt(e.retry_after_ms)??mt(e.retryAfterMs)??mt(n?.retry_after_ms)??mt(n?.retryAfterMs):void 0;return {code:o,kind:cg(o),message:s??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function is(t){let e=Uu(t);return new U(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function qo(t){return new U(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function lg(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=$o))throw new U(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${$o} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function Mo(){return new U("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"})}function as(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function ds(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n&&(n.kind==="result"||n.kind==="legacy_result"||n.kind==="agy_error"))return {event:n,index:e}}}function pg(t){let e=ds(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||as(e.event)?.status!=="SUCCESS"||os(t))return false;let r=new Map;for(let s of t){if(s.kind!=="step_update"||s.step.step_type!=="agent_response")continue;let o=Ho(s),i=Uo(s);!o||!Number.isSafeInteger(i)||r.set(JSON.stringify([o,i]),s.step);}if(r.size===0)return false;for(let s of r.values())if(s.state!=="DONE"||!qe(s.usage)||mt(s.usage.input_tokens)===void 0||mt(s.usage.output_tokens)===void 0)return false;return true}function fg(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function _g(t,e){return qe(t)&&qe(e)?{...e,...t}:qe(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&qe(e)?{...e,message:t}:t??e}function gg(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let o of e){let i=qe(o)?o:void 0,u=typeof o=="string"?ee(o):ee(i?.display_name)??ee(i?.action);u&&!n.includes(u)&&n.length<5&&n.push(u.slice(0,80));}let r=Math.max(0,e.length-n.length),s=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"";return new U(`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${s}.`,"cli/antigravity",{code:"UNKNOWN",kind:"permanent"})}function os(t){let e=ds(t);if(!e)return;if(e.event.kind==="agy_error")return is(e.event.error);let n=as(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return gg(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return qo("Antigravity returned a result with an unsupported status.");let r=n.error,s=_g(r==null||r===""?n:r,fg(t,e.index));return is(s)}function qu(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function hg(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function mg(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function Fu(t){let e=qu(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function kg(t){let e=qe(t)?t:void 0,n=e&&qe(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,s=(ee(e?.type)??ee(e?.code)??ee(e?.error_type)??ee(n?.type)??ee(n?.code)??ee(n?.error_type)??ee(r)??"TOOL_ERROR").slice(0,60),o=Uu(t).message.slice(0,250);return Fu({type:s,message:o})??"Antigravity reported a tool error."}function $u(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function Hu(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var Lo,rg,sg,$o,og,Fo,Bo=N(()=>{g();bt();Mu();_o();Jn();Vt();Xn();To();Lo="antigravity",rg=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),sg=new Set(["--conversation","--resume","--continue"]),$o=18e4,og=new Set(["QUOTA_EXHAUSTED","RATE_LIMITED","EMPTY_OUTPUT","AUTH_REQUIRED","MODEL_UNAVAILABLE","TIMEOUT_IDLE","TIMEOUT_TOTAL","TIMEOUT_RESUME","PROVIDER_NOT_FOUND","INVALID_PROVIDER_FORMAT","PROVIDER_CRASHED","UNKNOWN"]);Fo={command:"agy",maxInitialInputBytes:$o,meta:{displayName:"Antigravity",models:jd(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=Kn(t);if(e?.kind!=="init")return null;let n=e.envelope.conversation_id;return typeof n=="string"&&n.trim().length>0?n.trim():null},buildArgs(t,e,n){lg(t);let{model:r,effort:s}=xt(e.model),o=Eo(r),i=o.model,u=e.effort??s??o.effort,d=dg(i,u),c=e.additionalArgs??[],l=ag(ig(c,new Set(["--input-format","--output-format"]))),p=i&&!ss(c,"--model")?["--model",i]:[],f=ss(c,"--effort")?[]:su(d),h=ss(c,"--mode")||ss(c,"--dangerously-skip-permissions")?[]:ru(e.mode),m=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...p,...f,...h,...m,...l],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
72
+ `,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=zn(t),n=ds(e)?.event,r=os(e);if(r)throw r;let s=n?as(n):void 0;if(s){if(s.status!=="SUCCESS")throw qo("Antigravity returned a result with an unsupported status.");if(typeof s.response!="string")throw qo("Antigravity returned a successful result without a response string.");if(!s.response.trim())throw Mo();return s.response}if(e.length>0)throw Mo();let o=t.trim();if(!o)throw Mo();return o},extractPartialText(t){let e=zn(t),n=ds(e)?.event;if(!n||n.kind==="agy_error")return;let r=as(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=zn(n??""),s=os(r);return s||(t!==0&&e.trim()?is(e):null)},parseResultMeta(t){let e=zn(t),n=0,r=0,s=0,o=0,i=new Set;for(let d of e){if(d.kind!=="step_update"||d.step.state!=="DONE"||!qe(d.step.usage))continue;let c=Ho(d),l=Uo(d);if(!c||!Number.isSafeInteger(l))continue;let p=JSON.stringify([c,l]);if(i.has(p))continue;let f=d.step.usage,h=mt(f.input_tokens),m=mt(f.output_tokens);h===void 0||m===void 0||(i.add(p),n+=h,r+=m,s+=mt(f.cache_read_tokens)??0,o+=1);}return {usage:o===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:s,costUsd:0,complete:pg(e)},model:null}},parseEvent(t,e,n){let r=Kn(t);if(!r)return [];let s=e??new Date().toISOString();if(r.kind==="agy_error")return [Hu(s,is(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let h=os([r]);return h?[Hu(s,h)]:[]}if(r.kind!=="step_update")return [];let{step:o}=r,i=Ho(r)??"unknown",u=Uo(r),d=`${i}:${u}`;if((o.state==="DONE"||o.state==="ERROR")&&$u(n,`antigravity:terminal:${d}`))return [];if(o.step_type==="agent_response")return typeof o.text_delta=="string"&&o.text_delta.length>0?[{timestamp:s,type:"text",content:o.text_delta}]:[];if(o.step_type!=="tool")return [];let c=qe(o.tool_info)?o.tool_info:void 0,l=mg(o,c);if(!l)return [];let p=hg(o);if(o.state==="ACTIVE"){if($u(n,`antigravity:active:${d}`))return [];let h=qu(c?.parameters);return [{timestamp:s,type:"tool_use",toolName:l,toolUseId:p,...h===void 0?{}:{toolInput:h}}]}let f=o.state==="ERROR"?kg(c?.error):Fu(c?.output);return [{timestamp:s,type:"tool_result",toolName:l,toolUseId:p,...f===void 0?{}:{resultPreview:f},...o.state==="ERROR"?{isError:true}:{}}]}};});var Bu=N(()=>{g();_n();hn();gn();Xt();});function Tn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function yn(t){return Tn(t)?t:void 0}function Oe(t){return typeof t=="string"?t:void 0}function Zt(t){let e=typeof t=="number"?t:Number(t??0);return Number.isFinite(e)?e:0}function Rg(t){let e=[],n=-1,r=0,s=false,o=false;for(let i=0;i<t.length;i+=1){let u=t[i];if(n===-1){(u==="{"||u==="[")&&(n=i,r=1);continue}if(o){o=false;continue}if(u==="\\"&&s){o=true;continue}if(u==='"'){s=!s;continue}s||(u==="{"||u==="["?r+=1:(u==="}"||u==="]")&&(r-=1,r===0&&(e.push(t.slice(n,i+1)),n=-1)));}return n!==-1&&e.push(t.slice(n)),e}function er(t){let e=t.trim();if(!e)return [];try{let n=JSON.parse(e);return Tn(n)?[n]:[]}catch{return Rg(e).flatMap(n=>{try{let r=JSON.parse(n);return Tn(r)?[r]:[]}catch{return []}})}}function zu(t){let e=JSON.stringify(t);return e===void 0?String(t):e}function Qt(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.map(Qt).filter(n=>n!==void 0);return e.length>0?e.join(`
73
+ `):void 0}if(Tn(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=Qt(t[e]);if(n!==void 0)return n}}}function Sg(t){let e=i=>Array.isArray(i)&&i.every(u=>Number.isInteger(u)&&u>=0&&u<=255),n=i=>typeof i=="string"&&i.trim().length>0?i:void 0,r=i=>new TextDecoder("utf-8",{fatal:false}).decode(Uint8Array.from(i)),s=i=>{let u=JSON.stringify(i,(d,c)=>e(c)?`<bytes:${c.length}>`:c);return u===void 0?String(i):u},o=t.rawOutput;if(o!=null){let i=yn(o);if(!i)return n(Qt(o))??s(o);let u;if(e(i.output)&&i.output.length>0&&(u=n(r(i.output))),!u&&e(i.stdout)&&i.stdout.length>0&&(u=n(r(i.stdout))),!u){let l=yn(i.Result);u=n(i.output)??n(l?.output)??n(Qt(o));}let d=e(i.stderr)&&i.stderr.length>0?r(i.stderr):void 0;if(d!==void 0)if(u){let l=u.endsWith(`
55
74
  `)||u.endsWith("\r")?"":`
56
- `;u=`${u}${l}${d}`;}else u=n(d);if(u)return u;let c=n(i.summary)??n(Yt(t.content))??n(i.output_for_prompt);return c!==void 0?c:s(o)}if(t.content!==null&&t.content!==void 0)return Yt(t.content)??s(t.content);if(t.result!==null&&t.result!==void 0)return Yt(t.result)??s(t.result)}function Nu(t){let e=Tn(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?bu(n):"Grok CLI reported an error."}function bu(t){return (t.replace(D_,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Au(t){return C_.test(t)}function M_(t){let e=Tn(t.modelUsage);return e?Object.keys(e)[0]??null:null}function $_(t){let e=Tn(t.usage);if(!e)return null;let n=Qt(e.cache_read_input_tokens);return {inputTokens:Qt(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Qt(e.output_tokens),costUsd:Qt(t.total_cost_usd)}}function H_(t){let e=0,n=0,r=0,s=false,o=new Set;for(let i of t.split(`
57
- `).flatMap(Yn)){if(i.type!=="usage")continue;let u=Tn(i.usage);if(!u)continue;let d=Ae(i.signature);if(d&&d.length>0){let l=`signature:${d}`;if(o.has(l))continue;o.add(l);}let c=Qt(u.cache_read_input_tokens);e+=Qt(u.input_tokens)+c,n+=c,r+=Qt(u.output_tokens),s=true;}return s?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function U_(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let o of e.entries.slice(0,Ru)){if(!kn(o))continue;let i=Ae(o.content)?.trim();if(!i)continue;let u=Ae(o.status)?.trim(),d=Ae(o.priority)?.trim(),c=[u?`status=${u}`:void 0,d?`priority=${d}`:void 0].filter(p=>!!p),l=c.length>0?` (${c.join(", ")})`:"";n.push(`- ${i}${l}`);}if(n.length===0)return [];e.entries.length>Ru&&n.push(Iu);let r=n.join(`
58
- `),s=r.length>Su?`${r.slice(0,Su-1)}${Iu}`:r;return [{timestamp:t,type:"info",content:s}]}function q_(t,e){let n=Ae(e.type);if(n==="thought"){let r=Ae(e.data);return r===void 0?[]:[{timestamp:t,type:"thinking",content:r}]}if(n==="text"){let r=Ae(e.data);return r===void 0?[]:[{timestamp:t,type:"text",content:r}]}if(n==="plan")return U_(t,e);if(n==="tool_call"){let r=Ae(e.toolCallId),s=Ae(e.toolName)??Ae(e.title),o=e.rawInput===void 0?void 0:Ou(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:s,toolInput:o}]}if(n==="tool_call_update"){let r=Ae(e.status);if(r!=="completed"&&r!=="failed"&&r!=="error")return [];let s=L_(e),o=r!=="completed"||e.isError===true;return [{timestamp:t,type:"tool_result",toolUseId:Ae(e.toolCallId),toolName:Ae(e.toolName)??Ae(e.title),...s!==void 0?Ge(s,o):{isError:o}}]}if(n==="error"){let r=Nu(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}function F_(t){return process.platform==="win32"?{flags:["--single",t]}:{flags:["--prompt-file","/dev/stdin"],stdinMessage:t}}var rs,x_,C_,D_,Ru,Su,Iu,Po,Lo=b(()=>{g();Gt();io();Kt();_n();Vn();zt();rs="cli/grok",x_=new Set(["available_commands","usage","end"]),C_=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,D_=/\u001b\[[0-?]*[ -/]*[@-~]/g,Ru=20,Su=4e3,Iu="\u2026";Po={command:"grok",createSessionId:()=>crypto.randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=Ot(e.model),s=e.effort??r,o=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],u=n?At("grok").some(O=>O.id===n):false,d=n&&u?Jn("grok",n):[],c=!s||d.length===0||d.includes(s)?s:void 0,l=zd(c),p=e.additionalArgs??[],f=O=>p.some(S=>S===O||S.startsWith(`${O}=`)),h=e.providerOptions,m=h?.alwaysApprove,k=h?.sandbox,E=f("--permission-mode")?[]:Gd(e.mode),v=f("--always-approve")?[]:jd(m),w=f("--sandbox")?[]:Kd(k),x=f("--verbatim")?[]:["--verbatim"],I=F_(t);return {args:["--no-auto-update",...o,...I.flags,...x,"--output-format","streaming-json","--no-alt-screen",...i,...l,...E,...v,...w,...p],stdinMessage:I.stdinMessage}},extractText(t){let e=[],n=false;for(let r of t.split(`
59
- `).flatMap(Yn))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 Yn(t))if(e.type==="error"){let n=Nu(e);return Au(Ou(e))?new jt(n,rs):new j(n,rs)}return null},interpretExit(t,e){if(t===0)return null;let n=bu(e)||`Grok CLI exited with code ${t}.`;return Au(e)?new jt(n,rs):new j(n,rs)},parseResultMeta(t){let n=t.split(`
60
- `).flatMap(Yn).find(r=>r.type==="end");return n?{usage:$_(n),model:M_(n)}:{usage:H_(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return Yn(t).flatMap(r=>q_(Ke(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return kn(n)&&typeof n.type=="string"?x_.has(n.type):!1}catch{return false}}};});var vu,xu=b(()=>{g();ko();yo();Eo();Io();Do();Eu();Lo();ko();yo();Eo();Io();Do();Lo();fn();vu={codex:wo,claude:Yr,opencode:So,antigravity:Co,copilot:To,grok:Po};});function Cu(t){if(t.startsWith("cli/"))return vu[t.slice(4)]}var Du=b(()=>{g();wd();xu();});function ss(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function B_(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function os(t){if(typeof t.provider!="string"||t.provider.length===0)return;let n=t.taskLogRepository.readLogs(t.taskId)?.entries.filter(f=>f.level==="stdout").map(f=>f.message).join(`
61
- `)??"";if(!n.trim())return;let r=Cu(t.provider);if(!r)return;let s;try{s=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let o=B_(s?.model,t.model),i=s?.usage;if(!i)return {stdout:n,adapter:r};let u=ss(i.inputTokens),d=ss(i.outputTokens),c=ss(i.cachedInputTokens),l=Qa(ss(i.costUsd),u,d,c,o);return u!==0||d!==0||c!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:u,outputTokens:d,cachedInputTokens:c,costUsd:l,model:o,...i.complete===void 0?{}:{complete:i.complete}}}:{stdout:n,adapter:r}}var Mo=b(()=>{g();Du();Hr();});function Ho(t){let e=new Set;for(let n of t)for(let r of W_.get(n)??[n])e.add(r);return [...e]}function Uo(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"&&G_.has(n)?n:void 0}catch{return}}function ze(t){let e=Uo(t.metadata);if(e)return e;if(t.status==="runner_lost")return "runner_lost";if(t.status==="stopped")return "user_stop";if(t.status==="failed"&&typeof t.error=="string"){if($o.stopped.test(t.error))return "user_stop";if($o.runnerLost.test(t.error))return "runner_lost"}}function xe(t){switch(t.status){case "stopped":case "pending":case "running":case "paused":case "success":return t.status;case "completed":case "done":return "success";case "error":case "runner_lost":return "failed";case "failed":{let e=Uo(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&$o.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function j_(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function Qn(t){let e=xe(t);return t.status==="runner_lost"&&Uo(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...j_(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var Zt,W_,$o,G_,Zn=b(()=>{g();Zt=["success","completed","done","failed","error","stopped","runner_lost"],W_=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);$o={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},G_=new Set(["user_stop","runner_lost","launch_failed"]);});function qo(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let s=Number(r);return !Number.isFinite(s)||s<=0?e:Math.max(n,Math.trunc(s))}function tr(){return qo("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function wn(){return qo("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function as(){return qo("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function yn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function is(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 K_(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 Pu(t,e){return !!t.stop_requested_at&&yn(t.stop_requested_epoch)===yn(e)}function Lu(t,e){let n=yn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let s=K_(t.getTask(e.taskId));return !s||s.status!=="running"||yn(s.run_epoch)!==n?{accepted:false,row:s}:{accepted:true,row:s}}function Uu(t,e){let n=er.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),er.delete(t),true)}function nr(t,e){let n=er.get(t);return !n||e!==void 0&&n.runEpoch!==yn(e)?false:Uu(t,n)}function qu(t,e){let n=yn(e.runEpoch);nr(e.taskId);let r=true,s=null;try{let c=Lu(t,{...e,runEpoch:n});r=c.accepted,s=c.row;}catch(c){is(c);}if(!r)return false;let o=tr(),i=Math.min(o,1e3),u=setInterval(()=>{let c=er.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=i;let l=c.heartbeatElapsedMs>=o,p=Lu(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){Uu(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=o,c.lastHeartbeatAt=Date.now()),p.row&&Pu(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(is));}catch(l){is(l);}},i),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return er.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),s&&Pu(s,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(s)).catch(is)),true}var Mu,$u,Hu,er,rr=b(()=>{g();Mu=1e4,$u=3e4,Hu=18e5;er=new Map;});function us(t,e=Date.now(),n=Ko){let r=t?Date.parse(t):Number.NaN,s=typeof e=="number"?e:Date.parse(e),o=Vo(n,Ko,0);return Number.isFinite(r)&&Number.isFinite(s)&&s-r>o?"forced":"cooperative"}function Qo(t){let e=[],n=typeof t.pid=="number"&&t.pid>0?t.pid:void 0;n!==void 0&&e.push({pid:n,startedAt:t.pid_started_at});let r=Gu(t.metadata),s=r.ownership==="runner"&&typeof r.providerPid=="number"&&Number.isSafeInteger(r.providerPid)&&r.providerPid>0?r.providerPid:void 0;if(s!==void 0&&s!==n){let o=r.providerPidStartedAt;e.push({pid:s,startedAt:typeof o=="string"?o:null});}return e}async function Zo(t,e={}){if(t.pid===process.pid||t.pid===process.ppid)return {verdict:"unproven",ownership:"not_owned",reason:"pid is this process or its parent"};let n=typeof t.startedAt=="string"?Date.parse(t.startedAt):Number.NaN,r=Number.isFinite(n),s=e.legacyStartBoundaryMs;if(!r&&s===void 0)return {verdict:"unproven",ownership:"unknown",reason:"no start time recorded"};let o=e.processControlOptions??{},i=e.processControl?.checkProcessOwnershipAsync??ad,u=e.processControl?.readProcessIdentityAsync??ld,d;try{d=await i(t.pid,e.ownershipMarkers??J_,o);}catch{d="unknown";}let c;try{c=await u(t.pid,o);}catch{c={status:"unknown"};}if(c.status==="not_found")return {verdict:"unproven",ownership:"not_found",reason:"process is no longer running"};if(c.status!=="found")return {verdict:"unproven",ownership:"unknown",reason:"start time could not be read"};let l=new Date(c.startedAtMs).toISOString();if(r){if(Math.abs(c.startedAtMs-n)>qr)return {verdict:"reused",reason:`started ${l}, not the recorded ${t.startedAt}`}}else return s!==void 0&&c.startedAtMs>s?{verdict:"reused",reason:`started ${l}, after the row's last heartbeat`}:{verdict:"unproven",ownership:"unknown",reason:"no start time recorded and it started before the row's last heartbeat"};return d!=="owned"?{verdict:"unproven",ownership:d,reason:"command line has no owned marker"}:c.groupId!==null&&c.groupId!==t.pid?{verdict:"unproven",ownership:"not_owned",reason:"pid does not lead its process group"}:{verdict:"owned"}}async function ei(t,e={}){let n=await Zo(t,e);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function Vo(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function Gu(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function eg(t){if(!t)return;let e=Gu(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function Ce(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=eg(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function ds(t,e,n="Process owner could not be verified"){let r=e??(t.pid&&t.pid>0?t.pid:void 0);return {status:"ownership_unverified",finalStatus:t.status,...r?{pid:r}:{},error:n}}function Z(t,e,n){let r=n??(t?.pid&&t.pid>0?t.pid:void 0);return {status:"failed",finalStatus:t?.status??null,...r?{pid:r}:{},error:e}}function jo(t,e){return Z(t,X_,e)}function tg(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=wn():false}function ng(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function rg(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return Ce(r,n)}async function sg(t,e,n,r){let s=Date.now()+n;for(;;){let o=rg(t,e);if(o)return o;let i=s-Date.now();if(i<=0)return;await new Promise(u=>{setTimeout(u,Math.min(r,i));});}}async function Wu(t,e,n){let r=new Date().toISOString(),s={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},o=t.requestTaskStop({id:e,requestedAt:r,...s}),i=t.getTask(e);if(!o.accepted){if(o.status==="pending"){let x=t.stopPendingTask(e,void 0,void 0,{...s,at:r}),I=t.getTask(e);if(x||!I||I.status!=="running")return Ce(I);if(o=t.requestTaskStop({id:e,requestedAt:r,...s}),!o.accepted&&o.status!=="running"||!o.accepted&&!o.alreadyRequestedAt)return Ce(t.getTask(e))}else if(!(o.status==="running"&&o.alreadyRequestedAt))return Ce(i)}let u=o.runEpoch,d=Vo(n.graceMs,Ko,0),c=Vo(n.pollMs,z_,1),l=await sg(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return Ce(p);let f=Qo(p),h=f.map(x=>x.pid),m=h[0];if(!m){let x=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),I=t.getTask(e);return x||I?.status!=="running"?Ce(I):Z(I,"Failed to finalize task stop")}let k=ng(n);if(!tg(p,Date.now())){for(let x of f)if(await ei(x,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:k})!=="owned")return ds(p)}let E=n.processControl?.terminateProcessTree??It;for(let x of h){let I;try{I=await E(x,{...k,signal:St});}catch(O){I={status:"failed",pid:x,method:k.platform==="win32"?"taskkill":"process-group",error:O instanceof Error?O.message:String(O)};}if(I.status==="failed")return Z(t.getTask(e),I.error??"Failed to terminate process tree")}let v=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),w=t.getTask(e);return v||w?.status!=="running"?Ce(w,m):Z(w,"Task changed before stop was finalized")}function Xo(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function Yo(t){return Number.isSafeInteger(t)&&t>=0}function sr(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function og(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function ig(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function ag(t,e){let n=t?.pid&&t.pid>0?t.pid:e;return {status:"stopped",method:"forced",finalStatus:t?.status??"failed",...n?{pid:n}:{}}}function dg(t){switch(t){case "epoch_mismatch":return zo;case "workspace_mismatch":return Jo;default:return}}async function ju(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return jo(n,Xo(e.targetPid)?e.targetPid:void 0);if(!Yo(e.sourceRunEpoch)||!Yo(e.settleRunEpoch)||sr(n.run_epoch)!==e.settleRunEpoch)return Z(n,Fo,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return Z(n,Bo,e.targetPid);let r=new Date().toISOString(),s;try{s=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return Z(n,Go,e.targetPid)}let o=v=>s.stopRequestReceipt?{...v,stopRequestReceipt:s.stopRequestReceipt}:v,i=n,u=()=>{let v=t.getTask(e.taskId);return i=v,v},d=(v,w=false)=>{if(w)try{u();}catch{}return o(Z(i,v,e.targetPid))},c;try{c=u();}catch{return d(Go)}if(!c||c.status!=="running")return o(jo(c,e.targetPid));if(s.runEpoch!==e.settleRunEpoch||sr(c.run_epoch)!==e.settleRunEpoch)return o(Z(c,Fo,e.targetPid));if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return o(Z(c,Bo,e.targetPid));if(!Xo(e.targetPid))return o(Z(c,V_));let l=og(e),p;try{p=await ei({pid:e.targetPid,startedAt:c.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:l});}catch{return o(ds(c,e.targetPid))}if(p!=="owned")return o(ds(c,e.targetPid));let f;try{f=u();}catch{return d(Go)}if(!f||f.status!=="running")return o(jo(f,e.targetPid));if(sr(f.run_epoch)!==e.settleRunEpoch)return o(Z(f,Fo,e.targetPid));if(e.workspaceId!==void 0&&f.workspace_id!==e.workspaceId)return o(Z(f,Bo,e.targetPid));let h=e.processControl?.terminateProcessTree??It,m;try{m=await h(e.targetPid,{...l,signal:St});}catch{return d(Fu,true)}if(m.status==="failed")return d(Fu,true);let k;try{k=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return d(Wo,true)}if(!k)return d(Wo,true);let E;try{E=u();}catch{return d(Wo)}return o(Ce(E,e.targetPid))}async function Ku(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Ce(n);if(!Yo(e.expectedRunEpoch)||sr(n.run_epoch)!==e.expectedRunEpoch)return Z(n,zo);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return Z(n,Jo);let r=n.pid;if(!Xo(r))return Z(n,Y_);let s=ig(e);if(await ei({pid:r,startedAt:n.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:s})!=="owned")return ds(n,r,Q_);let i=e.processControl?.terminateProcessTree??It,u;try{u=await i(r,{...s,signal:St});}catch{return Z(t.getTask(e.taskId),Bu,r)}if(u.status==="failed")return Z(t.getTask(e.taskId),Bu,r);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return Ce(d,r);if(sr(d.run_epoch)!==e.expectedRunEpoch)return Z(d,zo,r);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return Z(d,Jo,r);let c;try{c=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return Z(t.getTask(e.taskId),Z_,r)}let l=dg(c);return l?Z(t.getTask(e.taskId),l,r):c!=="settled"?Ce(t.getTask(e.taskId),r):ag(t.getTask(e.taskId),r)}function zu(t,e,n={}){if(typeof t=="string"){let r=t,s=e??{};return Promise.resolve().then(()=>(ni(),Ju)).then(({TaskRepository:o})=>Wu(new o,r,s))}return Wu(t,e,n)}var Ko,z_,J_,V_,Fo,Bo,X_,Fu,Wo,Go,zo,Jo,Y_,Q_,Bu,Z_,ti=b(()=>{g();Fr();rr();Ko=5e3,z_=250;J_=["agy","crewx","claude","codex","opencode","grok","node"];V_="INSTRUCTION_STOP_TARGET_PID_MISSING",Fo="INSTRUCTION_STOP_EPOCH_MISMATCH",Bo="INSTRUCTION_STOP_WORKSPACE_MISMATCH",X_="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",Fu="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Wo="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Go="INSTRUCTION_STOP_REQUEST_FAILED",zo="HOST_SHUTDOWN_EPOCH_MISMATCH",Jo="HOST_SHUTDOWN_WORKSPACE_MISMATCH",Y_="HOST_SHUTDOWN_TARGET_PID_MISSING",Q_="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",Bu="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",Z_="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var Ju={};qc(Ju,{CANONICAL_USER_STOP_ERROR:()=>pi,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>rc,HOST_SHUTDOWN_TERMINAL_ERROR:()=>Zu,PENDING_ADOPT_GRACE_MS:()=>nc,PID_NULL_REAP_GRACE_MS:()=>hi,RATED_TASK_EXCERPT_MAX_CHARS:()=>mi,RATED_TASK_LIST_MAX_LIMIT:()=>oc,TASK_HEARTBEAT_HARD_STALE_MS:()=>Hu,TASK_HEARTBEAT_INTERVAL_MS:()=>Mu,TASK_HEARTBEAT_STALE_MS:()=>$u,TASK_RATINGS:()=>sc,TaskRatingError:()=>cr,TaskRepository:()=>ur,WORKFLOW_ANCHOR_TASK_KINDS:()=>Et,buildRatedTasksCountQuery:()=>ac,buildRatedTasksQuery:()=>ic,countRatedTasks:()=>Og,hasRecordedUsage:()=>_i,isWorkflowAnchorTaskKind:()=>Bn,listRatedTasks:()=>Ag,mergeTerminalReason:()=>fi,resolveTaskHeartbeatHardStaleMs:()=>as,resolveTaskHeartbeatIntervalMs:()=>tr,resolveTaskHeartbeatStaleMs:()=>wn,setTaskRating:()=>Ig});function Ve(t){return Qn(t)}function si(t){return Qn(t)}function oi(){return drizzleOrm.or(...Et.map(t=>drizzleOrm.like(a.metadata,`%"kind":"${t}"%`)))}function Vu(){return drizzleOrm.and(...Et.map(t=>drizzleOrm.notLike(a.metadata,`%"kind":"${t}"%`)))}function ai(t=a.model,e=a.metadata){let n=drizzleOrm.sql`
75
+ `;u=`${u}${l}${d}`;}else u=n(d);if(u)return u;let c=n(i.summary)??n(Qt(t.content))??n(i.output_for_prompt);return c!==void 0?c:s(o)}if(t.content!==null&&t.content!==void 0)return Qt(t.content)??s(t.content);if(t.result!==null&&t.result!==void 0)return Qt(t.result)??s(t.result)}function Ju(t){let e=yn(t.error),n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0].find(r=>typeof r=="string"&&r.trim().length>0);return n?Vu(n):"Grok CLI reported an error."}function Vu(t){return (t.replace(Eg,"").split(/\r?\n/).map(n=>n.trim()).filter(Boolean)[0]??t.trim()).slice(0,500)}function Ku(t){return wg.test(t)}function Ig(t){let e=yn(t.modelUsage);return e?Object.keys(e)[0]??null:null}function Ag(t){let e=yn(t.usage);if(!e)return null;let n=Zt(e.cache_read_input_tokens);return {inputTokens:Zt(e.input_tokens)+n,cachedInputTokens:n,outputTokens:Zt(e.output_tokens),costUsd:Zt(t.total_cost_usd)}}function Og(t){let e=0,n=0,r=0,s=false,o=new Set;for(let i of t.split(`
76
+ `).flatMap(er)){if(i.type!=="usage")continue;let u=yn(i.usage);if(!u)continue;let d=Oe(i.signature);if(d&&d.length>0){let l=`signature:${d}`;if(o.has(l))continue;o.add(l);}let c=Zt(u.cache_read_input_tokens);e+=Zt(u.input_tokens)+c,n+=c,r+=Zt(u.output_tokens),s=true;}return s?{inputTokens:e,cachedInputTokens:n,outputTokens:r,costUsd:0}:null}function Ng(t,e){if(!Array.isArray(e.entries)||e.entries.length===0)return [];let n=[];for(let o of e.entries.slice(0,Wu)){if(!Tn(o))continue;let i=Oe(o.content)?.trim();if(!i)continue;let u=Oe(o.status)?.trim(),d=Oe(o.priority)?.trim(),c=[u?`status=${u}`:void 0,d?`priority=${d}`:void 0].filter(p=>!!p),l=c.length>0?` (${c.join(", ")})`:"";n.push(`- ${i}${l}`);}if(n.length===0)return [];e.entries.length>Wu&&n.push(ju);let r=n.join(`
77
+ `),s=r.length>Gu?`${r.slice(0,Gu-1)}${ju}`:r;return [{timestamp:t,type:"info",content:s}]}function bg(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 Ng(t,e);if(n==="tool_call"){let r=Oe(e.toolCallId),s=Oe(e.toolName)??Oe(e.title),o=e.rawInput===void 0?void 0:zu(e.rawInput);return [{timestamp:t,type:"tool_use",toolUseId:r,toolName:s,toolInput:o}]}if(n==="tool_call_update"){let r=Oe(e.status);if(r!=="completed"&&r!=="failed"&&r!=="error")return [];let s=Sg(e),o=r!=="completed"||e.isError===true;return [{timestamp:t,type:"tool_result",toolUseId:Oe(e.toolCallId),toolName:Oe(e.toolName)??Oe(e.title),...s!==void 0?ze(s,o):{isError:o}}]}if(n==="error"){let r=Ju(e);return [{timestamp:t,type:"error",content:r,errorMessage:r}]}return []}function vg(t){return process.platform==="win32"?{flags:["--single",t]}:{flags:["--prompt-file","/dev/stdin"],stdinMessage:t}}var us,yg,wg,Eg,Wu,Gu,ju,Wo,Go=N(()=>{g();bt();fo();Vt();gn();Xn();Xt();us="cli/grok",yg=new Set(["available_commands","usage","end"]),wg=/(?:rate[\s_-]*limit|quota|usage[\s_-]*limit|too many requests|limit(?:ed|ing)?\s+(?:exceeded|reached))/i,Eg=/\u001b\[[0-?]*[ -/]*[@-~]/g,Wu=20,Gu=4e3,ju="\u2026";Wo={command:"grok",createSessionId:()=>crypto.randomUUID(),meta:{displayName:"Grok",capabilities:{resume:true}},buildArgs(t,e){let{model:n,effort:r}=xt(e.model),s=e.effort??r,o=e.resumeSessionId?["--resume",e.resumeSessionId]:e.providerSessionId?["--session-id",e.providerSessionId]:[],i=n?["--model",n]:[],u=n?vt("grok").some(O=>O.id===n):false,d=n&&u?Vn("grok",n):[],c=!s||d.length===0||d.includes(s)?s:void 0,l=nu(c),p=e.additionalArgs??[],f=O=>p.some(S=>S===O||S.startsWith(`${O}=`)),h=e.providerOptions,m=h?.alwaysApprove,k=h?.sandbox,E=f("--permission-mode")?[]:Zd(e.mode),v=f("--always-approve")?[]:eu(m),w=f("--sandbox")?[]:tu(k),x=f("--verbatim")?[]:["--verbatim"],I=vg(t);return {args:["--no-auto-update",...o,...I.flags,...x,"--output-format","streaming-json","--no-alt-screen",...i,...l,...E,...v,...w,...p],stdinMessage:I.stdinMessage}},extractText(t){let e=[],n=false;for(let r of t.split(`
78
+ `).flatMap(er))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 er(t))if(e.type==="error"){let n=Ju(e);return Ku(zu(e))?new Jt(n,us):new U(n,us)}return null},interpretExit(t,e){if(t===0)return null;let n=Vu(e)||`Grok CLI exited with code ${t}.`;return Ku(e)?new Jt(n,us):new U(n,us)},parseResultMeta(t){let n=t.split(`
79
+ `).flatMap(er).find(r=>r.type==="end");return n?{usage:Ag(n),model:Ig(n)}:{usage:Og(t),model:null}},parseEvent(t,e){let n=e??new Date().toISOString();return er(t).flatMap(r=>bg(Ve(r,n),r))},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let n=JSON.parse(e);return Tn(n)&&typeof n.type=="string"?yg.has(n.type):!1}catch{return false}}};});var Xu,Yu=N(()=>{g();So();Ao();No();Po();Bo();Bu();Go();So();Ao();No();Po();Bo();Go();_n();Xu={codex:Oo,claude:es,opencode:Do,antigravity:Fo,copilot:Io,grok:Wo};});function Qu(t){if(t.startsWith("cli/"))return Xu[t.slice(4)]}var Zu=N(()=>{g();vd();Yu();});function cs(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function xg(t,e){return typeof t=="string"&&t.length>0?t:typeof e=="string"&&e.length>0?e:null}function ls(t){if(typeof t.provider!="string"||t.provider.length===0)return;let n=t.taskLogRepository.readLogs(t.taskId)?.entries.filter(f=>f.level==="stdout").map(f=>f.message).join(`
80
+ `)??"";if(!n.trim())return;let r=Qu(t.provider);if(!r)return;let s;try{s=r.parseResultMeta?.(n);}catch{return {stdout:n,adapter:r}}let o=xg(s?.model,t.model),i=s?.usage;if(!i)return {stdout:n,adapter:r};let u=cs(i.inputTokens),d=cs(i.outputTokens),c=cs(i.cachedInputTokens),l=ad(cs(i.costUsd),u,d,c,o);return u!==0||d!==0||c!==0||l!==0?{stdout:n,adapter:r,usage:{inputTokens:u,outputTokens:d,cachedInputTokens:c,costUsd:l,model:o,...i.complete===void 0?{}:{complete:i.complete}}}:{stdout:n,adapter:r}}var jo=N(()=>{g();Zu();Fr();});function zo(t){let e=new Set;for(let n of t)for(let r of Cg.get(n)??[n])e.add(r);return [...e]}function Jo(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"&&Dg.has(n)?n:void 0}catch{return}}function Xe(t){let e=Jo(t.metadata);if(e)return e;if(t.status==="runner_lost")return "runner_lost";if(t.status==="stopped")return "user_stop";if(t.status==="failed"&&typeof t.error=="string"){if(Ko.stopped.test(t.error))return "user_stop";if(Ko.runnerLost.test(t.error))return "runner_lost"}}function De(t){switch(t.status){case "stopped":case "pending":case "running":case "paused":case "success":return t.status;case "completed":case "done":return "success";case "error":case "runner_lost":return "failed";case "failed":{let e=Jo(t.metadata);return e==="user_stop"?"stopped":e?"failed":typeof t.error=="string"&&Ko.stopped.test(t.error)?"stopped":"failed"}default:return t.status}}function Pg(t){if(!t)return {};try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return {}}}function tr(t){let e=De(t);return t.status==="runner_lost"&&Jo(t.metadata)===void 0?{...t,status:e,metadata:JSON.stringify({...Pg(t.metadata),terminalReason:"runner_lost"})}:{...t,status:e}}var en,Cg,Ko,Dg,nr=N(()=>{g();en=["success","completed","done","failed","error","stopped","runner_lost"],Cg=new Map([["success",["success","completed","done"]],["failed",["failed","error","runner_lost"]]]);Ko={stopped:/^(Killed by user|Stopped by user|Cancelled by user|사용자에 의해 중지됨)/,runnerLost:/^Reaped: (process not found|pid never recorded|stale workflow run)/},Dg=new Set(["user_stop","runner_lost","launch_failed"]);});function Vo(t,e,n=1){let r=process.env[t];if(r===void 0||r==="")return e;let s=Number(r);return !Number.isFinite(s)||s<=0?e:Math.max(n,Math.trunc(s))}function sr(){return Vo("CREWX_TASK_HEARTBEAT_MS",1e4,200)}function En(){return Vo("CREWX_TASK_HEARTBEAT_STALE_MS",3e4)}function fs(){return Vo("CREWX_TASK_HEARTBEAT_HARD_STALE_MS",18e5)}function wn(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function ps(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 Lg(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 ec(t,e){return !!t.stop_requested_at&&wn(t.stop_requested_epoch)===wn(e)}function tc(t,e){let n=wn(e.runEpoch);if(!(e.writeHeartbeat===false?true:t.heartbeatTask({id:e.taskId,runEpoch:n})))return {accepted:false,row:null};let s=Lg(t.getTask(e.taskId));return !s||s.status!=="running"||wn(s.run_epoch)!==n?{accepted:false,row:s}:{accepted:true,row:s}}function oc(t,e){let n=rr.get(t);return !n||e&&n!==e?false:(clearInterval(n.timer),rr.delete(t),true)}function or(t,e){let n=rr.get(t);return !n||e!==void 0&&n.runEpoch!==wn(e)?false:oc(t,n)}function ic(t,e){let n=wn(e.runEpoch);or(e.taskId);let r=true,s=null;try{let c=tc(t,{...e,runEpoch:n});r=c.accepted,s=c.row;}catch(c){ps(c);}if(!r)return false;let o=sr(),i=Math.min(o,1e3),u=setInterval(()=>{let c=rr.get(e.taskId);if(!(!c||c.timer!==u))try{c.heartbeatElapsedMs+=i;let l=c.heartbeatElapsedMs>=o,p=tc(t,{taskId:e.taskId,runEpoch:n,writeHeartbeat:l});if(!p.accepted){oc(e.taskId,c);return}l&&(c.heartbeatElapsedMs%=o,c.lastHeartbeatAt=Date.now()),p.row&&ec(p.row,n)&&!c.stopRequested&&(c.stopRequested=!0,e.onStopRequested&&Promise.resolve(e.onStopRequested(p.row)).catch(ps));}catch(l){ps(l);}},i),d={timer:u,runEpoch:n,stopRequested:false,lastHeartbeatAt:Date.now(),heartbeatElapsedMs:0};return rr.set(e.taskId,d),typeof u=="object"&&u!==null&&"unref"in u&&u.unref(),s&&ec(s,n)&&e.onStopRequested&&(d.stopRequested=true,Promise.resolve(e.onStopRequested(s)).catch(ps)),true}var nc,rc,sc,rr,ir=N(()=>{g();nc=1e4,rc=3e4,sc=18e5;rr=new Map;});function gs(t,e=Date.now(),n=ti){let r=t?Date.parse(t):Number.NaN,s=typeof e=="number"?e:Date.parse(e),o=si(n,ti,0);return Number.isFinite(r)&&Number.isFinite(s)&&s-r>o?"forced":"cooperative"}function ai(t){let e=[],n=typeof t.pid=="number"&&t.pid>0?t.pid:void 0;n!==void 0&&e.push({pid:n,startedAt:t.pid_started_at});let r=cc(t.metadata),s=r.ownership==="runner"&&typeof r.providerPid=="number"&&Number.isSafeInteger(r.providerPid)&&r.providerPid>0?r.providerPid:void 0;if(s!==void 0&&s!==n){let o=r.providerPidStartedAt;e.push({pid:s,startedAt:typeof o=="string"?o:null});}return e}async function di(t,e={}){if(t.pid===process.pid||t.pid===process.ppid)return {verdict:"unproven",ownership:"not_owned",reason:"pid is this process or its parent"};let n=typeof t.startedAt=="string"?Date.parse(t.startedAt):Number.NaN,r=Number.isFinite(n),s=e.legacyStartBoundaryMs;if(!r&&s===void 0)return {verdict:"unproven",ownership:"unknown",reason:"no start time recorded"};let o=e.processControlOptions??{},i=e.processControl?.checkProcessOwnershipAsync??hd,u=e.processControl?.readProcessIdentityAsync??yd,d;try{d=await i(t.pid,e.ownershipMarkers??$g,o);}catch{d="unknown";}let c;try{c=await u(t.pid,o);}catch{c={status:"unknown"};}if(c.status==="not_found")return {verdict:"unproven",ownership:"not_found",reason:"process is no longer running"};if(c.status!=="found")return {verdict:"unproven",ownership:"unknown",reason:"start time could not be read"};let l=new Date(c.startedAtMs).toISOString();if(r){if(Math.abs(c.startedAtMs-n)>Wr)return {verdict:"reused",reason:`started ${l}, not the recorded ${t.startedAt}`}}else return s!==void 0&&c.startedAtMs>s?{verdict:"reused",reason:`started ${l}, after the row's last heartbeat`}:{verdict:"unproven",ownership:"unknown",reason:"no start time recorded and it started before the row's last heartbeat"};return d!=="owned"?{verdict:"unproven",ownership:d,reason:"command line has no owned marker"}:c.groupId!==null&&c.groupId!==t.pid?{verdict:"unproven",ownership:"not_owned",reason:"pid does not lead its process group"}:{verdict:"owned"}}async function ui(t,e={}){let n=await di(t,e);return n.verdict==="owned"?"owned":n.verdict==="reused"?"not_owned":n.ownership}function si(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.max(n,Math.trunc(t))}function cc(t){if(!t)return {};try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}catch{}return {}}function Wg(t){if(!t)return;let e=cc(t.metadata).stopMethod;return e==="cooperative"||e==="forced"?e:void 0}function Pe(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=Wg(t);return {status:"stopped",finalStatus:t.status,...r?{method:r}:{},...n?{pid:n}:{}}}return {status:"not_running",finalStatus:t.status,...n?{pid:n}:{}}}function _s(t,e,n="Process owner could not be verified"){let r=e??(t.pid&&t.pid>0?t.pid:void 0);return {status:"ownership_unverified",finalStatus:t.status,...r?{pid:r}:{},error:n}}function Z(t,e,n){let r=n??(t?.pid&&t.pid>0?t.pid:void 0);return {status:"failed",finalStatus:t?.status??null,...r?{pid:r}:{},error:e}}function ei(t,e){return Z(t,Ug,e)}function Gg(t,e){if(!t.heartbeat_at)return false;let n=Date.parse(t.heartbeat_at);return Number.isFinite(n)?e-n<=En():false}function jg(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Kg(t,e,n){let r=t.getTask(e);if(!r||r.status!=="running")return Pe(r,n)}async function zg(t,e,n,r){let s=Date.now()+n;for(;;){let o=Kg(t,e);if(o)return o;let i=s-Date.now();if(i<=0)return;await new Promise(u=>{setTimeout(u,Math.min(r,i));});}}async function uc(t,e,n){let r=new Date().toISOString(),s={origin:n.origin??"internal",...n.callerPid!==void 0?{callerPid:n.callerPid}:{},...n.callerTaskId!==void 0?{callerTaskId:n.callerTaskId}:{}},o=t.requestTaskStop({id:e,requestedAt:r,...s}),i=t.getTask(e);if(!o.accepted){if(o.status==="pending"){let x=t.stopPendingTask(e,void 0,void 0,{...s,at:r}),I=t.getTask(e);if(x||!I||I.status!=="running")return Pe(I);if(o=t.requestTaskStop({id:e,requestedAt:r,...s}),!o.accepted&&o.status!=="running"||!o.accepted&&!o.alreadyRequestedAt)return Pe(t.getTask(e))}else if(!(o.status==="running"&&o.alreadyRequestedAt))return Pe(i)}let u=o.runEpoch,d=si(n.graceMs,ti,0),c=si(n.pollMs,Mg,1),l=await zg(t,e,d,c);if(l)return l;let p=t.getTask(e);if(!p||p.status!=="running")return Pe(p);let f=ai(p),h=f.map(x=>x.pid),m=h[0];if(!m){let x=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),I=t.getTask(e);return x||I?.status!=="running"?Pe(I):Z(I,"Failed to finalize task stop")}let k=jg(n);if(!Gg(p,Date.now())){for(let x of f)if(await ui(x,{ownershipMarkers:n.ownershipMarkers,processControl:n.processControl,processControlOptions:k})!=="owned")return _s(p)}let E=n.processControl?.terminateProcessTree??Nt;for(let x of h){let I;try{I=await E(x,{...k,signal:Ot});}catch(O){I={status:"failed",pid:x,method:k.platform==="win32"?"taskkill":"process-group",error:O instanceof Error?O.message:String(O)};}if(I.status==="failed")return Z(t.getTask(e),I.error??"Failed to terminate process tree")}let v=t.finalizeTaskStop({id:e,runEpoch:u,method:"forced"}),w=t.getTask(e);return v||w?.status!=="running"?Pe(w,m):Z(w,"Task changed before stop was finalized")}function oi(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>0}function ii(t){return Number.isSafeInteger(t)&&t>=0}function ar(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Jg(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Vg(t){return {...t.processControlOptions,...t.platform?{platform:t.platform}:{}}}function Xg(t,e){let n=t?.pid&&t.pid>0?t.pid:e;return {status:"stopped",method:"forced",finalStatus:t?.status??"failed",...n?{pid:n}:{}}}function Yg(t){switch(t){case "epoch_mismatch":return ni;case "workspace_mismatch":return ri;default:return}}async function lc(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return ei(n,oi(e.targetPid)?e.targetPid:void 0);if(!ii(e.sourceRunEpoch)||!ii(e.settleRunEpoch)||ar(n.run_epoch)!==e.settleRunEpoch)return Z(n,Xo,e.targetPid);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return Z(n,Yo,e.targetPid);let r=new Date().toISOString(),s;try{s=t.requestTaskStop({id:e.taskId,requestedAt:r,sourceRunEpoch:e.sourceRunEpoch,settleRunEpoch:e.settleRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return Z(n,Zo,e.targetPid)}let o=v=>s.stopRequestReceipt?{...v,stopRequestReceipt:s.stopRequestReceipt}:v,i=n,u=()=>{let v=t.getTask(e.taskId);return i=v,v},d=(v,w=false)=>{if(w)try{u();}catch{}return o(Z(i,v,e.targetPid))},c;try{c=u();}catch{return d(Zo)}if(!c||c.status!=="running")return o(ei(c,e.targetPid));if(s.runEpoch!==e.settleRunEpoch||ar(c.run_epoch)!==e.settleRunEpoch)return o(Z(c,Xo,e.targetPid));if(e.workspaceId!==void 0&&c.workspace_id!==e.workspaceId)return o(Z(c,Yo,e.targetPid));if(!oi(e.targetPid))return o(Z(c,Hg));let l=Jg(e),p;try{p=await ui({pid:e.targetPid,startedAt:c.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:l});}catch{return o(_s(c,e.targetPid))}if(p!=="owned")return o(_s(c,e.targetPid));let f;try{f=u();}catch{return d(Zo)}if(!f||f.status!=="running")return o(ei(f,e.targetPid));if(ar(f.run_epoch)!==e.settleRunEpoch)return o(Z(f,Xo,e.targetPid));if(e.workspaceId!==void 0&&f.workspace_id!==e.workspaceId)return o(Z(f,Yo,e.targetPid));let h=e.processControl?.terminateProcessTree??Nt,m;try{m=await h(e.targetPid,{...l,signal:Ot});}catch{return d(ac,true)}if(m.status==="failed")return d(ac,true);let k;try{k=t.finalizeTaskStop({id:e.taskId,runEpoch:e.settleRunEpoch,method:"forced"});}catch{return d(Qo,true)}if(!k)return d(Qo,true);let E;try{E=u();}catch{return d(Qo)}return o(Pe(E,e.targetPid))}async function pc(t,e){let n=t.getTask(e.taskId);if(!n||n.status!=="running")return Pe(n);if(!ii(e.expectedRunEpoch)||ar(n.run_epoch)!==e.expectedRunEpoch)return Z(n,ni);if(e.workspaceId!==void 0&&n.workspace_id!==e.workspaceId)return Z(n,ri);let r=n.pid;if(!oi(r))return Z(n,qg);let s=Vg(e);if(await ui({pid:r,startedAt:n.pid_started_at},{ownershipMarkers:e.ownershipMarkers,processControl:e.processControl,processControlOptions:s})!=="owned")return _s(n,r,Fg);let i=e.processControl?.terminateProcessTree??Nt,u;try{u=await i(r,{...s,signal:Ot});}catch{return Z(t.getTask(e.taskId),dc,r)}if(u.status==="failed")return Z(t.getTask(e.taskId),dc,r);let d=t.getTask(e.taskId);if(!d||d.status!=="running")return Pe(d,r);if(ar(d.run_epoch)!==e.expectedRunEpoch)return Z(d,ni,r);if(e.workspaceId!==void 0&&d.workspace_id!==e.workspaceId)return Z(d,ri,r);let c;try{c=t.finalizeTaskForHostShutdown({id:e.taskId,expectedRunEpoch:e.expectedRunEpoch,...e.workspaceId!==void 0?{workspaceId:e.workspaceId}:{}});}catch{return Z(t.getTask(e.taskId),Bg,r)}let l=Yg(c);return l?Z(t.getTask(e.taskId),l,r):c!=="settled"?Pe(t.getTask(e.taskId),r):Xg(t.getTask(e.taskId),r)}function fc(t,e,n={}){if(typeof t=="string"){let r=t,s=e??{};return Promise.resolve().then(()=>(li(),_c)).then(({TaskRepository:o})=>uc(new o,r,s))}return uc(t,e,n)}var ti,Mg,$g,Hg,Xo,Yo,Ug,ac,Qo,Zo,ni,ri,qg,Fg,dc,Bg,ci=N(()=>{g();Gr();ir();ti=5e3,Mg=250;$g=["agy","crewx","claude","codex","opencode","grok","node"];Hg="INSTRUCTION_STOP_TARGET_PID_MISSING",Xo="INSTRUCTION_STOP_EPOCH_MISMATCH",Yo="INSTRUCTION_STOP_WORKSPACE_MISMATCH",Ug="INSTRUCTION_STOP_GENERATION_ALREADY_SETTLED",ac="INSTRUCTION_STOP_PROCESS_TERMINATION_FAILED",Qo="INSTRUCTION_STOP_SETTLE_CAS_FAILED",Zo="INSTRUCTION_STOP_REQUEST_FAILED",ni="HOST_SHUTDOWN_EPOCH_MISMATCH",ri="HOST_SHUTDOWN_WORKSPACE_MISMATCH",qg="HOST_SHUTDOWN_TARGET_PID_MISSING",Fg="HOST_SHUTDOWN_OWNERSHIP_UNVERIFIED",dc="HOST_SHUTDOWN_PROCESS_TERMINATION_FAILED",Bg="HOST_SHUTDOWN_SETTLE_CAS_FAILED";});var _c={};il(_c,{CANONICAL_USER_STOP_ERROR:()=>wi,DEFAULT_TASK_REAPER_TICK_INTERVAL_MS:()=>Rc,HOST_SHUTDOWN_TERMINAL_ERROR:()=>Tc,PENDING_ADOPT_GRACE_MS:()=>Ec,PID_NULL_REAP_GRACE_MS:()=>Ii,RATED_TASK_EXCERPT_MAX_CHARS:()=>Ai,RATED_TASK_LIST_MAX_LIMIT:()=>Ic,TASK_HEARTBEAT_HARD_STALE_MS:()=>sc,TASK_HEARTBEAT_INTERVAL_MS:()=>nc,TASK_HEARTBEAT_STALE_MS:()=>rc,TASK_RATINGS:()=>Sc,TaskRatingError:()=>fr,TaskRepository:()=>pr,WORKFLOW_ANCHOR_TASK_KINDS:()=>It,buildRatedTasksCountQuery:()=>Oc,buildRatedTasksQuery:()=>Ac,countRatedTasks:()=>hh,hasRecordedUsage:()=>Ri,isWorkflowAnchorTaskKind:()=>Wn,listRatedTasks:()=>gh,mergeTerminalReason:()=>Ei,resolveTaskHeartbeatHardStaleMs:()=>fs,resolveTaskHeartbeatIntervalMs:()=>sr,resolveTaskHeartbeatStaleMs:()=>En,setTaskRating:()=>_h});function Qe(t){return tr(t)}function fi(t){return tr(t)}function _i(){return drizzleOrm.or(...It.map(t=>drizzleOrm.like(a.metadata,`%"kind":"${t}"%`)))}function gc(){return drizzleOrm.and(...It.map(t=>drizzleOrm.notLike(a.metadata,`%"kind":"${t}"%`)))}function hi(t=a.model,e=a.metadata){let n=drizzleOrm.sql`
62
81
  CASE
63
82
  WHEN ${t} LIKE 'claude-%' OR ${t} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
64
83
  WHEN ${t} LIKE 'gpt-%' OR ${t} LIKE 'codex-%' THEN 'codex'
@@ -87,7 +106,7 @@ ${r.join(`
87
106
  WHEN trim(${i}) = '' THEN 'unknown'
88
107
  ELSE ${i}
89
108
  END
90
- `}function hg(t){let e={status:t.status,metadata:t.metadata},n=xe(e);return n==="stopped"||n==="failed"&&ze(e)==="runner_lost"}function ar(t){return drizzleOrm.sql`${t} NOT IN (${drizzleOrm.sql.join(mg.map(e=>drizzleOrm.sql`${e}`),drizzleOrm.sql`, `)})`}function cs(t){let e=drizzleOrm.sql`
109
+ `}function oh(t){let e={status:t.status,metadata:t.metadata},n=De(e);return n==="stopped"||n==="failed"&&Xe(e)==="runner_lost"}function cr(t){return drizzleOrm.sql`${t} NOT IN (${drizzleOrm.sql.join(ih.map(e=>drizzleOrm.sql`${e}`),drizzleOrm.sql`, `)})`}function hs(t){let e=drizzleOrm.sql`
91
110
  CASE
92
111
  WHEN json_valid(${t}) = 1
93
112
  THEN json_extract(${t}, '$.usageAccounting')
@@ -97,7 +116,7 @@ ${r.join(`
97
116
  COALESCE(SUM(
98
117
  CASE WHEN ${e} = 'unavailable' THEN 1 ELSE 0 END
99
118
  ), 0)
100
- `}function en(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function oe(t){if(!t)return {};try{let e=JSON.parse(t);return en(e)?{...e}:{}}catch{return {}}}function gs(t){return t==null||t===""}function ls(t,e){return gs(t)&&!gs(e)?e:t}function kg(t,e){let n=oe(t);if(!e)return n;for(let[r,s]of Object.entries(e))gs(n[r])&&!gs(s)&&(n[r]=s);return n}function ps(t,e){let n=t.origin&&ec.has(t.origin)?t.origin:"internal",r=t.callerPid!==void 0&&Number.isInteger(t.callerPid)&&t.callerPid>0?t.callerPid:process.pid;return {origin:n,at:t.at??e,callerPid:r,...t.callerTaskId?{callerTaskId:t.callerTaskId}:{}}}function Tg(t){let e=oe(t).stopRequest;if(en(e)&&!(typeof e.origin!="string"||!ec.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function Xu(){return drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.ne(drizzleOrm.sql`COALESCE(${a.stop_requested_epoch}, 0)`,drizzleOrm.sql`COALESCE(${a.run_epoch}, 0)`))}function fi(t,e){let n=oe(t??null);return n.terminalReason=e,JSON.stringify(n)}function ui(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==pi&&(n[gg]=e),{error:pi,metadata:n}}function pe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function _i(t){return pe(t.input_tokens)!==0||pe(t.output_tokens)!==0||pe(t.cached_input_tokens)!==0||pe(t.cost_usd)!==0}function F(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function Yu(t){return {inputTokens:pe(t.inputTokens??0),outputTokens:pe(t.outputTokens??0),cachedInputTokens:pe(t.cachedInputTokens??0),costUsd:pe(t.costUsd??0)}}function tc(t){if(en(t))return {inputTokens:pe(t.inputTokens),outputTokens:pe(t.outputTokens),cachedInputTokens:pe(t.cachedInputTokens),costUsd:pe(t.costUsd)}}function dr(t){if(!en(t))return;let e=t.accounting;return e==="recorded"||e==="partial"||e==="unavailable"?e:void 0}function gi(t){return t.inputTokens!==0||t.outputTokens!==0||t.cachedInputTokens!==0||t.costUsd!==0}function yg(t){let e=dr(t);if(e==="recorded"||e==="partial")return true;if(e==="unavailable")return false;let n=tc(t);return n!==void 0&&gi(n)}function wg(t){return Object.values(t).some(e=>{let n=dr(e);return n==="partial"||n==="unavailable"})}function Eg(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){if(dr(n)==="unavailable")continue;let r=tc(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function fs(t,e,n){let r=Date.parse(t),s=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(s)?s-r:n??null}function ci(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return null;let n=cd(t,e);return n.status==="found"?new Date(n.startedAtMs).toISOString():null}function In(t,e){if(typeof t!="string"||t.length===0)throw new _("VALIDATION",`${e} is required`);return t}function ki(t,e){let n=Date.parse(t);if(!Number.isFinite(n))throw new _("VALIDATION",`${e} is not a valid ISO time: ${t}`);return new Date(n).toISOString()}function Ig(t,e){let n=In(e.workspaceId,"workspaceId"),r=In(e.taskId,"taskId"),s=e.rating;if(s!==null&&!sc.includes(s))throw new _("VALIDATION","rating must be 'up', 'down' or null");let o=e.now===void 0?new Date().toISOString():ki(e.now,"now");try{return t.transaction(i=>{let u=drizzleOrm.and(drizzleOrm.eq(a.id,r),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...Zt])),d=i.update(a).set({rating:s,rated_at:s===null?null:o}).where(drizzleOrm.and(u,drizzleOrm.sql`${a.rating} IS NOT ${s}`)).returning({rating:a.rating,ratedAt:a.rated_at}).all();if(d.length>0)return {taskId:r,rating:d[0].rating,ratedAt:d[0].ratedAt,changed:!0};let c=i.select({status:a.status,rating:a.rating,rated_at:a.rated_at}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,r),drizzleOrm.eq(a.workspace_id,n))).limit(1).get();if(!c)throw new cr("TASK_NOT_FOUND",r);if(!Sg.has(c.status))throw new cr("TASK_RATING_NOT_TERMINAL",r);return {taskId:r,rating:c.rating,ratedAt:c.rated_at,changed:!1}},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to set task rating",i)}}function ic(t){let e=drizzleOrm.sql`
119
+ `}function tn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function oe(t){if(!t)return {};try{let e=JSON.parse(t);return tn(e)?{...e}:{}}catch{return {}}}function ws(t){return t==null||t===""}function ms(t,e){return ws(t)&&!ws(e)?e:t}function ah(t,e){let n=oe(t);if(!e)return n;for(let[r,s]of Object.entries(e))ws(n[r])&&!ws(s)&&(n[r]=s);return n}function ks(t,e){let n=t.origin&&yc.has(t.origin)?t.origin:"internal",r=t.callerPid!==void 0&&Number.isInteger(t.callerPid)&&t.callerPid>0?t.callerPid:process.pid;return {origin:n,at:t.at??e,callerPid:r,...t.callerTaskId?{callerTaskId:t.callerTaskId}:{}}}function dh(t){let e=oe(t).stopRequest;if(tn(e)&&!(typeof e.origin!="string"||!yc.has(e.origin)||typeof e.at!="string"||typeof e.callerPid!="number"))return {...e}}function hc(){return drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.ne(drizzleOrm.sql`COALESCE(${a.stop_requested_epoch}, 0)`,drizzleOrm.sql`COALESCE(${a.run_epoch}, 0)`))}function Ei(t,e){let n=oe(t??null);return n.terminalReason=e,JSON.stringify(n)}function ki(t,e){let n={...t,terminalReason:"user_stop"},r=e?.trim();return r&&r!==wi&&(n[sh]=e),{error:wi,metadata:n}}function fe(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function Ri(t){return fe(t.input_tokens)!==0||fe(t.output_tokens)!==0||fe(t.cached_input_tokens)!==0||fe(t.cost_usd)!==0}function B(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}function mc(t){return {inputTokens:fe(t.inputTokens??0),outputTokens:fe(t.outputTokens??0),cachedInputTokens:fe(t.cachedInputTokens??0),costUsd:fe(t.costUsd??0)}}function wc(t){if(tn(t))return {inputTokens:fe(t.inputTokens),outputTokens:fe(t.outputTokens),cachedInputTokens:fe(t.cachedInputTokens),costUsd:fe(t.costUsd)}}function lr(t){if(!tn(t))return;let e=t.accounting;return e==="recorded"||e==="partial"||e==="unavailable"?e:void 0}function Si(t){return t.inputTokens!==0||t.outputTokens!==0||t.cachedInputTokens!==0||t.costUsd!==0}function uh(t){let e=lr(t);if(e==="recorded"||e==="partial")return true;if(e==="unavailable")return false;let n=wc(t);return n!==void 0&&Si(n)}function ch(t){return Object.values(t).some(e=>{let n=lr(e);return n==="partial"||n==="unavailable"})}function lh(t){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let n of Object.values(t)){if(lr(n)==="unavailable")continue;let r=wc(n);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function Ts(t,e,n){let r=Date.parse(t),s=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(s)?s-r:n??null}function Ti(t,e){if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return null;let n=Td(t,e);return n.status==="found"?new Date(n.startedAtMs).toISOString():null}function An(t,e){if(typeof t!="string"||t.length===0)throw new _("VALIDATION",`${e} is required`);return t}function Oi(t,e){let n=Date.parse(t);if(!Number.isFinite(n))throw new _("VALIDATION",`${e} is not a valid ISO time: ${t}`);return new Date(n).toISOString()}function _h(t,e){let n=An(e.workspaceId,"workspaceId"),r=An(e.taskId,"taskId"),s=e.rating;if(s!==null&&!Sc.includes(s))throw new _("VALIDATION","rating must be 'up', 'down' or null");let o=e.now===void 0?new Date().toISOString():Oi(e.now,"now");try{return t.transaction(i=>{let u=drizzleOrm.and(drizzleOrm.eq(a.id,r),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...en])),d=i.update(a).set({rating:s,rated_at:s===null?null:o}).where(drizzleOrm.and(u,drizzleOrm.sql`${a.rating} IS NOT ${s}`)).returning({rating:a.rating,ratedAt:a.rated_at}).all();if(d.length>0)return {taskId:r,rating:d[0].rating,ratedAt:d[0].ratedAt,changed:!0};let c=i.select({status:a.status,rating:a.rating,rated_at:a.rated_at}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,r),drizzleOrm.eq(a.workspace_id,n))).limit(1).get();if(!c)throw new fr("TASK_NOT_FOUND",r);if(!fh.has(c.status))throw new fr("TASK_RATING_NOT_TERMINAL",r);return {taskId:r,rating:c.rating,ratedAt:c.rated_at,changed:!1}},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to set task rating",i)}}function Ac(t){let e=drizzleOrm.sql`
101
120
  SELECT id, rated_at FROM tasks
102
121
  WHERE workspace_id = ${t.workspaceId}
103
122
  AND rating IS NOT NULL
@@ -107,27 +126,27 @@ ${r.join(`
107
126
  LIMIT ${t.limit}
108
127
  `;return drizzleOrm.sql`
109
128
  SELECT t.id AS taskId, t.agent_id AS agentId, t.thread_id AS threadId, t.status AS status,
110
- substr(t.error, 1, ${Rg}) AS errorHead,
129
+ substr(t.error, 1, ${ph}) AS errorHead,
111
130
  CASE WHEN json_valid(t.metadata) THEN json_extract(t.metadata, '$.terminalReason') END AS terminalReason,
112
131
  t.rating AS rating, t.rated_at AS ratedAt,
113
- NULLIF(substr(t.prompt, 1, ${mi}), '') AS promptExcerpt,
114
- NULLIF(substr(t.result, 1, ${mi}), '') AS resultExcerpt
132
+ NULLIF(substr(t.prompt, 1, ${Ai}), '') AS promptExcerpt,
133
+ NULLIF(substr(t.result, 1, ${Ai}), '') AS resultExcerpt
115
134
  FROM (${e}) AS page
116
135
  JOIN tasks t ON t.id = page.id
117
136
  ORDER BY page.rated_at DESC, page.id DESC
118
- `}function Ag(t,e){let n=In(e.workspaceId,"workspaceId");if(e.agentId!==void 0&&In(e.agentId,"agentId"),!Number.isFinite(e.limit)||Math.trunc(e.limit)<1)throw new _("VALIDATION","limit must be a positive integer");let r=Math.min(Math.trunc(e.limit),oc),s=e.sinceIso===void 0?void 0:ki(e.sinceIso,"sinceIso");try{return t.all(ic({workspaceId:n,agentId:e.agentId,sinceIso:s,limit:r})).map(i=>({taskId:i.taskId,agentId:i.agentId,threadId:i.threadId,status:xe({status:i.status,error:i.errorHead,metadata:i.terminalReason===null?null:JSON.stringify({terminalReason:i.terminalReason})}),rating:i.rating,ratedAt:i.ratedAt,promptExcerpt:i.promptExcerpt,resultExcerpt:i.resultExcerpt}))}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to list rated tasks",o)}}function ac(t){return drizzleOrm.sql`
137
+ `}function gh(t,e){let n=An(e.workspaceId,"workspaceId");if(e.agentId!==void 0&&An(e.agentId,"agentId"),!Number.isFinite(e.limit)||Math.trunc(e.limit)<1)throw new _("VALIDATION","limit must be a positive integer");let r=Math.min(Math.trunc(e.limit),Ic),s=e.sinceIso===void 0?void 0:Oi(e.sinceIso,"sinceIso");try{return t.all(Ac({workspaceId:n,agentId:e.agentId,sinceIso:s,limit:r})).map(i=>({taskId:i.taskId,agentId:i.agentId,threadId:i.threadId,status:De({status:i.status,error:i.errorHead,metadata:i.terminalReason===null?null:JSON.stringify({terminalReason:i.terminalReason})}),rating:i.rating,ratedAt:i.ratedAt,promptExcerpt:i.promptExcerpt,resultExcerpt:i.resultExcerpt}))}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to list rated tasks",o)}}function Oc(t){return drizzleOrm.sql`
119
138
  SELECT COUNT(*) AS total FROM tasks
120
139
  WHERE workspace_id = ${t.workspaceId}
121
140
  AND rating IS NOT NULL
122
141
  ${t.agentId!==void 0?drizzleOrm.sql`AND agent_id = ${t.agentId}`:drizzleOrm.sql``}
123
142
  ${t.sinceIso!==void 0?drizzleOrm.sql`AND rated_at >= ${t.sinceIso}`:drizzleOrm.sql``}
124
- `}function Og(t,e){let n=In(e.workspaceId,"workspaceId");e.agentId!==void 0&&In(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:ki(e.sinceIso,"sinceIso");try{return t.all(ac({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to count rated tasks",s)}}var ii,En,fg,Rn,Sn,_g,di,ir,He,pi,Zu,gg,mg,ec,hi,nc,rc,ur,sc,mi,oc,Rg,cr,Sg,ni=b(()=>{g();Tt();Dt();Pt();kt();Wt();Mr();Hr();rd();Fr();kd();yd();Mo();Zn();rr();ti();rr();Mr();ii=40,En="2026-05-09",fg="0.8.9-rc.13",Rn=10,Sn=parseInt(fg.split("rc.")[1]);_g=new Set(["workflow","mcp"]),di="usageByEpoch",ir="lateUsage",He="usageAccounting",pi="Stopped by user",Zu="Stopped by app shutdown",gg="terminalErrorOriginal";mg=["pending","running"];ec=new Set(["http","cli","instruction","workflow","internal"]);hi=600*1e3,nc=600*1e3,rc=300*1e3;ur=class extends Re{dbPath;clock;taskLogRepository;processControl;lastReaperTickAt;orphanReapInFlight;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),this.processControl=e.processControl??{},e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=he.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Br({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?Ct(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=he.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new _("NOT_FOUND","Database not found");let r=M(n);if(e)try{Pe(r.db,n);}catch(s){throw r.close(),s}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=F(e.runEpoch),s=r===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),s,drizzleOrm.eq(a.status,"running"))).run().changes>0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=F(o.run_epoch);if(o.status!=="running"){r={accepted:!1,status:o.status,runEpoch:i};return}let u=o.stop_requested_at!==null&&F(o.stop_requested_epoch)===i,d=u?o.stop_requested_at:e.requestedAt,c=oe(o.metadata),l=u?Tg(o.metadata)??ps({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):ps({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),Xu())).run().changes===0){let m=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:F(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:F(m.run_epoch),...m.stop_requested_at&&F(m.stop_requested_epoch)===F(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:o.status,runEpoch:i};let f=new Set([e.id]),h=(m,k)=>{if(k>=8)return;let E=s.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,m),drizzleOrm.eq(a.status,"running"))).all();for(let v of E)f.has(v.id)||(f.add(v.id),s.update(a).set({stop_requested_at:d,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...oe(v.metadata),stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,v.id),drizzleOrm.eq(a.status,"running"),Xu())).run(),h(v.id,k+1));};h(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=F(o.run_epoch),u=F(e.sourceRunEpoch),d=F(e.settleRunEpoch);if(o.status!=="running"||i!==d||e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId){r={accepted:!1,status:o.status,runEpoch:i};return}let c=d===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,d),l=drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.isNull(a.stop_requested_epoch),drizzleOrm.ne(a.stop_requested_epoch,u)),p=ps({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),f=JSON.stringify({...oe(o.metadata),stopRequest:p}),h=w=>s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:f}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,w,l)).returning({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).all(),k=(e.workspaceId===void 0?h():e.workspaceId===null?h(drizzleOrm.isNull(a.workspace_id)):h(drizzleOrm.eq(a.workspace_id,e.workspaceId)))[0];if(k){if(k.stop_requested_at===null||k.stop_requested_epoch===null||k.metadata===null)throw new Error("Instruction stop request write returned incomplete fields");r={accepted:!0,status:k.status,runEpoch:F(k.run_epoch),stopRequestReceipt:{taskId:k.id,workspaceId:k.workspace_id,sourceRunEpoch:u,settleRunEpoch:F(k.run_epoch),stopRequestedAt:k.stop_requested_at,stopRequestedEpoch:F(k.stop_requested_epoch),metadataBefore:o.metadata,metadataAfter:k.metadata}};return}let E=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!E||E.status!=="running"){r={accepted:!1,status:E?.status??"not_running",runEpoch:F(E?.run_epoch)};return}let v=F(E.run_epoch);r={accepted:!1,status:E.status,runEpoch:v,...E.stop_requested_at&&F(E.stop_requested_epoch)===u?{alreadyRequestedAt:E.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),s=!1;return n.db.transaction(o=>{let i=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||F(i.run_epoch)!==F(e.runEpoch))return;let u=i.stop_requested_at!==null&&F(i.stop_requested_epoch)===F(e.runEpoch),d=oe(i.metadata),c=u?ui(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...c.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??fs(i.started_at,r,void 0),f=i.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,i.run_epoch);s=o.update(a).set({status:"stopped",error:c.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),f)).run().changes>0;},{behavior:"immediate"}),s}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),s=F(e.expectedRunEpoch),o="not_running";return n.db.transaction(i=>{let u=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!u||u.status!=="running"){o="not_running";return}if(F(u.run_epoch)!==s){o="epoch_mismatch";return}if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId){o="workspace_mismatch";return}let c=u.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?drizzleOrm.isNull(a.workspace_id):drizzleOrm.eq(a.workspace_id,e.workspaceId),p={...oe(u.metadata),terminalReason:"runner_lost"},f=u.duration_ms??fs(u.started_at,r,void 0);o=i.update(a).set({status:"failed",error:Zu,completed_at:r,duration_ms:f,metadata:JSON.stringify(p)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),o}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return zu(this,e,n)}async stopTaskGenerationForInstruction(e){return ju({requestTaskStop:n=>this.requestTaskStopForInstruction(n),getTask:n=>this.getTask(n),finalizeTaskStop:n=>this.finalizeTaskStop(n)},e)}startTask(e){let n=this.openHandle(true);try{let r=e.actorKind==="human"&&typeof e.workspaceId=="string"&&e.workspaceId.length>0&&typeof e.actorId=="string"&&e.actorId.length>0,s=r?n.db.select({id:a.id}).from(a).where(drizzleOrm.eq(a.id,e.id)).get()!==void 0:!0,o={id:e.id,agent_id:e.agentId,actor_kind:e.actorKind??null,actor_id:e.actorId??null,user_id:e.userId??null,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,pid_started_at:ci(e.pid,this.processControl),parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workflow_run_id:Xa(e.metadata),schedule_id:nd(e.metadata),workspace_id:e.workspaceId??null,cwd:e.cwd??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,security_key:e.securityKey??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},i=u=>{n.db.insert(a).values(u).onConflictDoUpdate({target:a.id,set:{status:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:drizzleOrm.sql`COALESCE(excluded.pid, ${a.pid})`,pid_started_at:drizzleOrm.sql`CASE WHEN excluded.pid IS NULL THEN ${a.pid_started_at} ELSE excluded.pid_started_at END`,actor_kind:drizzleOrm.sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_kind ELSE ${a.actor_kind} END`,actor_id:drizzleOrm.sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_id ELSE ${a.actor_id} END`,command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workflow_run_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.workflow_run_id ELSE ${a.workflow_run_id} END`,schedule_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.schedule_id ELSE ${a.schedule_id} END`,workspace_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.workspace_id}, excluded.workspace_id) ELSE ${a.workspace_id} END`,cwd:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.project_id}, excluded.project_id) ELSE ${a.project_id} END`,crewx_version:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,security_key:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.security_key ELSE ${a.security_key} END`,coding_agent_command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.and(drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid)))}).run();};try{i(o);}catch(u){let d=u instanceof Error?u.message:typeof u=="object"&&u!==null&&"message"in u?String(u.message):String(u);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|pid_started_at|cwd|actor_kind|actor_id/i.test(d)||!/no such column|no column named/i.test(d))throw u;let c=new Set(n.db.all("PRAGMA table_info(tasks)").map(wr=>wr.name)),l=c.has("cwd"),p=c.has("user_id"),f=c.has("actor_kind"),h=c.has("actor_id"),m=c.has("log_storage"),k=l?", cwd":"",E=l?", ?":"",v=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",w=m?", log_storage":"",x=m?", ?":"",I=p?", user_id":"",O=p?", ?":"",S=f?", actor_kind":"",G=f?", ?":"",_e=h?", actor_id":"",ht=h?", ?":"",et=m?`,
143
+ `}function hh(t,e){let n=An(e.workspaceId,"workspaceId");e.agentId!==void 0&&An(e.agentId,"agentId");let r=e.sinceIso===void 0?void 0:Oi(e.sinceIso,"sinceIso");try{return t.all(Oc({workspaceId:n,agentId:e.agentId,sinceIso:r}))[0]?.total??0}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to count rated tasks",s)}}var gi,Rn,nh,Sn,In,rh,mi,ur,Fe,wi,Tc,sh,ih,yc,Ii,Ec,Rc,pr,Sc,Ai,Ic,ph,fr,fh,li=N(()=>{g();Et();$t();Ht();wt();zt();Ur();Fr();pd();Gr();Od();bd();jo();nr();ir();ci();ir();Ur();gi=40,Rn="2026-05-09",nh="0.8.9-rc.13",Sn=10,In=parseInt(nh.split("rc.")[1]);rh=new Set(["workflow","mcp"]),mi="usageByEpoch",ur="lateUsage",Fe="usageAccounting",wi="Stopped by user",Tc="Stopped by app shutdown",sh="terminalErrorOriginal";ih=["pending","running"];yc=new Set(["http","cli","instruction","workflow","internal"]);Ii=600*1e3,Ec=600*1e3,Rc=300*1e3;pr=class extends Se{dbPath;clock;taskLogRepository;processControl;lastReaperTickAt;orphanReapInFlight;pidNullObservedSince=new Map;constructor(e={}){super(),this.clock=e.clock??(()=>Date.now()),this.processControl=e.processControl??{},e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=me.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new jr({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?Mt(this.dbPath):super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=me.dirname(n);Ru.existsSync(s)||Ru.mkdirSync(s,{recursive:true});}else if(!Ru.existsSync(n))throw new _("NOT_FOUND","Database not found");let r=M(n);if(e)try{Me(r.db,n);}catch(s){throw r.close(),s}return r}heartbeatTask(e){let n=this.openHandle(true);try{let r=B(e.runEpoch),s=r===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,r);return n.db.update(a).set({heartbeat_at:new Date(this.clock()).toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),s,drizzleOrm.eq(a.status,"running"))).run().changes>0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to heartbeat task",r)}finally{n.close();}}requestTaskStop(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=B(o.run_epoch);if(o.status!=="running"){r={accepted:!1,status:o.status,runEpoch:i};return}let u=o.stop_requested_at!==null&&B(o.stop_requested_epoch)===i,d=u?o.stop_requested_at:e.requestedAt,c=oe(o.metadata),l=u?dh(o.metadata)??ks({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d):ks({origin:e.origin,at:d,callerPid:e.callerPid,callerTaskId:e.callerTaskId},d);if(s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...c,stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),hc())).run().changes===0){let m=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!m||m.status!=="running"){r={accepted:!1,status:m?.status??"not_running",runEpoch:B(m?.run_epoch)};return}r={accepted:!1,status:m.status,runEpoch:B(m.run_epoch),...m.stop_requested_at&&B(m.stop_requested_epoch)===B(m.run_epoch)?{alreadyRequestedAt:m.stop_requested_at}:{}};}else r={accepted:!0,status:o.status,runEpoch:i};let f=new Set([e.id]),h=(m,k)=>{if(k>=8)return;let E=s.select({id:a.id,status:a.status,metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,m),drizzleOrm.eq(a.status,"running"))).all();for(let v of E)f.has(v.id)||(f.add(v.id),s.update(a).set({stop_requested_at:d,stop_requested_epoch:drizzleOrm.sql`${a.run_epoch}`,metadata:JSON.stringify({...oe(v.metadata),stopRequest:l})}).where(drizzleOrm.and(drizzleOrm.eq(a.id,v.id),drizzleOrm.eq(a.status,"running"),hc())).run(),h(v.id,k+1));};h(e.id,0);},{behavior:"immediate"}),r}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to request task stop",r)}finally{n.close();}}requestTaskStopForInstruction(e){if(!this.dbExists())return {accepted:false,status:"not_running",runEpoch:0};let n=this.openHandle(true);try{let r={accepted:!1,status:"not_running",runEpoch:0};return n.db.transaction(s=>{let o=s.select({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!o)return;let i=B(o.run_epoch),u=B(e.sourceRunEpoch),d=B(e.settleRunEpoch);if(o.status!=="running"||i!==d||e.workspaceId!==void 0&&o.workspace_id!==e.workspaceId){r={accepted:!1,status:o.status,runEpoch:i};return}let c=d===0?drizzleOrm.or(drizzleOrm.eq(a.run_epoch,0),drizzleOrm.isNull(a.run_epoch)):drizzleOrm.eq(a.run_epoch,d),l=drizzleOrm.or(drizzleOrm.isNull(a.stop_requested_at),drizzleOrm.isNull(a.stop_requested_epoch),drizzleOrm.ne(a.stop_requested_epoch,u)),p=ks({origin:"instruction",at:e.requestedAt,callerPid:e.callerPid,callerTaskId:e.callerTaskId},e.requestedAt),f=JSON.stringify({...oe(o.metadata),stopRequest:p}),h=w=>s.update(a).set({stop_requested_at:e.requestedAt,stop_requested_epoch:u,metadata:f}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,w,l)).returning({id:a.id,status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,metadata:a.metadata}).all(),k=(e.workspaceId===void 0?h():e.workspaceId===null?h(drizzleOrm.isNull(a.workspace_id)):h(drizzleOrm.eq(a.workspace_id,e.workspaceId)))[0];if(k){if(k.stop_requested_at===null||k.stop_requested_epoch===null||k.metadata===null)throw new Error("Instruction stop request write returned incomplete fields");r={accepted:!0,status:k.status,runEpoch:B(k.run_epoch),stopRequestReceipt:{taskId:k.id,workspaceId:k.workspace_id,sourceRunEpoch:u,settleRunEpoch:B(k.run_epoch),stopRequestedAt:k.stop_requested_at,stopRequestedEpoch:B(k.stop_requested_epoch),metadataBefore:o.metadata,metadataAfter:k.metadata}};return}let E=s.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!E||E.status!=="running"){r={accepted:!1,status:E?.status??"not_running",runEpoch:B(E?.run_epoch)};return}let v=B(E.run_epoch);r={accepted:!1,status:E.status,runEpoch:v,...E.stop_requested_at&&B(E.stop_requested_epoch)===u?{alreadyRequestedAt:E.stop_requested_at}:{}};},{behavior:"immediate"}),r}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to request instruction task stop",r)}finally{n.close();}}finalizeTaskStop(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),s=!1;return n.db.transaction(o=>{let i=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i||i.status!=="running"||B(i.run_epoch)!==B(e.runEpoch))return;let u=i.stop_requested_at!==null&&B(i.stop_requested_epoch)===B(e.runEpoch),d=oe(i.metadata),c=u?ki(d,e.error):{error:e.error??null,metadata:e.terminalReason===void 0?{...d}:{...d,terminalReason:e.terminalReason}},l={...c.metadata,stopMethod:e.method},p=i.duration_ms??e.durationMs??Ts(i.started_at,r,void 0),f=i.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,i.run_epoch);s=o.update(a).set({status:"stopped",error:c.error,completed_at:r,duration_ms:p,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),f)).run().changes>0;},{behavior:"immediate"}),s}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to finalize task stop",r)}finally{n.close();}}finalizeTaskForHostShutdown(e){if(!this.dbExists())return "not_running";let n=this.openHandle(true);try{let r=e.completedAt??new Date(this.clock()).toISOString(),s=B(e.expectedRunEpoch),o="not_running";return n.db.transaction(i=>{let u=i.select({status:a.status,run_epoch:a.run_epoch,workspace_id:a.workspace_id,started_at:a.started_at,duration_ms:a.duration_ms,metadata:a.metadata}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!u||u.status!=="running"){o="not_running";return}if(B(u.run_epoch)!==s){o="epoch_mismatch";return}if(e.workspaceId!==void 0&&u.workspace_id!==e.workspaceId){o="workspace_mismatch";return}let c=u.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,u.run_epoch),l=e.workspaceId===void 0?void 0:e.workspaceId===null?drizzleOrm.isNull(a.workspace_id):drizzleOrm.eq(a.workspace_id,e.workspaceId),p={...oe(u.metadata),terminalReason:"runner_lost"},f=u.duration_ms??Ts(u.started_at,r,void 0);o=i.update(a).set({status:"failed",error:Tc,completed_at:r,duration_ms:f,metadata:JSON.stringify(p)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),c,l)).run().changes>0?"settled":"not_running";},{behavior:"immediate"}),o}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to finalize task for host shutdown",r)}finally{n.close();}}async stopTask(e,n={}){return fc(this,e,n)}async stopTaskGenerationForInstruction(e){return lc({requestTaskStop:n=>this.requestTaskStopForInstruction(n),getTask:n=>this.getTask(n),finalizeTaskStop:n=>this.finalizeTaskStop(n)},e)}startTask(e){let n=this.openHandle(true);try{let r=e.actorKind==="human"&&typeof e.workspaceId=="string"&&e.workspaceId.length>0&&typeof e.actorId=="string"&&e.actorId.length>0,s=r?n.db.select({id:a.id}).from(a).where(drizzleOrm.eq(a.id,e.id)).get()!==void 0:!0,o={id:e.id,agent_id:e.agentId,actor_kind:e.actorKind??null,actor_id:e.actorId??null,user_id:e.userId??null,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,pid_started_at:Ti(e.pid,this.processControl),parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workflow_run_id:od(e.metadata),schedule_id:ld(e.metadata),workspace_id:e.workspaceId??null,cwd:e.cwd??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,security_key:e.securityKey??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},i=u=>{n.db.insert(a).values(u).onConflictDoUpdate({target:a.id,set:{status:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN 'running' ELSE ${a.status} END`,pid:drizzleOrm.sql`COALESCE(excluded.pid, ${a.pid})`,pid_started_at:drizzleOrm.sql`CASE WHEN excluded.pid IS NULL THEN ${a.pid_started_at} ELSE excluded.pid_started_at END`,actor_kind:drizzleOrm.sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_kind ELSE ${a.actor_kind} END`,actor_id:drizzleOrm.sql`CASE WHEN ${a.status} IN ('pending', 'running') AND ${a.pid} IS NULL AND ${a.actor_kind} IS NULL AND COALESCE(${a.run_epoch}, 0) = 0 THEN excluded.actor_id ELSE ${a.actor_id} END`,command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.command ELSE ${a.command} END`,metadata:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.metadata ELSE ${a.metadata} END`,workflow_run_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.workflow_run_id ELSE ${a.workflow_run_id} END`,schedule_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.schedule_id ELSE ${a.schedule_id} END`,workspace_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.workspace_id}, excluded.workspace_id) ELSE ${a.workspace_id} END`,cwd:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.cwd}, excluded.cwd) ELSE ${a.cwd} END`,project_id:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN COALESCE(${a.project_id}, excluded.project_id) ELSE ${a.project_id} END`,crewx_version:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.crewx_version ELSE ${a.crewx_version} END`,model:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.model ELSE ${a.model} END`,rendered_prompt:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.rendered_prompt ELSE ${a.rendered_prompt} END`,security_key:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.security_key ELSE ${a.security_key} END`,coding_agent_command:drizzleOrm.sql`CASE WHEN ${a.status} = 'pending' AND ${a.pid} IS NULL THEN excluded.coding_agent_command ELSE ${a.coding_agent_command} END`},setWhere:drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.and(drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid)))}).run();};try{i(o);}catch(u){let d=u instanceof Error?u.message:typeof u=="object"&&u!==null&&"message"in u?String(u.message):String(u);if(!/log_storage|heartbeat_at|stop_requested_at|stop_requested_epoch|pid_started_at|cwd|actor_kind|actor_id/i.test(d)||!/no such column|no column named/i.test(d))throw u;let c=new Set(n.db.all("PRAGMA table_info(tasks)").map(Sr=>Sr.name)),l=c.has("cwd"),p=c.has("user_id"),f=c.has("actor_kind"),h=c.has("actor_id"),m=c.has("log_storage"),k=l?", cwd":"",E=l?", ?":"",v=l?", cwd = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN COALESCE(tasks.cwd, excluded.cwd) ELSE tasks.cwd END":"",w=m?", log_storage":"",x=m?", ?":"",I=p?", user_id":"",O=p?", ?":"",S=f?", actor_kind":"",j=f?", ?":"",ge=h?", actor_id":"",Tt=h?", ?":"",rt=m?`,
125
144
  log_storage = CASE WHEN tasks.status = 'pending' THEN excluded.log_storage ELSE tasks.log_storage END`:"";n.runRaw(`INSERT INTO tasks (
126
145
  id, agent_id, prompt, mode, status, started_at, pid,
127
146
  parent_task_id, caller_agent_id, trace_id, command, metadata,
128
147
  workspace_id${k}, project_id, platform, crewx_version, thread_id,
129
- model, rendered_prompt, coding_agent_command${I}${S}${_e}${w}
130
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${E}${O}${G}${ht}${x})
148
+ model, rendered_prompt, coding_agent_command${I}${S}${ge}${w}
149
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${E}${O}${j}${Tt}${x})
131
150
  ON CONFLICT(id) DO UPDATE SET
132
151
  status = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN 'running' ELSE tasks.status END,
133
152
  pid = COALESCE(excluded.pid, tasks.pid),
@@ -138,10 +157,10 @@ ${r.join(`
138
157
  crewx_version = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.crewx_version ELSE tasks.crewx_version END,
139
158
  model = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.model ELSE tasks.model END,
140
159
  rendered_prompt = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.rendered_prompt ELSE tasks.rendered_prompt END,
141
- coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${et}
142
- WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[o.id,o.agent_id,o.prompt,o.mode,o.status,o.started_at,o.pid,o.parent_task_id,o.caller_agent_id,o.trace_id,o.command,o.metadata,o.workspace_id,...l?[o.cwd]:[],o.project_id,o.platform,o.crewx_version,o.thread_id,o.model,o.rendered_prompt,o.coding_agent_command,...p?[o.user_id]:[],...f?[o.actor_kind]:[],...h?[o.actor_id]:[],...m?[o.log_storage]:[]]);}r&&!s&&new Wr({dbPath:this.resolveDbPath()}).recordAccepted({workspaceId:e.workspaceId,actorId:e.actorId,actorKind:e.actorKind,agentId:e.agentId});}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to start task",r)}finally{n.close();}}recordTaskPid(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:a.status,run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||F(r.run_epoch)!==F(e.runEpoch))return !1;let s=r.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,r.run_epoch);return n.db.update(a).set({pid:e.pid,pid_started_at:ci(e.pid,this.processControl)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),s)).run().changes>0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to record task pid",r)}finally{n.close();}}updateTaskOwnership(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:a.status,run_epoch:a.run_epoch,metadata:a.metadata,model:a.model,rendered_prompt:a.rendered_prompt,security_key:a.security_key,coding_agent_command:a.coding_agent_command}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||F(r.run_epoch)!==F(e.runEpoch))return !1;let s=kg(r.metadata,e.runtime?.metadata);if(s.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0){s.providerPid=e.providerPid;let u=ci(e.providerPid,this.processControl);u!==null?s.providerPidStartedAt=u:delete s.providerPidStartedAt;}let o=r.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,r.run_epoch),i=n.db.update(a).set({metadata:JSON.stringify(s),model:ls(r.model,e.runtime?.model),rendered_prompt:ls(r.rendered_prompt,e.runtime?.renderedPrompt),security_key:ls(r.security_key,e.runtime?.securityKey),coding_agent_command:ls(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o)).run();return i.changes>0&&F(e.runEpoch)>0&&n.db.update(a).set({stop_requested_at:null,stop_requested_epoch:null}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o,drizzleOrm.sql`${a.stop_requested_at} IS NOT NULL
143
- AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(a).set({status:"running"}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid))).run().changes===1}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let s=this.openHandle(true);try{return s.db.update(a).set({status:"failed",error:n,completed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes>0}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to fail pending task",o)}finally{s.close();}}stopPendingTask(e,n,r=new Date().toISOString(),s={}){let o=this.openHandle(true);try{let i=!1;return o.db.transaction(u=>{let d=u.select({metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).limit(1).get();if(!d)return;let c=ui(oe(d.metadata),n),l={...c.metadata,stopMethod:"cooperative",stopRequest:ps(s,r)};i=u.update(a).set({status:"stopped",error:c.error,completed_at:r,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes===1;},{behavior:"immediate"}),i}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to stop pending task",i)}finally{o.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select(re).from(a).where(drizzleOrm.eq(a.project_id,e)).orderBy(drizzleOrm.desc(a.started_at)).all().map(Ve)}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true),r,s;try{n.db.transaction(o=>{let i=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,result:a.result,exit_code:a.exit_code,error:a.error,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i)return;let u=F(i.run_epoch),d=F(e.runEpoch),c=i.status==="running"&&u===d,l=i.stop_requested_at!==null&&F(i.stop_requested_epoch)===u,p=c&&l,f=i.status==="stopped"&&u===d&&l,h=oe(i.metadata),m=en(h[ir])?h[ir]:{},k=String(d),E=hg(i),v=E&&u===d&&!_i(i)&&!Object.prototype.hasOwnProperty.call(m,k),w=E&&u===d&&!Object.prototype.hasOwnProperty.call(m,k),x=u>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||e.usageComplete!==void 0||u!==d,I={},O;if(i.status!=="running"&&(r=i.status,s=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),x&&(i.status==="running"||w)){O=oe(i.metadata);let S=en(O[di])?{...O[di]}:{},G=String(d),_e=Yu(e),ht=dr(S[G]);e.usageComplete!==void 0?S[G]={..._e,accounting:e.usagePresent===!0?e.usageComplete?"recorded":"partial":"unavailable"}:ht!==void 0?S[G]={..._e,accounting:ht}:S[G]=_e,O[di]=S;let et=Eg(S),wr=gi(et),Mc=Object.values(S).some(yg),$c=Object.values(S).some(Hc=>dr(Hc)!==void 0);e.usageComplete!==void 0||$c?(O[He]=Mc?"recorded":"unavailable",wg(S)?O.usageIncomplete=!0:delete O.usageIncomplete):wr&&h[He]==="unavailable"?O[He]="recorded":i.status!=="running"&&!wr&&h[He]===void 0&&(O[He]="unavailable"),I.metadata=JSON.stringify(O),I.input_tokens=et.inputTokens,I.output_tokens=et.outputTokens,I.cached_input_tokens=et.cachedInputTokens,I.cost_usd=et.costUsd;}else if(c||v)if(c)I.input_tokens=pe(e.inputTokens??0),I.output_tokens=pe(e.outputTokens??0),I.cached_input_tokens=pe(e.cachedInputTokens??0),I.cost_usd=pe(e.costUsd??0);else {let S=Yu(e),G=e.usageComplete!==void 0?e.usagePresent===!0:gi(S);G&&(I.input_tokens=S.inputTokens,I.output_tokens=S.outputTokens,I.cached_input_tokens=S.cachedInputTokens,I.cost_usd=S.costUsd),O={...h};let _e=en(h[ir])?{...h[ir]}:{};_e[k]={at:e.completedAt},O[ir]=_e,O[He]===void 0?O[He]=G?"recorded":"unavailable":G&&O[He]==="unavailable"&&(O[He]="recorded"),I.metadata=JSON.stringify(O);}if((c||v)&&e.model!==void 0&&e.model!==null&&(!v||i.model===null)&&(I.model=e.model),p){O??=oe(i.metadata);let S=ui(O,e.error);O={...S.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:us(i.stop_requested_at,e.completedAt)},I.status="stopped",I.result=e.result??i.result,I.error=S.error,I.completed_at=e.completedAt,I.duration_ms=i.duration_ms??e.durationMs??fs(i.started_at,e.completedAt,void 0),I.exit_code=e.exitCode??i.exit_code,I.metadata=JSON.stringify(O);}else if(c)e.partialResultRecovered===!0&&(O??=oe(i.metadata),O.partialResultRecovered=!0,I.metadata=JSON.stringify(O)),I.status=e.status,I.result=e.result??null,I.error=e.error??null,I.completed_at=e.completedAt,I.duration_ms=u>0?fs(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,I.exit_code=e.exitCode??null;else if(f){let S=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(I.result=e.result,S=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(I.exit_code=e.exitCode),e.partialResultRecovered===!0&&(O??=oe(i.metadata),O.partialResultRecovered=!0,I.metadata=JSON.stringify(O)),S&&(r=void 0,s=void 0);}Object.keys(I).length>0&&o.update(a).set(I).where(drizzleOrm.eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to finish task",o)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:s??`task:end status=${e.status}`});}catch(o){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${o instanceof Error?o.message:String(o)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
144
- `);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.workspace_id,e.workspaceId)),s={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let o=n.db.select({metadata:a.metadata}).from(a).where(r).limit(1).get(),i=oe(o?.metadata??null);i.terminalReason=e.terminalReason,s.metadata=JSON.stringify(i);}n.db.update(a).set(s).where(r).run();}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to update task lifecycle",r)}finally{n.close();}}appendLog(e,n){this.taskLogRepository.appendLog(e,n);}appendLogs(e,n){this.taskLogRepository.appendLogs(e,n);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,n){return this.taskLogRepository.readLogsTail(e,n)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(re).from(a).where(drizzleOrm.eq(a.status,"running")).orderBy(drizzleOrm.desc(a.started_at)).all().map(Ve)}catch(n){throw new _("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getActiveTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(re).from(a).where(drizzleOrm.inArray(a.status,["pending","running"])).orderBy(drizzleOrm.desc(a.started_at)).all().map(Ve)}catch(n){throw new _("DB_ERROR","Failed to get active tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(re).from(a).orderBy(drizzleOrm.desc(a.started_at)).limit(100).all().map(Ve)}catch(n){throw new _("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}readTaskSecurityKey(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({security_key:a.security_key}).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get()?.security_key??null}catch(r){throw new _("DB_ERROR","Failed to read task security key",r)}finally{n.close();}}recordProviderInput(e){if(!this.dbExists())return false;let n=F(e.runEpoch);if(n===0&&e.interceptedRequest!==true)return false;let r=e.recordedAt??new Date(this.clock()).toISOString(),s=this.openHandle(true);try{let o=!1;return s.db.transaction(i=>{let u=i.select({run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!u||F(u.run_epoch)!==n)return;o=i.insert(lt).values({task_id:e.id,run_epoch:n,input:e.input,key_wrap_skipped:e.keyWrapSkipped?1:0,recorded_at:r}).onConflictDoNothing().run().changes>0;}),o}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to record provider input",o)}finally{s.close();}}listProviderInputEpochs(e,n={}){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=r.db.select({run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();if(!s)return [];let o=F(s.run_epoch),i=r.db.select({run_epoch:lt.run_epoch,key_wrap_skipped:lt.key_wrap_skipped}).from(lt).where(drizzleOrm.eq(lt.task_id,e)).all(),u=new Map(i.map(c=>[c.run_epoch,c])),d=[];for(let c=1;c<=o;c++){let l=u.get(c);l?d.push({runEpoch:c,available:!0,...l.key_wrap_skipped===1?{keyWrapSkipped:!0}:{}}):d.push({runEpoch:c,available:!1,reason:n.archivedRunEpochs?.has(c)?"pruned":"absent"});}return d}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to list provider inputs",s)}finally{r.close();}}readProviderInput(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let s=r.db.select().from(lt).where(drizzleOrm.and(drizzleOrm.eq(lt.task_id,e),drizzleOrm.eq(lt.run_epoch,F(n)))).limit(1).get();return s?{runEpoch:s.run_epoch,input:s.input,keyWrapSkipped:s.key_wrap_skipped===1,recordedAt:s.recorded_at}:void 0}catch(s){throw new _("DB_ERROR","Failed to read provider input",s)}finally{r.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select(re).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();return r?Ve(r):void 0}catch(r){throw new _("DB_ERROR","Failed to get task",r)}finally{n.close();}}async killTask(e){let n=await this.stopTask(e);return n.status==="stopped"?{status:"terminated",killed:n.method==="forced"||n.method==="cooperative",...n.pid?{pid:n.pid}:{}}:n.status==="not_running"?{status:"not_running",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}:{status:"failed",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}}reapOrphanedTasks(e={}){return this.orphanReapInFlight===void 0&&(this.orphanReapInFlight=this.runOrphanReaperPass(e).finally(()=>{this.orphanReapInFlight=void 0;})),this.orphanReapInFlight}async runOrphanReaperPass(e){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=n.db.select({id:a.id,status:a.status,pid:a.pid,pid_started_at:a.pid_started_at,platform:a.platform,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at,started_at:a.started_at,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.status,"pending"))).all(),s=this.clock(),o=Math.max(1,Math.trunc(e.tickIntervalMs??rc)),i=this.lastReaperTickAt,u=i===void 0?Number.POSITIVE_INFINITY:s-i,d=i!==void 0&&u>=0&&u<=o*2;this.lastReaperTickAt=s;let c=wn(),l=as(),p=new Date(s-nc).toISOString(),f=new Date(s).toISOString(),h=new Set,m=[],k=0,E=(w,x)=>{let I=oe(fi(w.metadata,"runner_lost")),O=typeof I.provider=="string"?I.provider:void 0,S;try{S=os({taskLogRepository:this.taskLogRepository,taskId:w.id,provider:O,model:w.model})?.usage;}catch{}let G={status:"failed",error:x,completed_at:f};S?(G.input_tokens=S.inputTokens,G.output_tokens=S.outputTokens,G.cached_input_tokens=S.cachedInputTokens,G.cost_usd=S.costUsd,w.model===null&&S.model!==null&&(G.model=S.model),I[He]="recorded"):!_i(w)&&I[He]!=="recorded"&&(I[He]="unavailable"),G.metadata=JSON.stringify(I);let _e=w.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,w.run_epoch),ht=w.heartbeat_at===null?drizzleOrm.isNull(a.heartbeat_at):drizzleOrm.eq(a.heartbeat_at,w.heartbeat_at),et=n.db.update(a).set(G).where(drizzleOrm.and(drizzleOrm.eq(a.id,w.id),drizzleOrm.eq(a.status,"running"),_e,ht)).run();return et.changes>0&&k++,et.changes>0};for(let w of r){if(w.status==="pending"){if(w.pid!==null||w.started_at>=p)continue;let S=fi(w.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:f,metadata:S}).where(drizzleOrm.and(drizzleOrm.eq(a.id,w.id),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,p))).run().changes>0&&k++;continue}if(_g.has(w.platform??"cli"))continue;if(w.pid===null){let S=`${w.id}:${w.run_epoch??0}`;h.add(S);let G=this.pidNullObservedSince.get(S);if(G===void 0){this.pidNullObservedSince.set(S,s);continue}s-G>=hi&&E(w,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(S);continue}if(w.heartbeat_at===null){Rt(w.pid,this.processControl.kill)==="not_found"&&E(w,"Reaped: process not found (orphaned task)");continue}let x=Date.parse(w.heartbeat_at),I=Number.isFinite(x)?s-x:Number.POSITIVE_INFINITY;if(I<=c)continue;let O=Qo(w).filter(S=>Rt(S.pid,this.processControl.kill)!=="not_found");O.length===0?E(w,"Reaped: process not found (orphaned task)"):I>l&&d&&m.push({row:w,targets:O});}let v=new Map;for(let w of m){let{row:x,targets:I}=w,O=n.db.select({status:a.status,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at}).from(a).where(drizzleOrm.eq(a.id,x.id)).get();if(!O||O.status!=="running"||F(O.run_epoch)!==F(x.run_epoch)||O.heartbeat_at!==x.heartbeat_at)continue;let S=await this.judgeRecordedTargets(x,I);if(S.unproven!==void 0){console.warn("[crewx] reaper left running task",{taskId:x.id,reason:S.unproven});continue}if(S.owned.length>0){let G=await this.terminateRecordedProcesses(S.owned,v);if(G!==void 0){console.warn("[crewx] reaper left running task",{taskId:x.id,reason:G});continue}}E(x,"Reaped: heartbeat stale beyond hard limit (orphaned task)")&&S.reused.length>0&&console.warn("[crewx] reaper reaped task whose recorded pid was reused",{taskId:x.id,reason:S.reused.join("; ")});}for(let w of Array.from(this.pidNullObservedSince.keys()))h.has(w)||this.pidNullObservedSince.delete(w);return k}finally{n.close();}}async judgeRecordedTargets(e,n){let r=e.heartbeat_at===null?Number.NaN:Date.parse(e.heartbeat_at),s=Number.isFinite(r)?r+tr()+qr:void 0,o=[],i=[];for(let u of n){let d=await Zo(u,{processControlOptions:this.processControl,legacyStartBoundaryMs:s});if(d.verdict==="owned")o.push(u);else if(d.verdict==="reused")i.push(`pid ${u.pid} reused (${d.reason})`);else return {owned:o,reused:i,unproven:`pid ${u.pid} not proven owned (${d.ownership}): ${d.reason}`}}return {owned:o,reused:i}}async terminateRecordedProcesses(e,n){for(let r of e){if(!n.has(r.pid)){let s;try{s=(await It(r.pid,{...this.processControl,signal:St})).status==="failed"?"failed":"terminated";}catch{s="failed";}n.set(r.pid,s);}if(n.get(r.pid)==="failed")return `pid ${r.pid} termination not confirmed`;if(Rt(r.pid,this.processControl.kill)!=="not_found")return `pid ${r.pid} still alive after termination`}}reapRunningWorkflowTasks(e=hi){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),s=drizzleOrm.and(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,r),drizzleOrm.or(drizzleOrm.isNull(a.metadata),Vu())),o=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(s).all(),i=new Date().toISOString(),u=0;for(let d of o){let c=oe(d.metadata);c.terminalReason="runner_lost";let l=n.db.update(a).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:i,metadata:JSON.stringify(c)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,d.id),drizzleOrm.eq(a.status,"running"))).run();u+=l.changes??0;}return u}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=M(s);try{let i=n?drizzleOrm.eq(a.workspace_id,n):void 0,u=i?drizzleOrm.and(drizzleOrm.eq(a.id,e),i):drizzleOrm.eq(a.id,e),d=o.db.select(re).from(a).where(u).limit(1).get()??void 0;if(!d){let c=i?drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),i):drizzleOrm.eq(a.thread_id,e);d=o.db.select(re).from(a).where(c).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??void 0;}if(d)return Ve(d)}catch(i){throw new _("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!fs$1.existsSync(i))continue;let u=M(i);try{let d=n?drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,e),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.eq(a.parent_task_id,e),c=u.db.select(re).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(Ve(l)));}catch(d){throw new _("DB_ERROR","Failed to find child tasks",d)}finally{u.close();}}return o}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?drizzleOrm.sql`
160
+ coding_agent_command = CASE WHEN tasks.status = 'pending' AND tasks.pid IS NULL THEN excluded.coding_agent_command ELSE tasks.coding_agent_command END${rt}
161
+ WHERE tasks.status = 'running' OR (tasks.status = 'pending' AND tasks.pid IS NULL)`,[o.id,o.agent_id,o.prompt,o.mode,o.status,o.started_at,o.pid,o.parent_task_id,o.caller_agent_id,o.trace_id,o.command,o.metadata,o.workspace_id,...l?[o.cwd]:[],o.project_id,o.platform,o.crewx_version,o.thread_id,o.model,o.rendered_prompt,o.coding_agent_command,...p?[o.user_id]:[],...f?[o.actor_kind]:[],...h?[o.actor_id]:[],...m?[o.log_storage]:[]]);}r&&!s&&new Kr({dbPath:this.resolveDbPath()}).recordAccepted({workspaceId:e.workspaceId,actorId:e.actorId,actorKind:e.actorKind,agentId:e.agentId});}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to start task",r)}finally{n.close();}}recordTaskPid(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:a.status,run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||B(r.run_epoch)!==B(e.runEpoch))return !1;let s=r.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,r.run_epoch);return n.db.update(a).set({pid:e.pid,pid_started_at:Ti(e.pid,this.processControl)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),s)).run().changes>0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to record task pid",r)}finally{n.close();}}updateTaskOwnership(e){if(!this.dbExists())return false;let n=this.openHandle(true);try{let r=n.db.select({status:a.status,run_epoch:a.run_epoch,metadata:a.metadata,model:a.model,rendered_prompt:a.rendered_prompt,security_key:a.security_key,coding_agent_command:a.coding_agent_command}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!r||r.status!=="running"||B(r.run_epoch)!==B(e.runEpoch))return !1;let s=ah(r.metadata,e.runtime?.metadata);if(s.ownership=e.ownership,e.ownership==="runner"&&e.providerPid!==void 0){s.providerPid=e.providerPid;let u=Ti(e.providerPid,this.processControl);u!==null?s.providerPidStartedAt=u:delete s.providerPidStartedAt;}let o=r.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,r.run_epoch),i=n.db.update(a).set({metadata:JSON.stringify(s),model:ms(r.model,e.runtime?.model),rendered_prompt:ms(r.rendered_prompt,e.runtime?.renderedPrompt),security_key:ms(r.security_key,e.runtime?.securityKey),coding_agent_command:ms(r.coding_agent_command,e.runtime?.codingAgentCommand)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o)).run();return i.changes>0&&B(e.runEpoch)>0&&n.db.update(a).set({stop_requested_at:null,stop_requested_epoch:null}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.status,"running"),o,drizzleOrm.sql`${a.stop_requested_at} IS NOT NULL
162
+ AND COALESCE(${a.stop_requested_epoch}, 0) <> COALESCE(${a.run_epoch}, 0)`)).run(),i.changes>0}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to update task ownership",r)}finally{n.close();}}adoptPendingTask(e){let n=this.openHandle(true);try{return n.db.update(a).set({status:"running"}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid))).run().changes===1}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to adopt pending task",r)}finally{n.close();}}failPendingTask(e,n,r=new Date().toISOString()){let s=this.openHandle(true);try{return s.db.update(a).set({status:"failed",error:n,completed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes>0}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to fail pending task",o)}finally{s.close();}}stopPendingTask(e,n,r=new Date().toISOString(),s={}){let o=this.openHandle(true);try{let i=!1;return o.db.transaction(u=>{let d=u.select({metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).limit(1).get();if(!d)return;let c=ki(oe(d.metadata),n),l={...c.metadata,stopMethod:"cooperative",stopRequest:ks(s,r)};i=u.update(a).set({status:"stopped",error:c.error,completed_at:r,metadata:JSON.stringify(l)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"pending"))).run().changes===1;},{behavior:"immediate"}),i}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to stop pending task",i)}finally{o.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select(re).from(a).where(drizzleOrm.eq(a.project_id,e)).orderBy(drizzleOrm.desc(a.started_at)).all().map(Qe)}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to list tasks by project",r)}finally{n.close();}}finishTask(e){let n=this.openHandle(true),r,s;try{n.db.transaction(o=>{let i=o.select({status:a.status,run_epoch:a.run_epoch,stop_requested_at:a.stop_requested_at,stop_requested_epoch:a.stop_requested_epoch,started_at:a.started_at,duration_ms:a.duration_ms,result:a.result,exit_code:a.exit_code,error:a.error,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!i)return;let u=B(i.run_epoch),d=B(e.runEpoch),c=i.status==="running"&&u===d,l=i.stop_requested_at!==null&&B(i.stop_requested_epoch)===u,p=c&&l,f=i.status==="stopped"&&u===d&&l,h=oe(i.metadata),m=tn(h[ur])?h[ur]:{},k=String(d),E=oh(i),v=E&&u===d&&!Ri(i)&&!Object.prototype.hasOwnProperty.call(m,k),w=E&&u===d&&!Object.prototype.hasOwnProperty.call(m,k),x=u>0||d>0||e.runEpoch!==void 0&&e.runEpoch!==null||e.usageComplete!==void 0||u!==d,I={},O;if(i.status!=="running"&&(r=i.status,s=e.result?.trim()||e.error?.trim()||`task:end status=${e.status}`),x&&(i.status==="running"||w)){O=oe(i.metadata);let S=tn(O[mi])?{...O[mi]}:{},j=String(d),ge=mc(e),Tt=lr(S[j]);e.usageComplete!==void 0?S[j]={...ge,accounting:e.usagePresent===!0?e.usageComplete?"recorded":"partial":"unavailable"}:Tt!==void 0?S[j]={...ge,accounting:Tt}:S[j]=ge,O[mi]=S;let rt=lh(S),Sr=Si(rt),nl=Object.values(S).some(uh),rl=Object.values(S).some(sl=>lr(sl)!==void 0);e.usageComplete!==void 0||rl?(O[Fe]=nl?"recorded":"unavailable",ch(S)?O.usageIncomplete=!0:delete O.usageIncomplete):Sr&&h[Fe]==="unavailable"?O[Fe]="recorded":i.status!=="running"&&!Sr&&h[Fe]===void 0&&(O[Fe]="unavailable"),I.metadata=JSON.stringify(O),I.input_tokens=rt.inputTokens,I.output_tokens=rt.outputTokens,I.cached_input_tokens=rt.cachedInputTokens,I.cost_usd=rt.costUsd;}else if(c||v)if(c)I.input_tokens=fe(e.inputTokens??0),I.output_tokens=fe(e.outputTokens??0),I.cached_input_tokens=fe(e.cachedInputTokens??0),I.cost_usd=fe(e.costUsd??0);else {let S=mc(e),j=e.usageComplete!==void 0?e.usagePresent===!0:Si(S);j&&(I.input_tokens=S.inputTokens,I.output_tokens=S.outputTokens,I.cached_input_tokens=S.cachedInputTokens,I.cost_usd=S.costUsd),O={...h};let ge=tn(h[ur])?{...h[ur]}:{};ge[k]={at:e.completedAt},O[ur]=ge,O[Fe]===void 0?O[Fe]=j?"recorded":"unavailable":j&&O[Fe]==="unavailable"&&(O[Fe]="recorded"),I.metadata=JSON.stringify(O);}if((c||v)&&e.model!==void 0&&e.model!==null&&(!v||i.model===null)&&(I.model=e.model),p){O??=oe(i.metadata);let S=ki(O,e.error);O={...S.metadata,...e.partialResultRecovered===!0?{partialResultRecovered:!0}:{},stopMethod:gs(i.stop_requested_at,e.completedAt)},I.status="stopped",I.result=e.result??i.result,I.error=S.error,I.completed_at=e.completedAt,I.duration_ms=i.duration_ms??e.durationMs??Ts(i.started_at,e.completedAt,void 0),I.exit_code=e.exitCode??i.exit_code,I.metadata=JSON.stringify(O);}else if(c)e.partialResultRecovered===!0&&(O??=oe(i.metadata),O.partialResultRecovered=!0,I.metadata=JSON.stringify(O)),I.status=e.status,I.result=e.result??null,I.error=e.error??null,I.completed_at=e.completedAt,I.duration_ms=u>0?Ts(i.started_at,e.completedAt,e.durationMs):e.durationMs??null,I.exit_code=e.exitCode??null;else if(f){let S=!1;i.result===null&&e.result!==void 0&&e.result!==null&&(I.result=e.result,S=!0),i.exit_code===null&&e.exitCode!==void 0&&e.exitCode!==null&&(I.exit_code=e.exitCode),e.partialResultRecovered===!0&&(O??=oe(i.metadata),O.partialResultRecovered=!0,I.metadata=JSON.stringify(O)),S&&(r=void 0,s=void 0);}Object.keys(I).length>0&&o.update(a).set(I).where(drizzleOrm.eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to finish task",o)}finally{n.close();}if(r!==void 0){try{this.taskLogRepository.appendLog(e.id,{timestamp:e.completedAt,level:"late-result",message:s??`task:end status=${e.status}`});}catch(o){console.error(`[crewx] failed to preserve late task result for ${e.id}: ${o instanceof Error?o.message:String(o)}`);}process.stderr.write(`Task ${e.id} was already finalized (${r}); late result kept in task log
163
+ `);}}updateTaskLifecycle(e){let n=this.openHandle(true);try{let r=drizzleOrm.and(drizzleOrm.eq(a.id,e.id),drizzleOrm.eq(a.workspace_id,e.workspaceId)),s={status:e.status,error:e.error,completed_at:e.completedAt,duration_ms:e.durationMs};if(e.terminalReason){let o=n.db.select({metadata:a.metadata}).from(a).where(r).limit(1).get(),i=oe(o?.metadata??null);i.terminalReason=e.terminalReason,s.metadata=JSON.stringify(i);}n.db.update(a).set(s).where(r).run();}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to update task lifecycle",r)}finally{n.close();}}appendLog(e,n){this.taskLogRepository.appendLog(e,n);}appendLogs(e,n){this.taskLogRepository.appendLogs(e,n);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,n){return this.taskLogRepository.readLogsTail(e,n)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(re).from(a).where(drizzleOrm.eq(a.status,"running")).orderBy(drizzleOrm.desc(a.started_at)).all().map(Qe)}catch(n){throw new _("DB_ERROR","Failed to get running tasks",n)}finally{e.close();}}getActiveTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(re).from(a).where(drizzleOrm.inArray(a.status,["pending","running"])).orderBy(drizzleOrm.desc(a.started_at)).all().map(Qe)}catch(n){throw new _("DB_ERROR","Failed to get active tasks",n)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select(re).from(a).orderBy(drizzleOrm.desc(a.started_at)).limit(100).all().map(Qe)}catch(n){throw new _("DB_ERROR","Failed to get all tasks",n)}finally{e.close();}}readTaskSecurityKey(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({security_key:a.security_key}).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get()?.security_key??null}catch(r){throw new _("DB_ERROR","Failed to read task security key",r)}finally{n.close();}}recordProviderInput(e){if(!this.dbExists())return false;let n=B(e.runEpoch);if(n===0&&e.interceptedRequest!==true)return false;let r=e.recordedAt??new Date(this.clock()).toISOString(),s=this.openHandle(true);try{let o=!1;return s.db.transaction(i=>{let u=i.select({run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e.id)).limit(1).get();if(!u||B(u.run_epoch)!==n)return;o=i.insert(_t).values({task_id:e.id,run_epoch:n,input:e.input,key_wrap_skipped:e.keyWrapSkipped?1:0,recorded_at:r}).onConflictDoNothing().run().changes>0;}),o}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to record provider input",o)}finally{s.close();}}listProviderInputEpochs(e,n={}){if(!this.dbExists())return [];let r=this.openHandle(false);try{let s=r.db.select({run_epoch:a.run_epoch}).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();if(!s)return [];let o=B(s.run_epoch),i=r.db.select({run_epoch:_t.run_epoch,key_wrap_skipped:_t.key_wrap_skipped}).from(_t).where(drizzleOrm.eq(_t.task_id,e)).all(),u=new Map(i.map(c=>[c.run_epoch,c])),d=[];for(let c=1;c<=o;c++){let l=u.get(c);l?d.push({runEpoch:c,available:!0,...l.key_wrap_skipped===1?{keyWrapSkipped:!0}:{}}):d.push({runEpoch:c,available:!1,reason:n.archivedRunEpochs?.has(c)?"pruned":"absent"});}return d}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to list provider inputs",s)}finally{r.close();}}readProviderInput(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let s=r.db.select().from(_t).where(drizzleOrm.and(drizzleOrm.eq(_t.task_id,e),drizzleOrm.eq(_t.run_epoch,B(n)))).limit(1).get();return s?{runEpoch:s.run_epoch,input:s.input,keyWrapSkipped:s.key_wrap_skipped===1,recordedAt:s.recorded_at}:void 0}catch(s){throw new _("DB_ERROR","Failed to read provider input",s)}finally{r.close();}}getTask(e){if(!this.dbExists())return;let n=this.openHandle(false);try{let r=n.db.select(re).from(a).where(drizzleOrm.eq(a.id,e)).limit(1).get();return r?Qe(r):void 0}catch(r){throw new _("DB_ERROR","Failed to get task",r)}finally{n.close();}}async killTask(e){let n=await this.stopTask(e);return n.status==="stopped"?{status:"terminated",killed:n.method==="forced"||n.method==="cooperative",...n.pid?{pid:n.pid}:{}}:n.status==="not_running"?{status:"not_running",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}:{status:"failed",killed:false,...n.pid?{pid:n.pid}:{},...n.error?{error:n.error}:{}}}reapOrphanedTasks(e={}){return this.orphanReapInFlight===void 0&&(this.orphanReapInFlight=this.runOrphanReaperPass(e).finally(()=>{this.orphanReapInFlight=void 0;})),this.orphanReapInFlight}async runOrphanReaperPass(e){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=n.db.select({id:a.id,status:a.status,pid:a.pid,pid_started_at:a.pid_started_at,platform:a.platform,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at,started_at:a.started_at,metadata:a.metadata,model:a.model,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cached_input_tokens:a.cached_input_tokens,cost_usd:a.cost_usd}).from(a).where(drizzleOrm.or(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.status,"pending"))).all(),s=this.clock(),o=Math.max(1,Math.trunc(e.tickIntervalMs??Rc)),i=this.lastReaperTickAt,u=i===void 0?Number.POSITIVE_INFINITY:s-i,d=i!==void 0&&u>=0&&u<=o*2;this.lastReaperTickAt=s;let c=En(),l=fs(),p=new Date(s-Ec).toISOString(),f=new Date(s).toISOString(),h=new Set,m=[],k=0,E=(w,x)=>{let I=oe(Ei(w.metadata,"runner_lost")),O=typeof I.provider=="string"?I.provider:void 0,S;try{S=ls({taskLogRepository:this.taskLogRepository,taskId:w.id,provider:O,model:w.model})?.usage;}catch{}let j={status:"failed",error:x,completed_at:f};S?(j.input_tokens=S.inputTokens,j.output_tokens=S.outputTokens,j.cached_input_tokens=S.cachedInputTokens,j.cost_usd=S.costUsd,w.model===null&&S.model!==null&&(j.model=S.model),I[Fe]="recorded"):!Ri(w)&&I[Fe]!=="recorded"&&(I[Fe]="unavailable"),j.metadata=JSON.stringify(I);let ge=w.run_epoch===null?drizzleOrm.isNull(a.run_epoch):drizzleOrm.eq(a.run_epoch,w.run_epoch),Tt=w.heartbeat_at===null?drizzleOrm.isNull(a.heartbeat_at):drizzleOrm.eq(a.heartbeat_at,w.heartbeat_at),rt=n.db.update(a).set(j).where(drizzleOrm.and(drizzleOrm.eq(a.id,w.id),drizzleOrm.eq(a.status,"running"),ge,Tt)).run();return rt.changes>0&&k++,rt.changes>0};for(let w of r){if(w.status==="pending"){if(w.pid!==null||w.started_at>=p)continue;let S=Ei(w.metadata,"launch_failed");n.db.update(a).set({status:"failed",error:"Reaped: runner never adopted task (pending timeout)",completed_at:f,metadata:S}).where(drizzleOrm.and(drizzleOrm.eq(a.id,w.id),drizzleOrm.eq(a.status,"pending"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,p))).run().changes>0&&k++;continue}if(rh.has(w.platform??"cli"))continue;if(w.pid===null){let S=`${w.id}:${w.run_epoch??0}`;h.add(S);let j=this.pidNullObservedSince.get(S);if(j===void 0){this.pidNullObservedSince.set(S,s);continue}s-j>=Ii&&E(w,"Reaped: pid never recorded after resume (stale running_instruction)")&&this.pidNullObservedSince.delete(S);continue}if(w.heartbeat_at===null){At(w.pid,this.processControl.kill)==="not_found"&&E(w,"Reaped: process not found (orphaned task)");continue}let x=Date.parse(w.heartbeat_at),I=Number.isFinite(x)?s-x:Number.POSITIVE_INFINITY;if(I<=c)continue;let O=ai(w).filter(S=>At(S.pid,this.processControl.kill)!=="not_found");O.length===0?E(w,"Reaped: process not found (orphaned task)"):I>l&&d&&m.push({row:w,targets:O});}let v=new Map;for(let w of m){let{row:x,targets:I}=w,O=n.db.select({status:a.status,run_epoch:a.run_epoch,heartbeat_at:a.heartbeat_at}).from(a).where(drizzleOrm.eq(a.id,x.id)).get();if(!O||O.status!=="running"||B(O.run_epoch)!==B(x.run_epoch)||O.heartbeat_at!==x.heartbeat_at)continue;let S=await this.judgeRecordedTargets(x,I);if(S.unproven!==void 0){console.warn("[crewx] reaper left running task",{taskId:x.id,reason:S.unproven});continue}if(S.owned.length>0){let j=await this.terminateRecordedProcesses(S.owned,v);if(j!==void 0){console.warn("[crewx] reaper left running task",{taskId:x.id,reason:j});continue}}E(x,"Reaped: heartbeat stale beyond hard limit (orphaned task)")&&S.reused.length>0&&console.warn("[crewx] reaper reaped task whose recorded pid was reused",{taskId:x.id,reason:S.reused.join("; ")});}for(let w of Array.from(this.pidNullObservedSince.keys()))h.has(w)||this.pidNullObservedSince.delete(w);return k}finally{n.close();}}async judgeRecordedTargets(e,n){let r=e.heartbeat_at===null?Number.NaN:Date.parse(e.heartbeat_at),s=Number.isFinite(r)?r+sr()+Wr:void 0,o=[],i=[];for(let u of n){let d=await di(u,{processControlOptions:this.processControl,legacyStartBoundaryMs:s});if(d.verdict==="owned")o.push(u);else if(d.verdict==="reused")i.push(`pid ${u.pid} reused (${d.reason})`);else return {owned:o,reused:i,unproven:`pid ${u.pid} not proven owned (${d.ownership}): ${d.reason}`}}return {owned:o,reused:i}}async terminateRecordedProcesses(e,n){for(let r of e){if(!n.has(r.pid)){let s;try{s=(await Nt(r.pid,{...this.processControl,signal:Ot})).status==="failed"?"failed":"terminated";}catch{s="failed";}n.set(r.pid,s);}if(n.get(r.pid)==="failed")return `pid ${r.pid} termination not confirmed`;if(At(r.pid,this.processControl.kill)!=="not_found")return `pid ${r.pid} still alive after termination`}}reapRunningWorkflowTasks(e=Ii){if(!this.dbExists())return 0;let n=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString(),s=drizzleOrm.and(drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.isNull(a.pid),drizzleOrm.lt(a.started_at,r),drizzleOrm.or(drizzleOrm.isNull(a.metadata),gc())),o=n.db.select({id:a.id,metadata:a.metadata}).from(a).where(s).all(),i=new Date().toISOString(),u=0;for(let d of o){let c=oe(d.metadata);c.terminalReason="runner_lost";let l=n.db.update(a).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:i,metadata:JSON.stringify(c)}).where(drizzleOrm.and(drizzleOrm.eq(a.id,d.id),drizzleOrm.eq(a.status,"running"))).run();u+=l.changes??0;}return u}finally{n.close();}}findTaskStatus(e,n){let r=this.resolveDbPaths();for(let s of r){if(!Ru.existsSync(s))continue;let o=M(s);try{let i=n?drizzleOrm.eq(a.workspace_id,n):void 0,u=i?drizzleOrm.and(drizzleOrm.eq(a.id,e),i):drizzleOrm.eq(a.id,e),d=o.db.select(re).from(a).where(u).limit(1).get()??void 0;if(!d){let c=i?drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),i):drizzleOrm.eq(a.thread_id,e);d=o.db.select(re).from(a).where(c).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??void 0;}if(d)return Qe(d)}catch(i){throw new _("DB_ERROR","Failed to find task status",i)}finally{o.close();}}}findChildTasks(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!Ru.existsSync(i))continue;let u=M(i);try{let d=n?drizzleOrm.and(drizzleOrm.eq(a.parent_task_id,e),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.eq(a.parent_task_id,e),c=u.db.select(re).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(Qe(l)));}catch(d){throw new _("DB_ERROR","Failed to find child tasks",d)}finally{u.close();}}return o}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.all(e?drizzleOrm.sql`
145
164
  SELECT
146
165
  COALESCE(workspace_id, 'unknown') AS workspace_id,
147
166
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -162,14 +181,14 @@ ${r.join(`
162
181
  FROM tasks
163
182
  GROUP BY workspace_id
164
183
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
165
- `)}catch(r){throw new _("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),s=new Set,o=0,i=0,u=0;for(let d of r){if(!fs$1.existsSync(d))continue;let c=M(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,f=c.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(p).all();for(let h of f)s.has(h.id)||(s.add(h.id),o+=h.input_tokens??0,i+=h.output_tokens??0,u+=h.cost_usd??0);}catch(l){throw new _("DB_ERROR","Failed to get thread token usage",l)}finally{c.close();}}return {inputTokens:o,outputTokens:i,costUsd:u}}findTasksByThread(e,n,r){let s=this.resolveDbPaths(),o=new Set,i=[],u=r?.projection==="activity-log";for(let d of s){if(!fs$1.existsSync(d))continue;let c=M(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,f=u?c.db.select({id:a.id,thread_id:a.thread_id,agent_id:a.agent_id,parent_task_id:a.parent_task_id,started_at:a.started_at,completed_at:a.completed_at}).from(a).where(p).orderBy(drizzleOrm.asc(a.started_at)).all():c.db.select(re).from(a).where(p).orderBy(drizzleOrm.asc(a.started_at)).all().map(Ve);for(let h of f)o.has(h.id)||(o.add(h.id),i.push(h));}catch(l){throw new _("DB_ERROR","Failed to find tasks by thread",l)}finally{c.close();}}return i}parseWorkflowCardMetadata(e){if(!e)return {};try{let n=JSON.parse(e);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let n of this.resolveDbPaths()){if(!fs$1.existsSync(n))continue;let r=M(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(drizzleOrm.and(drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.inArray(a.status,["running","pending"]),oi())).orderBy(drizzleOrm.desc(a.started_at)).all().map(si));}catch(s){throw new _("DB_ERROR","Failed to find workflow parent tasks",s)}finally{r.close();}}return e}findWorkflowParentTasksByWorkspace(e){let n=[],r=new Map;for(let s of this.resolveDbPaths()){if(!fs$1.existsSync(s))continue;let o=M(s);try{let i=o.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(drizzleOrm.and(drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.eq(a.workspace_id,e))).orderBy(drizzleOrm.desc(a.started_at),drizzleOrm.desc(a.id)).all();for(let u of i){let d=this.parseWorkflowCardMetadata(u.metadata);if(!Bn(d.kind)||typeof d.workflowRunId!="string")continue;let c=d.kind,l=r.get(c)??new Set;l.has(d.workflowRunId)||(l.add(d.workflowRunId),r.set(c,l),n.push(si(u)));}}catch(i){throw new _("DB_ERROR","Failed to find workflow parent tasks by workspace",i)}finally{o.close();}}return n}findWorkflowParentTask(e){if(this.dbExists())for(let n of this.resolveDbPaths()){if(!fs$1.existsSync(n))continue;let r=M(n);try{let s=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(drizzleOrm.and(drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.eq(a.workspace_id,e.workspaceId))).orderBy(drizzleOrm.desc(a.started_at),drizzleOrm.desc(a.id)).all();for(let o of s){let i=this.parseWorkflowCardMetadata(o.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return si(o)}}catch(s){throw new _("DB_ERROR","Failed to find workflow parent task",s)}finally{r.close();}}}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let s=new Set(e),o=new Map,i=n?drizzleOrm.eq(a.workspace_id,n):void 0,u=(d,c)=>{if(!d)return;let l=o.get(d);if(l&&c.started_at<=l)return;let p=this.parseWorkflowCardMetadata(c.metadata);Bn(p.kind)&&(o.set(d,c.started_at),r.set(d,{taskId:c.id,workflowRunId:p.workflowRunId,raw:c.result??void 0}));};for(let d of this.resolveDbPaths()){if(!fs$1.existsSync(d))continue;let c=M(d);try{let l=drizzleOrm.and(drizzleOrm.inArray(a.thread_id,e),oi()),p=c.db.select({id:a.id,thread_id:a.thread_id,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?drizzleOrm.and(l,i):l).all();for(let m of p)u(m.thread_id,m);let f=drizzleOrm.and(drizzleOrm.isNull(a.thread_id),oi()),h=c.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?drizzleOrm.and(f,i):f).all();for(let m of h){let k=this.extractThreadIdFromCommand(m.command);!k||!s.has(k)||u(k,m);}}catch(l){throw new _("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{c.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(drizzleOrm.eq(a.workspace_id,e.workspaceId));let s=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;s&&r.push(drizzleOrm.inArray(a.agent_id,s));let o=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;o&&r.push(drizzleOrm.inArray(a.status,Ho(o)));let i=e.q??e.search;i&&r.push(drizzleOrm.like(a.prompt,`%${i}%`)),e.from&&r.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(a.started_at,e.to));let u=r.length>0?drizzleOrm.and(...r):void 0,d=n.db.select({count:drizzleOrm.sql`count(*)`}).from(a).where(u).get(),c=(e.sortDir??"DESC")==="ASC"?drizzleOrm.asc(a.started_at):drizzleOrm.desc(a.started_at);return {rows:n.db.select(re).from(a).where(u).orderBy(c).limit(e.limit).offset(e.offset).all().map(Ve),total:d?.count??0}}catch(r){throw new _("DB_ERROR","Failed to find all tasks",r)}finally{n.close();}}getAgentUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=ai(drizzleOrm.sql.raw("t.model"),drizzleOrm.sql.raw("t.metadata")),i=ar(drizzleOrm.sql.raw("t.status")),u=cs(drizzleOrm.sql.raw("t.metadata")),d=drizzleOrm.sql`
184
+ `)}catch(r){throw new _("DB_ERROR","Failed to get workspace usage summary",r)}finally{n.close();}}getThreadTokenUsage(e,n){let r=this.resolveDbPaths(),s=new Set,o=0,i=0,u=0;for(let d of r){if(!Ru.existsSync(d))continue;let c=M(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,f=c.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(p).all();for(let h of f)s.has(h.id)||(s.add(h.id),o+=h.input_tokens??0,i+=h.output_tokens??0,u+=h.cost_usd??0);}catch(l){throw new _("DB_ERROR","Failed to get thread token usage",l)}finally{c.close();}}return {inputTokens:o,outputTokens:i,costUsd:u}}findTasksByThread(e,n,r){let s=this.resolveDbPaths(),o=new Set,i=[],u=r?.projection==="activity-log";for(let d of s){if(!Ru.existsSync(d))continue;let c=M(d);try{let l=drizzleOrm.eq(a.thread_id,e),p=n?drizzleOrm.and(l,drizzleOrm.eq(a.workspace_id,n)):l,f=u?c.db.select({id:a.id,thread_id:a.thread_id,agent_id:a.agent_id,parent_task_id:a.parent_task_id,started_at:a.started_at,completed_at:a.completed_at}).from(a).where(p).orderBy(drizzleOrm.asc(a.started_at)).all():c.db.select(re).from(a).where(p).orderBy(drizzleOrm.asc(a.started_at)).all().map(Qe);for(let h of f)o.has(h.id)||(o.add(h.id),i.push(h));}catch(l){throw new _("DB_ERROR","Failed to find tasks by thread",l)}finally{c.close();}}return i}parseWorkflowCardMetadata(e){if(!e)return {};try{let n=JSON.parse(e);return {kind:typeof n.kind=="string"?n.kind:void 0,workflowRunId:typeof n.workflowRunId=="string"?n.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let n of this.resolveDbPaths()){if(!Ru.existsSync(n))continue;let r=M(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(drizzleOrm.and(drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.inArray(a.status,["running","pending"]),_i())).orderBy(drizzleOrm.desc(a.started_at)).all().map(fi));}catch(s){throw new _("DB_ERROR","Failed to find workflow parent tasks",s)}finally{r.close();}}return e}findWorkflowParentTasksByWorkspace(e){let n=[],r=new Map;for(let s of this.resolveDbPaths()){if(!Ru.existsSync(s))continue;let o=M(s);try{let i=o.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(drizzleOrm.and(drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.eq(a.workspace_id,e))).orderBy(drizzleOrm.desc(a.started_at),drizzleOrm.desc(a.id)).all();for(let u of i){let d=this.parseWorkflowCardMetadata(u.metadata);if(!Wn(d.kind)||typeof d.workflowRunId!="string")continue;let c=d.kind,l=r.get(c)??new Set;l.has(d.workflowRunId)||(l.add(d.workflowRunId),r.set(c,l),n.push(fi(u)));}}catch(i){throw new _("DB_ERROR","Failed to find workflow parent tasks by workspace",i)}finally{o.close();}}return n}findWorkflowParentTask(e){if(this.dbExists())for(let n of this.resolveDbPaths()){if(!Ru.existsSync(n))continue;let r=M(n);try{let s=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(drizzleOrm.and(drizzleOrm.eq(a.platform,"workflow"),drizzleOrm.eq(a.workspace_id,e.workspaceId))).orderBy(drizzleOrm.desc(a.started_at),drizzleOrm.desc(a.id)).all();for(let o of s){let i=this.parseWorkflowCardMetadata(o.metadata);if(i.kind===e.kind&&i.workflowRunId===e.workflowRunId)return fi(o)}}catch(s){throw new _("DB_ERROR","Failed to find workflow parent task",s)}finally{r.close();}}}batchFetchWorkflowCards(e,n){let r=new Map;if(e.length===0)return r;let s=new Set(e),o=new Map,i=n?drizzleOrm.eq(a.workspace_id,n):void 0,u=(d,c)=>{if(!d)return;let l=o.get(d);if(l&&c.started_at<=l)return;let p=this.parseWorkflowCardMetadata(c.metadata);Wn(p.kind)&&(o.set(d,c.started_at),r.set(d,{taskId:c.id,workflowRunId:p.workflowRunId,raw:c.result??void 0}));};for(let d of this.resolveDbPaths()){if(!Ru.existsSync(d))continue;let c=M(d);try{let l=drizzleOrm.and(drizzleOrm.inArray(a.thread_id,e),_i()),p=c.db.select({id:a.id,thread_id:a.thread_id,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?drizzleOrm.and(l,i):l).all();for(let m of p)u(m.thread_id,m);let f=drizzleOrm.and(drizzleOrm.isNull(a.thread_id),_i()),h=c.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?drizzleOrm.and(f,i):f).all();for(let m of h){let k=this.extractThreadIdFromCommand(m.command);!k||!s.has(k)||u(k,m);}}catch(l){throw new _("DB_ERROR","Failed to batch fetch workflow cards",l)}finally{c.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(drizzleOrm.eq(a.workspace_id,e.workspaceId));let s=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;s&&r.push(drizzleOrm.inArray(a.agent_id,s));let o=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;o&&r.push(drizzleOrm.inArray(a.status,zo(o)));let i=e.q??e.search;i&&r.push(drizzleOrm.like(a.prompt,`%${i}%`)),e.from&&r.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(a.started_at,e.to));let u=r.length>0?drizzleOrm.and(...r):void 0,d=n.db.select({count:drizzleOrm.sql`count(*)`}).from(a).where(u).get(),c=(e.sortDir??"DESC")==="ASC"?drizzleOrm.asc(a.started_at):drizzleOrm.desc(a.started_at);return {rows:n.db.select(re).from(a).where(u).orderBy(c).limit(e.limit).offset(e.offset).all().map(Qe),total:d?.count??0}}catch(r){throw new _("DB_ERROR","Failed to find all tasks",r)}finally{n.close();}}getAgentUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=hi(drizzleOrm.sql.raw("t.model"),drizzleOrm.sql.raw("t.metadata")),i=cr(drizzleOrm.sql.raw("t.status")),u=hs(drizzleOrm.sql.raw("t.metadata")),d=drizzleOrm.sql`
166
185
  COALESCE(t.input_tokens, 0)
167
186
  + CASE
168
- WHEN t.started_at >= ${En}
187
+ WHEN t.started_at >= ${Rn}
169
188
  AND (
170
189
  t.crewx_version IS NULL
171
190
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
172
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Rn}) AS INTEGER) < ${Sn})
191
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Sn}) AS INTEGER) < ${In})
173
192
  )
174
193
  THEN COALESCE(t.cached_input_tokens, 0)
175
194
  ELSE 0
@@ -188,7 +207,7 @@ ${r.join(`
188
207
  FROM tasks t
189
208
  ${c}
190
209
  GROUP BY t.agent_id, t.workspace_id, ${o}
191
- `),p=new Map;for(let m of l){let k=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",E={provider:k,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,totalTokens:m.input_tokens+m.output_tokens,costUsd:m.cost_usd,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count},v=m.workspace_id??null,w=JSON.stringify([m.agent_id,v]),x=p.get(w);if(!x){p.set(w,{agentId:m.agent_id,workspaceId:v,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,costUsd:m.cost_usd,totalTokens:m.input_tokens+m.output_tokens,providers:[E]});continue}x.totalTasks+=m.total_tasks,x.unavailableTaskCount=(x.unavailableTaskCount??0)+m.unavailable_task_count,x.inputTokens+=m.input_tokens,x.outputTokens+=m.output_tokens,x.cachedInputTokens+=m.cached_input_tokens,x.costUsd+=m.cost_usd,x.totalTokens+=m.input_tokens+m.output_tokens;let I=x.providers.find(O=>O.provider===k);I?(I.inputTokens+=E.inputTokens,I.outputTokens+=E.outputTokens,I.cachedInputTokens+=E.cachedInputTokens,I.totalTokens+=E.totalTokens,I.costUsd+=E.costUsd,I.totalTasks+=E.totalTasks,I.unavailableTaskCount+=E.unavailableTaskCount):x.providers.push(E);}let f=[...p.values()];for(let m of f)m.providers.sort((k,E)=>k.provider===E.provider?0:k.provider==="unknown"?1:E.provider==="unknown"?-1:k.totalTokens!==E.totalTokens?E.totalTokens-k.totalTokens:k.provider<E.provider?-1:1);let h=(m,k)=>m===k?0:m<k?-1:1;return f.sort((m,k)=>{if(m.totalTokens!==k.totalTokens)return k.totalTokens-m.totalTokens;let E=h(m.agentId,k.agentId);return E!==0?E:m.workspaceId===k.workspaceId?0:m.workspaceId===null?1:k.workspaceId===null?-1:h(m.workspaceId,k.workspaceId)}),f}catch(o){throw new _("DB_ERROR","Failed to get agent usage",o)}finally{s.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=ar(drizzleOrm.sql.raw("t.status")),i=cs(drizzleOrm.sql.raw("t.metadata"));return s.db.all(r?drizzleOrm.sql`
210
+ `),p=new Map;for(let m of l){let k=typeof m.provider=="string"&&m.provider.trim()!==""?m.provider:"unknown",E={provider:k,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,totalTokens:m.input_tokens+m.output_tokens,costUsd:m.cost_usd,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count},v=m.workspace_id??null,w=JSON.stringify([m.agent_id,v]),x=p.get(w);if(!x){p.set(w,{agentId:m.agent_id,workspaceId:v,totalTasks:m.total_tasks,unavailableTaskCount:m.unavailable_task_count,inputTokens:m.input_tokens,outputTokens:m.output_tokens,cachedInputTokens:m.cached_input_tokens,costUsd:m.cost_usd,totalTokens:m.input_tokens+m.output_tokens,providers:[E]});continue}x.totalTasks+=m.total_tasks,x.unavailableTaskCount=(x.unavailableTaskCount??0)+m.unavailable_task_count,x.inputTokens+=m.input_tokens,x.outputTokens+=m.output_tokens,x.cachedInputTokens+=m.cached_input_tokens,x.costUsd+=m.cost_usd,x.totalTokens+=m.input_tokens+m.output_tokens;let I=x.providers.find(O=>O.provider===k);I?(I.inputTokens+=E.inputTokens,I.outputTokens+=E.outputTokens,I.cachedInputTokens+=E.cachedInputTokens,I.totalTokens+=E.totalTokens,I.costUsd+=E.costUsd,I.totalTasks+=E.totalTasks,I.unavailableTaskCount+=E.unavailableTaskCount):x.providers.push(E);}let f=[...p.values()];for(let m of f)m.providers.sort((k,E)=>k.provider===E.provider?0:k.provider==="unknown"?1:E.provider==="unknown"?-1:k.totalTokens!==E.totalTokens?E.totalTokens-k.totalTokens:k.provider<E.provider?-1:1);let h=(m,k)=>m===k?0:m<k?-1:1;return f.sort((m,k)=>{if(m.totalTokens!==k.totalTokens)return k.totalTokens-m.totalTokens;let E=h(m.agentId,k.agentId);return E!==0?E:m.workspaceId===k.workspaceId?0:m.workspaceId===null?1:k.workspaceId===null?-1:h(m.workspaceId,k.workspaceId)}),f}catch(o){throw new _("DB_ERROR","Failed to get agent usage",o)}finally{s.close();}}getAgentUsageTrendRaw(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=cr(drizzleOrm.sql.raw("t.status")),i=hs(drizzleOrm.sql.raw("t.metadata"));return s.db.all(r?drizzleOrm.sql`
192
211
  SELECT
193
212
  date(t.started_at) AS date,
194
213
  t.agent_id,
@@ -196,11 +215,11 @@ ${r.join(`
196
215
  COALESCE(SUM(
197
216
  COALESCE(t.input_tokens, 0)
198
217
  + CASE
199
- WHEN t.started_at >= ${En}
218
+ WHEN t.started_at >= ${Rn}
200
219
  AND (
201
220
  t.crewx_version IS NULL
202
221
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
203
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Rn}) AS INTEGER) < ${Sn})
222
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Sn}) AS INTEGER) < ${In})
204
223
  )
205
224
  THEN COALESCE(t.cached_input_tokens, 0)
206
225
  ELSE 0
@@ -225,11 +244,11 @@ ${r.join(`
225
244
  COALESCE(SUM(
226
245
  COALESCE(t.input_tokens, 0)
227
246
  + CASE
228
- WHEN t.started_at >= ${En}
247
+ WHEN t.started_at >= ${Rn}
229
248
  AND (
230
249
  t.crewx_version IS NULL
231
250
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
232
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Rn}) AS INTEGER) < ${Sn})
251
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Sn}) AS INTEGER) < ${In})
233
252
  )
234
253
  THEN COALESCE(t.cached_input_tokens, 0)
235
254
  ELSE 0
@@ -245,14 +264,14 @@ ${r.join(`
245
264
  AND t.agent_id != 'workflow'
246
265
  GROUP BY date(t.started_at), t.agent_id
247
266
  ORDER BY date(t.started_at) ASC
248
- `).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(o){throw new _("DB_ERROR","Failed to get agent usage trend",o)}finally{s.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let s=r.db.select(re).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.workspace_id,n))).limit(1).get();return s?Ve(s):void 0}catch(s){throw new _("DB_ERROR","Failed to find task for stop",s)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.agent_id,e.agentId),drizzleOrm.eq(a.workspace_id,e.workspaceId),drizzleOrm.sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??null}catch(r){throw new _("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r,s="failed",o){if(!this.dbExists())return;let i=this.openHandle(true);try{let u=new Date().toISOString(),d=r?drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.workspace_id,r)):drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"running")),c=i.db.select({metadata:a.metadata}).from(a).where(d).limit(1).get();if(!c)return;let l={status:s,error:n,completed_at:u};if(o){let p=oe(c.metadata);p.terminalReason=o,l.metadata=JSON.stringify(p);}i.db.update(a).set(l).where(d).run();}catch(u){throw u instanceof _?u:new _("DB_ERROR","Failed to mark task failed",u)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!fs$1.existsSync(i))continue;let u=M(i);try{let d=n?drizzleOrm.and(drizzleOrm.like(a.prompt,`%${e}%`),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.like(a.prompt,`%${e}%`),c=u.db.select(re).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(Ve(l)));}catch(d){throw new _("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{u.close();}}return o}getProviderUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=ai(),i=ar(a.status),u=cs(a.metadata),d=drizzleOrm.sql`
267
+ `).map(d=>({date:d.date,agentId:d.agent_id,unavailableTaskCount:d.unavailable_task_count,inputTokens:d.input_tokens,outputTokens:d.output_tokens,cachedInputTokens:d.cached_input_tokens,costUsd:d.cost_usd,totalTokens:d.input_tokens+d.output_tokens}))}catch(o){throw new _("DB_ERROR","Failed to get agent usage trend",o)}finally{s.close();}}findTaskForStop(e,n){if(!this.dbExists())return;let r=this.openHandle(false);try{let s=r.db.select(re).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.workspace_id,n))).limit(1).get();return s?Qe(s):void 0}catch(s){throw new _("DB_ERROR","Failed to find task for stop",s)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select({id:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(drizzleOrm.and(drizzleOrm.eq(a.agent_id,e.agentId),drizzleOrm.eq(a.workspace_id,e.workspaceId),drizzleOrm.sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(drizzleOrm.desc(a.started_at)).limit(1).get()??null}catch(r){throw new _("DB_ERROR","Failed to find latest task by metadata",r)}finally{n.close();}}markTaskFailed(e,n,r,s="failed",o){if(!this.dbExists())return;let i=this.openHandle(true);try{let u=new Date().toISOString(),d=r?drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"running"),drizzleOrm.eq(a.workspace_id,r)):drizzleOrm.and(drizzleOrm.eq(a.id,e),drizzleOrm.eq(a.status,"running")),c=i.db.select({metadata:a.metadata}).from(a).where(d).limit(1).get();if(!c)return;let l={status:s,error:n,completed_at:u};if(o){let p=oe(c.metadata);p.terminalReason=o,l.metadata=JSON.stringify(p);}i.db.update(a).set(l).where(d).run();}catch(u){throw u instanceof _?u:new _("DB_ERROR","Failed to mark task failed",u)}finally{i.close();}}findTasksByPromptHint(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!Ru.existsSync(i))continue;let u=M(i);try{let d=n?drizzleOrm.and(drizzleOrm.like(a.prompt,`%${e}%`),drizzleOrm.eq(a.workspace_id,n)):drizzleOrm.like(a.prompt,`%${e}%`),c=u.db.select(re).from(a).where(d).orderBy(drizzleOrm.asc(a.started_at)).all();for(let l of c)s.has(l.id)||(s.add(l.id),o.push(Qe(l)));}catch(d){throw new _("DB_ERROR","Failed to find tasks by prompt hint",d)}finally{u.close();}}return o}getProviderUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=hi(),i=cr(a.status),u=hs(a.metadata),d=drizzleOrm.sql`
249
268
  COALESCE(${a.input_tokens}, 0)
250
269
  + CASE
251
- WHEN ${a.started_at} >= ${En}
270
+ WHEN ${a.started_at} >= ${Rn}
252
271
  AND (
253
272
  ${a.crewx_version} IS NULL
254
273
  OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
255
- OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Rn}) AS INTEGER) < ${Sn})
274
+ OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Sn}) AS INTEGER) < ${In})
256
275
  )
257
276
  THEN COALESCE(${a.cached_input_tokens}, 0)
258
277
  ELSE 0
@@ -272,14 +291,14 @@ ${r.join(`
272
291
  ${c}
273
292
  GROUP BY ${o}
274
293
  ORDER BY (COALESCE(SUM(${d}), 0) + COALESCE(SUM(${a.output_tokens}), 0)) DESC
275
- `).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(o){throw new _("DB_ERROR","Failed to get provider usage",o)}finally{s.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=ai(),i=ar(a.status),u=cs(a.metadata),d=drizzleOrm.sql`
294
+ `).map(p=>({provider:p.provider,totalTasks:p.total_tasks,unavailableTaskCount:p.unavailable_task_count,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null}))}catch(o){throw new _("DB_ERROR","Failed to get provider usage",o)}finally{s.close();}}getModelUsage(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=hi(),i=cr(a.status),u=hs(a.metadata),d=drizzleOrm.sql`
276
295
  COALESCE(${a.input_tokens}, 0)
277
296
  + CASE
278
- WHEN ${a.started_at} >= ${En}
297
+ WHEN ${a.started_at} >= ${Rn}
279
298
  AND (
280
299
  ${a.crewx_version} IS NULL
281
300
  OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
282
- OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Rn}) AS INTEGER) < ${Sn})
301
+ OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Sn}) AS INTEGER) < ${In})
283
302
  )
284
303
  THEN COALESCE(${a.cached_input_tokens}, 0)
285
304
  ELSE 0
@@ -299,7 +318,7 @@ ${r.join(`
299
318
  FROM ${a}
300
319
  ${c}
301
320
  GROUP BY ${a.model}, ${o}
302
- `),p=new Map;for(let f of l){let h=no(f.model??""),m=JSON.stringify([f.provider,h]),k=p.get(m);k?(k.totalTasks+=f.total_tasks,k.unavailableTaskCount=(k.unavailableTaskCount??0)+f.unavailable_task_count,k.inputTokens+=f.input_tokens,k.outputTokens+=f.output_tokens,k.cachedInputTokens+=f.cached_input_tokens,k.costUsd+=f.cost_usd,k.totalTokens+=f.input_tokens+f.output_tokens,k.activeDurationMs+=f.active_duration_ms??0,f.last_active_at&&(!k.lastActiveAt||f.last_active_at>k.lastActiveAt)&&(k.lastActiveAt=f.last_active_at)):p.set(m,{model:h,provider:f.provider,totalTasks:f.total_tasks,unavailableTaskCount:f.unavailable_task_count,inputTokens:f.input_tokens,outputTokens:f.output_tokens,cachedInputTokens:f.cached_input_tokens,costUsd:f.cost_usd,totalTokens:f.input_tokens+f.output_tokens,activeDurationMs:f.active_duration_ms??0,lastActiveAt:f.last_active_at??null});}return Array.from(p.values()).sort((f,h)=>h.costUsd-f.costUsd)}catch(o){throw new _("DB_ERROR","Failed to get model usage",o)}finally{s.close();}}getTasksForReport(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=r?drizzleOrm.sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return s.db.all(drizzleOrm.sql`
321
+ `),p=new Map;for(let f of l){let h=uo(f.model??""),m=JSON.stringify([f.provider,h]),k=p.get(m);k?(k.totalTasks+=f.total_tasks,k.unavailableTaskCount=(k.unavailableTaskCount??0)+f.unavailable_task_count,k.inputTokens+=f.input_tokens,k.outputTokens+=f.output_tokens,k.cachedInputTokens+=f.cached_input_tokens,k.costUsd+=f.cost_usd,k.totalTokens+=f.input_tokens+f.output_tokens,k.activeDurationMs+=f.active_duration_ms??0,f.last_active_at&&(!k.lastActiveAt||f.last_active_at>k.lastActiveAt)&&(k.lastActiveAt=f.last_active_at)):p.set(m,{model:h,provider:f.provider,totalTasks:f.total_tasks,unavailableTaskCount:f.unavailable_task_count,inputTokens:f.input_tokens,outputTokens:f.output_tokens,cachedInputTokens:f.cached_input_tokens,costUsd:f.cost_usd,totalTokens:f.input_tokens+f.output_tokens,activeDurationMs:f.active_duration_ms??0,lastActiveAt:f.last_active_at??null});}return Array.from(p.values()).sort((f,h)=>h.costUsd-f.costUsd)}catch(o){throw new _("DB_ERROR","Failed to get model usage",o)}finally{s.close();}}getTasksForReport(e,n,r){if(!this.dbExists())return [];let s=this.openHandle(false);try{let o=r?drizzleOrm.sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`;return s.db.all(drizzleOrm.sql`
303
322
  SELECT
304
323
  ${a.thread_id} AS thread_id,
305
324
  ${a.agent_id} AS agent_id,
@@ -311,19 +330,19 @@ ${r.join(`
311
330
  FROM ${a}
312
331
  ${o}
313
332
  ORDER BY ${a.started_at} ASC
314
- `).map(u=>({threadId:u.thread_id,agentId:u.agent_id,startedAt:u.started_at,status:u.status,error:u.error,exitCode:u.exit_code,terminalReason:ze({status:u.status,error:u.error,metadata:u.metadata})??null}))}catch(o){throw new _("DB_ERROR","Failed to get tasks for report",o)}finally{s.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let s=this.openHandle(false);try{let o=drizzleOrm.sql`
333
+ `).map(u=>({threadId:u.thread_id,agentId:u.agent_id,startedAt:u.started_at,status:u.status,error:u.error,exitCode:u.exit_code,terminalReason:Xe({status:u.status,error:u.error,metadata:u.metadata})??null}))}catch(o){throw new _("DB_ERROR","Failed to get tasks for report",o)}finally{s.close();}}getDelegationMatrix(e,n,r){if(!this.dbExists())return {edges:[],truncated:false};let s=this.openHandle(false);try{let o=drizzleOrm.sql`
315
334
  COALESCE(${a.input_tokens}, 0)
316
335
  + CASE
317
- WHEN ${a.started_at} >= ${En}
336
+ WHEN ${a.started_at} >= ${Rn}
318
337
  AND (
319
338
  ${a.crewx_version} IS NULL
320
339
  OR (${a.crewx_version} LIKE '0.8.%' AND ${a.crewx_version} NOT LIKE '0.8.9%')
321
- OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Rn}) AS INTEGER) < ${Sn})
340
+ OR (${a.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${a.crewx_version}, ${Sn}) AS INTEGER) < ${In})
322
341
  )
323
342
  THEN COALESCE(${a.cached_input_tokens}, 0)
324
343
  ELSE 0
325
344
  END
326
- `,i=ar(a.status),u=r?drizzleOrm.sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,d=s.db.all(drizzleOrm.sql`
345
+ `,i=cr(a.status),u=r?drizzleOrm.sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n} AND ${a.workspace_id} = ${r}`:drizzleOrm.sql`WHERE ${i} AND ${a.started_at} >= ${e} AND ${a.started_at} < ${n}`,d=s.db.all(drizzleOrm.sql`
327
346
  SELECT
328
347
  ${a.caller_agent_id} AS caller_agent_id,
329
348
  ${a.agent_id} AS agent_id,
@@ -334,28 +353,28 @@ ${r.join(`
334
353
  ${u}
335
354
  GROUP BY ${a.caller_agent_id}, ${a.agent_id}
336
355
  ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
337
- LIMIT ${ii+1}
338
- `),c=d.length>ii;return {edges:d.slice(0,ii).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:c}}catch(o){throw new _("DB_ERROR","Failed to get delegation matrix",o)}finally{s.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(drizzleOrm.eq(a.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(drizzleOrm.inArray(a.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(drizzleOrm.inArray(a.status,Ho(e.statuses))),e.from&&r.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(a.started_at,e.to));let s=r.length>0?drizzleOrm.and(...r):void 0,o=(e.order??"DESC")==="ASC"?drizzleOrm.asc(a.started_at):drizzleOrm.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(s).orderBy(o).limit(e.limit).all():n.db.select(i).from(a).where(s).orderBy(o).all()).map(({error:d,metadata:c,...l})=>({...l,status:xe({status:l.status,error:d,metadata:c}),terminalReason:ze({status:l.status,error:d,metadata:c})??null}))}catch(r){throw new _("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,s=e.maxTurnsPerThread??4,o=[drizzleOrm.isNotNull(a.thread_id),drizzleOrm.isNull(a.parent_task_id),drizzleOrm.isNull(a.caller_agent_id),drizzleOrm.or(drizzleOrm.isNull(a.platform),drizzleOrm.ne(a.platform,"workflow")),drizzleOrm.or(drizzleOrm.isNull(a.metadata),Vu()),drizzleOrm.or(drizzleOrm.isNull(a.metadata),drizzleOrm.notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&o.push(drizzleOrm.eq(a.workspace_id,e.workspaceId)),e.from&&o.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&o.push(drizzleOrm.lt(a.started_at,e.to));let i=n.db.select({id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id}).from(a).where(drizzleOrm.and(...o)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.asc(a.id)).all(),u=new Map;for(let c of i){if(!c.thread_id)continue;let l={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},p=u.get(c.thread_id);p?p.push(l):u.set(c.thread_id,[l]);}let d=[];for(let[c,l]of u){let p=l.filter(f=>f.agentId===e.targetAgentId).length;p<2||d.push({threadId:c,targetAgentTurnCount:p,turns:l});}return d.sort((c,l)=>{let p=c.turns[c.turns.length-1].startedAt,f=l.turns[l.turns.length-1].startedAt;return p<f?1:p>f?-1:0}),d.slice(0,r).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-s)}))}catch(r){throw new _("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}},sc=["up","down"],mi=1e3,oc=200,Rg=64,cr=class extends _{stableCode;taskId;constructor(e,n){super(e==="TASK_NOT_FOUND"?"NOT_FOUND":"CONFLICT",e==="TASK_NOT_FOUND"?`Task not found: ${n}`:`Task is not finished, so it cannot be rated: ${n}`),this.name="TaskRatingError",this.stableCode=e,this.taskId=n;}},Sg=new Set(Zt);});g();g();g();var mt=class{detach(e){}};g();function Di(t){let e=n=>String(n).padStart(2,"0");return `${t.getFullYear()}${e(t.getMonth()+1)}${e(t.getDate())}T${e(t.getHours())}${e(t.getMinutes())}${e(t.getSeconds())}`}function vs(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var xs=class extends mt{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(e){super(),this.logsDir=he.join(e?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=e?.version??"unknown";}attach(e){this.unsubs.push(e.on("task:start",n=>{try{fs$1.existsSync(this.logsDir)||fs$1.mkdirSync(this.logsDir,{recursive:!0});let r=Di(n.timestamp),s=he.join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,s);let o=`=== TASK LOG: ${n.traceId} ===
356
+ LIMIT ${gi+1}
357
+ `),c=d.length>gi;return {edges:d.slice(0,gi).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:c}}catch(o){throw new _("DB_ERROR","Failed to get delegation matrix",o)}finally{s.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let n=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(drizzleOrm.eq(a.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(drizzleOrm.inArray(a.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(drizzleOrm.inArray(a.status,zo(e.statuses))),e.from&&r.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&r.push(drizzleOrm.lt(a.started_at,e.to));let s=r.length>0?drizzleOrm.and(...r):void 0,o=(e.order??"DESC")==="ASC"?drizzleOrm.asc(a.started_at):drizzleOrm.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(s).orderBy(o).limit(e.limit).all():n.db.select(i).from(a).where(s).orderBy(o).all()).map(({error:d,metadata:c,...l})=>({...l,status:De({status:l.status,error:d,metadata:c}),terminalReason:Xe({status:l.status,error:d,metadata:c})??null}))}catch(r){throw new _("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,s=e.maxTurnsPerThread??4,o=[drizzleOrm.isNotNull(a.thread_id),drizzleOrm.isNull(a.parent_task_id),drizzleOrm.isNull(a.caller_agent_id),drizzleOrm.or(drizzleOrm.isNull(a.platform),drizzleOrm.ne(a.platform,"workflow")),drizzleOrm.or(drizzleOrm.isNull(a.metadata),gc()),drizzleOrm.or(drizzleOrm.isNull(a.metadata),drizzleOrm.notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&o.push(drizzleOrm.eq(a.workspace_id,e.workspaceId)),e.from&&o.push(drizzleOrm.gte(a.started_at,e.from)),e.to&&o.push(drizzleOrm.lt(a.started_at,e.to));let i=n.db.select({id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id}).from(a).where(drizzleOrm.and(...o)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.asc(a.id)).all(),u=new Map;for(let c of i){if(!c.thread_id)continue;let l={id:c.id,agentId:c.agent_id,status:c.status,prompt:c.prompt,startedAt:c.started_at,completedAt:c.completed_at},p=u.get(c.thread_id);p?p.push(l):u.set(c.thread_id,[l]);}let d=[];for(let[c,l]of u){let p=l.filter(f=>f.agentId===e.targetAgentId).length;p<2||d.push({threadId:c,targetAgentTurnCount:p,turns:l});}return d.sort((c,l)=>{let p=c.turns[c.turns.length-1].startedAt,f=l.turns[l.turns.length-1].startedAt;return p<f?1:p>f?-1:0}),d.slice(0,r).map(c=>({threadId:c.threadId,targetAgentTurnCount:c.targetAgentTurnCount,turns:c.turns.slice(-s)}))}catch(r){throw new _("DB_ERROR","Failed to find thread chains",r)}finally{n.close();}}},Sc=["up","down"],Ai=1e3,Ic=200,ph=64,fr=class extends _{stableCode;taskId;constructor(e,n){super(e==="TASK_NOT_FOUND"?"NOT_FOUND":"CONFLICT",e==="TASK_NOT_FOUND"?`Task not found: ${n}`:`Task is not finished, so it cannot be rated: ${n}`),this.name="TaskRatingError",this.stableCode=e,this.taskId=n;}},fh=new Set(en);});g();g();g();var yt=class{detach(e){}};g();function Bi(t){let e=n=>String(n).padStart(2,"0");return `${t.getFullYear()}${e(t.getMonth()+1)}${e(t.getDate())}T${e(t.getHours())}${e(t.getMinutes())}${e(t.getSeconds())}`}function Ms(t){let e=t.toISOString();return `${e.slice(0,10)} ${e.slice(11,19)} UTC`}var $s=class extends yt{name="file-logger";unsubs=[];logFiles=new Map;logsDir;version;constructor(e){super(),this.logsDir=me.join(e?.workspaceRoot??process.cwd(),".crewx","logs"),this.version=e?.version??"unknown";}attach(e){this.unsubs.push(e.on("task:start",n=>{try{Ru.existsSync(this.logsDir)||Ru.mkdirSync(this.logsDir,{recursive:!0});let r=Bi(n.timestamp),s=me.join(this.logsDir,`${r}_${n.traceId}.log`);this.logFiles.set(n.traceId,s);let o=`=== TASK LOG: ${n.traceId} ===
339
358
  CrewX Version: ${this.version}
340
359
  Mode: ${n.mode}
341
360
  Agent: ${n.agentRef}
342
- Started: ${vs(n.timestamp)}
361
+ Started: ${Ms(n.timestamp)}
343
362
  Message: ${n.message}
344
363
 
345
- `;fs$1.writeFileSync(s,o,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let s=new Date().toISOString();fs$1.appendFileSync(r,`[${s}] STDOUT: ${n.output}
346
- `,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let s=vs(new Date),o=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${s}] INFO: Task ${o} in ${n.durationMs}ms
364
+ `;Ru.writeFileSync(s,o,{encoding:"utf8",mode:384});}catch{}}),e.on("task:output",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let s=new Date().toISOString();Ru.appendFileSync(r,`[${s}] STDOUT: ${n.output}
365
+ `,"utf8");}catch{}}),e.on("task:end",n=>{try{let r=this.logFiles.get(n.traceId);if(!r)return;let s=Ms(new Date),o=n.error?`failed: ${n.error.message}`:"completed successfully",i=`[${s}] INFO: Task ${o} in ${n.durationMs}ms
347
366
  [${s}] INFO: Process closed with exit code: ${n.error?1:0}
348
- `;fs$1.appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};g();g();var Mi=Symbol.for("crewx.interceptor.run-stops");function Gc(){let t=globalThis,e=t[Mi];if(e)return e;let n=new Map;return t[Mi]=n,n}function $i(t){let e=Gc().get(t);return e?(e.abort(),true):false}g();var rn=new Map;function Er(t){let e=he__namespace.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 qi(t){let e=Er(t);return crypto.createHash("sha256").update(e).digest("hex")}function Fi(t){let e=Er(t),n=rn.get(e);if(n!==void 0)return n;let r=e;try{let s=he__namespace.join(e,".git");if(!fs$1.lstatSync(s).isFile())return rn.set(e,r),r;let o=/^gitdir:\s*(.+?)\s*$/i.exec(fs$1.readFileSync(s,"utf8").trim());if(!o)return rn.set(e,r),r;let i=o[1],u=he__namespace.isAbsolute(i)?i:he__namespace.resolve(he__namespace.dirname(s),i),d=fs$1.readFileSync(he__namespace.join(u,"commondir"),"utf8").trim();if(!d)return rn.set(e,r),r;let c=he__namespace.isAbsolute(d)?d:he__namespace.resolve(u,d);if(he__namespace.basename(c)!==".git"||!fs$1.statSync(c).isDirectory())return rn.set(e,r),r;let l=Er(fs$1.realpathSync.native(e)),p=Er(fs$1.realpathSync.native(he__namespace.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return rn.set(e,r),r}kt();ni();pn();Mo();rr();ti();Fr();var bg=200,vg=200;function xg(t){if(typeof t!="object"||t===null||!("code"in t))return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function Cg(t){let e=t instanceof _?t.code:void 0,n=t instanceof _?t.cause:t,r=xg(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function uc(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Dg(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function cc(t){if(!t)return {};try{let e=JSON.parse(t);return Dg(e)?e:{}}catch{return {}}}function An(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Pg=new Set(["workflow","mcp"]),Ti=class extends mt{name="sqlite-tracing";unsubs=[];dbPath;version;inheritWorktreeOwner;runnerIdentity;taskRepo;heartbeatTaskIds=new Set;ownedTaskRuns=new Map;ignoredDetachedTaskIds=new Set;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super();let n=process.env.CREWX_DB;this.dbPath=e?.dbRoot!==void 0?he.join(e.dbRoot,".crewx","crewx.db"):n??he.join(ji.homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown",this.inheritWorktreeOwner=e?.inheritWorktreeOwner===true;let r=e?.runnerIdentity;this.runnerIdentity={detachedRunner:r?.detachedRunner===true,assignedTaskId:r?.detachedRunner===true&&r.assignedTaskId?.trim()||void 0};}attach(e){let n=new ur({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),s=fs$1.existsSync(he.join(r,"crewx.yaml"))||fs$1.existsSync(he.join(r,"crewx.yml")),o=this.inheritWorktreeOwner?Fi(r):r,i=s?qi(o):null,u=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let c=d.callerAgentId??null,l=d.parentTaskId??null,p=d.rootTraceId??d.traceId,{detachedRunner:f,assignedTaskId:h}=this.runnerIdentity,m=h??d.traceId,k=An(d.metadata?.runEpoch),E=f?"runner":"caller",v=d.workspaceId??i,w=f?n.getTask(m):void 0,x=d.pid??null,I={...d.metadata??{provider:d.provider??"cli/claude"},ownership:E,...f&&x!==null?{providerPid:x}:{}},O=JSON.stringify(I);if(f&&w?.status==="running"&&w.pid!==null&&k===0){this.ignoredDetachedTaskIds.add(m);return}n.startTask({id:m,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",actorKind:d.actorKind??null,actorId:d.actorId??null,pid:f?process.pid:x,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,securityKey:d.renderedPrompt==null?null:d.securityKey??null,command:u,codingAgentCommand:d.codingAgentCommand??null,workspaceId:v,projectId:d.projectId??null,callerAgentId:c,parentTaskId:l,traceId:p,metadata:O,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:k,ownership:E,...f?{providerPid:x}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:I}})?this.recordOwnedTaskRun({taskId:m,runEpoch:k,workspaceId:v,ownership:E}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:k,ownership:E}),Pg.has(d.platform??"cli")||qu(n,{taskId:m,runEpoch:k,onStopRequested:ht=>this.handleStopRequested(n,ht)})&&this.heartbeatTaskIds.add(m);}catch(c){console.warn("[crewx] task:start tracing failed",{cause:c instanceof Error?c.name:typeof c});}}),e.on("task:output",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;this.enqueueLog(c,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(c){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(c,[l],uc(l));}}),e.on("task:run-update",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;let l=An(d.runEpoch),p=this.runnerIdentity.detachedRunner;n.updateTaskOwnership({id:c,runEpoch:l,ownership:p?"runner":"caller",...p&&d.pid!==void 0?{providerPid:d.pid}:{},runtime:{...d.model!==void 0?{model:d.model}:{},...d.renderedPrompt!==void 0?{renderedPrompt:d.renderedPrompt}:{},...d.securityKey!==void 0?{securityKey:d.securityKey}:{},...d.codingAgentCommand!==void 0?{codingAgentCommand:d.codingAgentCommand}:{},...d.metadata?{metadata:d.metadata}:{}}}),!p&&d.pid!==void 0&&n.recordTaskPid({id:c,runEpoch:l,pid:d.pid});}catch(c){console.warn("[crewx] task:run-update tracing failed",{cause:c instanceof Error?c.name:typeof c});}}),e.on("task:provider-input",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;n.recordProviderInput({id:c,runEpoch:d.runEpoch,input:d.input,keyWrapSkipped:d.keyWrapSkipped,interceptedRequest:d.interceptedRequest===!0,recordedAt:d.timestamp.toISOString()});}catch(c){console.warn("[crewx] task:provider-input tracing failed",{cause:c instanceof Error?c.name:typeof c});}}),e.on("task:end",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(c))return;let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(c,An(l)),nr(c,l)&&this.heartbeatTaskIds.delete(c),this.flushTaskLogs(c);let f=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{},...d.error.mode?{mode:d.error.mode}:{}}):null,h=d.result??null,m=!1,k=d.metadata?.suppressPartialResultRecovery===!0;if(d.error&&!k&&(!h||h.trim()==="")){let E=this.recoverPartialResult(c,d,l);E&&(h=E,m=!0);}n.finishTask({id:c,status:d.error?"failed":"success",result:h,error:f,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,usagePresent:d.inputTokens!==void 0||d.outputTokens!==void 0||d.cachedInputTokens!==void 0,usageComplete:d.usageComplete,model:d.model??null,runEpoch:l,partialResultRecovered:m});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)nr(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let s=await Ku(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(s.status==="failed"||s.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:s.status,...s.error?{error:s.error}:{}});}catch(s){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:s instanceof Error?s.name:typeof s});}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=uc(n),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=bg){this.flushTaskLogs(e);return}if(!r.timer){let s=setTimeout(()=>{let o=this.queues.get(e);!o||o.timer!==s||(o.timer=void 0,this.flushTaskLogs(e));},vg);r.timer=s;}}recoverPartialResult(e,n,r){try{let s=this.taskRepo;if(!s)return;let o=s.getTask(e);if(!o||o.status!=="running"||An(o.run_epoch)!==An(r))return;let i=cc(o.metadata),u=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=os({taskLogRepository:s,taskId:e,provider:u,model:o.model});if(!d?.adapter.extractPartialText)return;let c=d.adapter.extractPartialText(d.stdout);return !c||!c.trim()||at(c,u)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let s=An(n.run_epoch),o=cc(n.metadata??null),i=o.ownership==="runner"?"runner":"caller";if(i==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let u=typeof o.providerPid=="number"&&Number.isSafeInteger(o.providerPid)&&o.providerPid>0?o.providerPid:void 0,d=i==="runner"?u:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if($i(r),d!==void 0){let c;try{c=await It(d,{signal:St});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(c.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:c.error??"process termination failed"});return}}try{let c=e.finalizeTaskStop({id:r,runEpoch:s,method:us(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&nr(r,s)&&this.heartbeatTaskIds.delete(r);}catch(c){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:c instanceof Error?c.name:typeof c});}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,s=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,s);}let o=this.queues.get(e);o&&o.entries.length===0&&(o.timer&&clearTimeout(o.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let s=Cg(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[s.code]=(this.metrics.appendFailureByCode[s.code]??0)+1,this.metrics.appendFailureByCause[s.cause]=(this.metrics.appendFailureByCause[s.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:s.code,cause:s.cause,pendingEntries:n.length,pendingBytes:r});}};g();g();g();Tt();Dt();Pt();kt();Wt();Mr();Zn();g();function ms(t){return t!==null&&t!==""}function Lg(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":ms(t.parent_task_id)||ms(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function lc(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&ms(e)?e:null}}function ks(t){let e=Lg(t),n=ms(t.caller_agent_id)?t.caller_agent_id:null,r=t.parent_thread_id!==null&&t.parent_thread_id!==t.thread_id;return {origin:e==="human"?"direct":"delegated",delegatedByAgentId:e==="agent"?n??(r&&t.parent_agent_id||null):null}}function pc(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?lc(t.creator_actor_kind,t.creator_actor_id):e?ks(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?lc(t.created_by_kind,t.created_by_id):n?ks(n):void 0}function lr(t){return Qn(t)}function Fg({metadata:t,...e}){return {...e,status:xe({...e,metadata:t}),terminalReason:ze({...e,metadata:t})??null}}var pr=32,_c=100,Bg=["running","failed"];function Wg(t){return t==="running"?0:t==="failed"?1:2}function gc(t,e){return t[0]!==e[0]?t[0]-e[0]:t[1]!==e[1]?t[1]===null?1:e[1]===null||t[1]<e[1]?-1:1:t[2]<e[2]?-1:t[2]>e[2]?1:0}function Gg(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function jg(t){try{let e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(Array.isArray(e)&&e.length===3&&Number.isInteger(e[0])&&e[0]>=0&&e[0]<=2&&(e[1]===null||typeof e[1]=="string")&&typeof e[2]=="string")return [e[0],e[1],e[2]]}catch{}throw new _("VALIDATION","Invalid descendant cursor")}function hc(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function yi(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function Kg(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function wi(t,e,n,r){let s=Kg(e);s&&(t[s]+=r,t.total+=r,s==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var ys=900,mc=20;function kc(t,e){return (t?.origin??"direct")===e}function Tc(t,e){let n=new Date(e.updated_at).getTime()-new Date(t.updated_at).getTime();return n!==0?n:t.id.localeCompare(e.id)}var On=class extends _{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function Nn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function zg(t){let n=Nn(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}}function yc(t,e,n){return t.get(drizzleOrm.sql`
367
+ `;Ru.appendFileSync(r,i,"utf8"),this.logFiles.delete(n.traceId);}catch{}}));}detach(e){this.unsubs.forEach(n=>n()),this.unsubs=[],this.logFiles.clear();}};g();g();var ji=Symbol.for("crewx.interceptor.run-stops");function cl(){let t=globalThis,e=t[ji];if(e)return e;let n=new Map;return t[ji]=n,n}function Ki(t){let e=cl().get(t);return e?(e.abort(),true):false}g();var sn=new Map;function Ir(t){let e=me__namespace.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 Vi(t){let e=Ir(t);return crypto.createHash("sha256").update(e).digest("hex")}function Xi(t){let e=Ir(t),n=sn.get(e);if(n!==void 0)return n;let r=e;try{let s=me__namespace.join(e,".git");if(!Ru.lstatSync(s).isFile())return sn.set(e,r),r;let o=/^gitdir:\s*(.+?)\s*$/i.exec(Ru.readFileSync(s,"utf8").trim());if(!o)return sn.set(e,r),r;let i=o[1],u=me__namespace.isAbsolute(i)?i:me__namespace.resolve(me__namespace.dirname(s),i),d=Ru.readFileSync(me__namespace.join(u,"commondir"),"utf8").trim();if(!d)return sn.set(e,r),r;let c=me__namespace.isAbsolute(d)?d:me__namespace.resolve(u,d);if(me__namespace.basename(c)!==".git"||!Ru.statSync(c).isDirectory())return sn.set(e,r),r;let l=Ir(Ru.realpathSync.native(e)),p=Ir(Ru.realpathSync.native(me__namespace.dirname(c)));(l===p||(p.endsWith("/")?l.startsWith(p):l.startsWith(`${p}/`)))&&(r=p);}catch{}return sn.set(e,r),r}wt();li();fn();jo();ir();ci();Gr();var kh=200,Th=200;function yh(t){if(typeof t!="object"||t===null||!("code"in t))return;let e=t.code;return typeof e=="string"&&e.length>0?e:void 0}function wh(t){let e=t instanceof _?t.code:void 0,n=t instanceof _?t.cause:t,r=yh(n);return {code:e??r??"DB_ERROR",cause:r??(n instanceof Error?n.name:e??typeof n)}}function bc(t){return Buffer.byteLength(JSON.stringify(t),"utf8")}function Eh(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vc(t){if(!t)return {};try{let e=JSON.parse(t);return Eh(e)?e:{}}catch{return {}}}function On(t){return typeof t=="number"&&Number.isFinite(t)?Math.trunc(t):0}var Rh=new Set(["workflow","mcp"]),Ni=class extends yt{name="sqlite-tracing";unsubs=[];dbPath;version;inheritWorktreeOwner;runnerIdentity;taskRepo;heartbeatTaskIds=new Set;ownedTaskRuns=new Map;ignoredDetachedTaskIds=new Set;queues=new Map;metrics={flushCount:0,flushedEntries:0,maxQueueEntries:0,maxQueueBytes:0,appendFailureCount:0,appendFailureEntries:0,appendFailureBytes:0,appendFailureByCode:{},appendFailureByCause:{}};constructor(e){super();let n=process.env.CREWX_DB;this.dbPath=e?.dbRoot!==void 0?me.join(e.dbRoot,".crewx","crewx.db"):n??me.join(ea.homedir(),".crewx","crewx.db"),this.version=e?.version??"unknown",this.inheritWorktreeOwner=e?.inheritWorktreeOwner===true;let r=e?.runnerIdentity;this.runnerIdentity={detachedRunner:r?.detachedRunner===true,assignedTaskId:r?.detachedRunner===true&&r.assignedTaskId?.trim()||void 0};}attach(e){let n=new pr({dbPath:this.dbPath});n.resolveDbPath(),this.taskRepo=n;let r=process.cwd(),s=Ru.existsSync(me.join(r,"crewx.yaml"))||Ru.existsSync(me.join(r,"crewx.yml")),o=this.inheritWorktreeOwner?Xi(r):r,i=s?Vi(o):null,u=process.argv.join(" ");this.unsubs.push(e.on("task:start",d=>{try{let c=d.callerAgentId??null,l=d.parentTaskId??null,p=d.rootTraceId??d.traceId,{detachedRunner:f,assignedTaskId:h}=this.runnerIdentity,m=h??d.traceId,k=On(d.metadata?.runEpoch),E=f?"runner":"caller",v=d.workspaceId??i,w=f?n.getTask(m):void 0,x=d.pid??null,I={...d.metadata??{provider:d.provider??"cli/claude"},ownership:E,...f&&x!==null?{providerPid:x}:{}},O=JSON.stringify(I);if(f&&w?.status==="running"&&w.pid!==null&&k===0){this.ignoredDetachedTaskIds.add(m);return}n.startTask({id:m,agentId:d.agentRef.replace(/^@/,""),prompt:d.message,mode:d.mode,status:"running",actorKind:d.actorKind??null,actorId:d.actorId??null,pid:f?process.pid:x,startedAt:d.timestamp.toISOString(),crewxVersion:this.version,platform:d.platform??"cli",model:d.model??null,renderedPrompt:d.renderedPrompt??null,securityKey:d.renderedPrompt==null?null:d.securityKey??null,command:u,codingAgentCommand:d.codingAgentCommand??null,workspaceId:v,projectId:d.projectId??null,callerAgentId:c,parentTaskId:l,traceId:p,metadata:O,threadId:d.threadId??null,cwd:d.cwd??null}),n.updateTaskOwnership({id:m,runEpoch:k,ownership:E,...f?{providerPid:x}:{},runtime:{model:d.model??null,renderedPrompt:d.renderedPrompt??null,codingAgentCommand:d.codingAgentCommand??null,metadata:I}})?this.recordOwnedTaskRun({taskId:m,runEpoch:k,workspaceId:v,ownership:E}):console.warn("[crewx] task execution metadata not recorded",{taskId:m,runEpoch:k,ownership:E}),Rh.has(d.platform??"cli")||ic(n,{taskId:m,runEpoch:k,onStopRequested:Tt=>this.handleStopRequested(n,Tt)})&&this.heartbeatTaskIds.add(m);}catch(c){console.warn("[crewx] task:start tracing failed",{cause:c instanceof Error?c.name:typeof c});}}),e.on("task:output",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;this.enqueueLog(c,{timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output});}catch(c){let l={timestamp:d.timestamp.toISOString(),level:d.level??"stdout",message:d.output};this.recordAppendFailure(c,[l],bc(l));}}),e.on("task:run-update",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;let l=On(d.runEpoch),p=this.runnerIdentity.detachedRunner;n.updateTaskOwnership({id:c,runEpoch:l,ownership:p?"runner":"caller",...p&&d.pid!==void 0?{providerPid:d.pid}:{},runtime:{...d.model!==void 0?{model:d.model}:{},...d.renderedPrompt!==void 0?{renderedPrompt:d.renderedPrompt}:{},...d.securityKey!==void 0?{securityKey:d.securityKey}:{},...d.codingAgentCommand!==void 0?{codingAgentCommand:d.codingAgentCommand}:{},...d.metadata?{metadata:d.metadata}:{}}}),!p&&d.pid!==void 0&&n.recordTaskPid({id:c,runEpoch:l,pid:d.pid});}catch(c){console.warn("[crewx] task:run-update tracing failed",{cause:c instanceof Error?c.name:typeof c});}}),e.on("task:provider-input",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.has(c))return;n.recordProviderInput({id:c,runEpoch:d.runEpoch,input:d.input,keyWrapSkipped:d.keyWrapSkipped,interceptedRequest:d.interceptedRequest===!0,recordedAt:d.timestamp.toISOString()});}catch(c){console.warn("[crewx] task:provider-input tracing failed",{cause:c instanceof Error?c.name:typeof c});}}),e.on("task:end",d=>{try{let c=this.resolveTaskId(d.traceId);if(this.ignoredDetachedTaskIds.delete(c))return;let l=typeof d.metadata?.runEpoch=="number"?d.metadata.runEpoch:null;this.removeOwnedTaskRun(c,On(l)),or(c,l)&&this.heartbeatTaskIds.delete(c),this.flushTaskLogs(c);let f=d.error?JSON.stringify({code:d.error.code,message:d.error.message,...d.error.providerCode?{providerCode:d.error.providerCode}:{},...d.error.mode?{mode:d.error.mode}:{}}):null,h=d.result??null,m=!1,k=d.metadata?.suppressPartialResultRecovery===!0;if(d.error&&!k&&(!h||h.trim()==="")){let E=this.recoverPartialResult(c,d,l);E&&(h=E,m=!0);}n.finishTask({id:c,status:d.error?"failed":"success",result:h,error:f,completedAt:d.timestamp.toISOString(),durationMs:d.durationMs,exitCode:d.exitCode??null,inputTokens:d.inputTokens??0,outputTokens:d.outputTokens??0,cachedInputTokens:d.cachedInputTokens??0,costUsd:d.costUsd??0,usagePresent:d.inputTokens!==void 0||d.outputTokens!==void 0||d.cachedInputTokens!==void 0,usageComplete:d.usageComplete,model:d.model??null,runEpoch:l,partialResultRecovered:m});}catch{}}));}detach(e){try{this.flushAllTaskLogs();}finally{this.clearAllTimers();for(let n of this.heartbeatTaskIds)or(n);this.heartbeatTaskIds.clear(),this.ownedTaskRuns.clear(),this.unsubs.forEach(n=>n()),this.unsubs=[],this.queues.clear(),this.ignoredDetachedTaskIds.clear(),this.taskRepo=void 0;}}listOwnedRunningTasks(){return Array.from(this.ownedTaskRuns.values(),e=>({...e}))}async stopOwnedRunningTasksForHostShutdown(){let e=this.taskRepo;if(!e)return;let n=this.listOwnedRunningTasks();for(let r of n)try{let s=await pc(e,{taskId:r.taskId,expectedRunEpoch:r.runEpoch,workspaceId:r.workspaceId});(s.status==="failed"||s.status==="ownership_unverified")&&console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,status:s.status,...s.error?{error:s.error}:{}});}catch(s){console.warn("[crewx] host-shutdown task stop failed",{taskId:r.taskId,runEpoch:r.runEpoch,cause:s instanceof Error?s.name:typeof s});}}getMetrics(){let e=0,n=0;for(let r of this.queues.values())e+=r.entries.length,n+=r.bytes;return {...this.metrics,appendFailureByCode:{...this.metrics.appendFailureByCode},appendFailureByCause:{...this.metrics.appendFailureByCause},pendingQueueEntries:e,pendingQueueBytes:n}}resolveTaskId(e){return this.runnerIdentity.detachedRunner?this.runnerIdentity.assignedTaskId??e:e}recordOwnedTaskRun(e){let n=this.ownedTaskRuns.get(e.taskId);n&&n.runEpoch>e.runEpoch||this.ownedTaskRuns.set(e.taskId,{...e});}removeOwnedTaskRun(e,n){let r=this.ownedTaskRuns.get(e);!r||r.runEpoch!==n||this.ownedTaskRuns.delete(e);}enqueueLog(e,n){let r=this.queues.get(e);if(r||(r={entries:[],bytes:0},this.queues.set(e,r)),r.entries.push(n),r.bytes+=bc(n),this.metrics.maxQueueEntries=Math.max(this.metrics.maxQueueEntries,r.entries.length),this.metrics.maxQueueBytes=Math.max(this.metrics.maxQueueBytes,r.bytes),r.entries.length>=kh){this.flushTaskLogs(e);return}if(!r.timer){let s=setTimeout(()=>{let o=this.queues.get(e);!o||o.timer!==s||(o.timer=void 0,this.flushTaskLogs(e));},Th);r.timer=s;}}recoverPartialResult(e,n,r){try{let s=this.taskRepo;if(!s)return;let o=s.getTask(e);if(!o||o.status!=="running"||On(o.run_epoch)!==On(r))return;let i=vc(o.metadata),u=typeof i.provider=="string"?i.provider:typeof n.metadata?.provider=="string"?n.metadata.provider:void 0;if(!u)return;let d=ls({taskLogRepository:s,taskId:e,provider:u,model:o.model});if(!d?.adapter.extractPartialText)return;let c=d.adapter.extractPartialText(d.stdout);return !c||!c.trim()||ct(c,u)?void 0:c}catch{return}}async handleStopRequested(e,n){let r=n.id;if(!r)return;let s=On(n.run_epoch),o=vc(n.metadata??null),i=o.ownership==="runner"?"runner":"caller";if(i==="runner"&&n.pid!==process.pid){console.warn("[crewx] ignored stop request for task owned by another runner",{taskId:r});return}let u=typeof o.providerPid=="number"&&Number.isSafeInteger(o.providerPid)&&o.providerPid>0?o.providerPid:void 0,d=i==="runner"?u:typeof n.pid=="number"&&n.pid>0?n.pid:void 0;if(Ki(r),d!==void 0){let c;try{c=await Nt(d,{signal:Ot});}catch(l){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:l instanceof Error?l.name:typeof l});return}if(c.status==="failed"){console.warn("[crewx] cooperative task stop failed",{taskId:r,cause:c.error??"process termination failed"});return}}try{let c=e.finalizeTaskStop({id:r,runEpoch:s,method:gs(n.stop_requested_at)}),l=e.getTask(r);(c||l?.status!=="running")&&or(r,s)&&this.heartbeatTaskIds.delete(r);}catch(c){console.warn("[crewx] cooperative task stop finalization failed",{taskId:r,cause:c instanceof Error?c.name:typeof c});}}flushTaskLogs(e){let n=this.queues.get(e);if(!n||n.entries.length===0){n?.timer&&clearTimeout(n.timer),this.queues.delete(e);return}n.timer&&(clearTimeout(n.timer),n.timer=void 0);let r=n.entries,s=n.bytes;n.entries=[],n.bytes=0,this.metrics.flushCount+=1;try{this.taskRepo?.appendLogs(e,r),this.metrics.flushedEntries+=r.length;}catch(i){this.recordAppendFailure(i,r,s);}let o=this.queues.get(e);o&&o.entries.length===0&&(o.timer&&clearTimeout(o.timer),this.queues.delete(e));}flushAllTaskLogs(){for(let e of [...this.queues.keys()])this.flushTaskLogs(e);}clearAllTimers(){for(let e of this.queues.values())e.timer&&(clearTimeout(e.timer),e.timer=void 0);}recordAppendFailure(e,n,r){let s=wh(e);this.metrics.appendFailureCount+=1,this.metrics.appendFailureEntries+=n.length,this.metrics.appendFailureBytes+=r,this.metrics.appendFailureByCode[s.code]=(this.metrics.appendFailureByCode[s.code]??0)+1,this.metrics.appendFailureByCause[s.cause]=(this.metrics.appendFailureByCause[s.cause]??0)+1,console.warn("[crewx] sqlite tracing append failed",{code:s.code,cause:s.cause,pendingEntries:n.length,pendingBytes:r});}};g();g();g();Et();$t();Ht();wt();zt();Ur();nr();g();function Rs(t){return t!==null&&t!==""}function Sh(t){return t.schedule_id!==null&&t.schedule_id!==void 0?"system":Rs(t.parent_task_id)||Rs(t.caller_agent_id)?"agent":t.platform==="workflow"?"system":"human"}function xc(t,e){return {origin:t==="human"?"direct":"delegated",delegatedByAgentId:t==="agent"&&Rs(e)?e:null}}function Ss(t){let e=Sh(t),n=Rs(t.caller_agent_id)?t.caller_agent_id:null,r=t.parent_thread_id!==null&&t.parent_thread_id!==t.thread_id;return {origin:e==="human"?"direct":"delegated",delegatedByAgentId:e==="agent"?n??(r&&t.parent_agent_id||null):null}}function Cc(t,e,n){return t.creator_task_id!==null&&t.creator_pointer_unverified===0?t.creator_actor_kind!==null?xc(t.creator_actor_kind,t.creator_actor_id):e?Ss(e):{origin:"direct",delegatedByAgentId:null}:t.created_by_kind!==null?xc(t.created_by_kind,t.created_by_id):n?Ss(n):void 0}function _r(t){return tr(t)}function vh({metadata:t,...e}){return {...e,status:De({...e,metadata:t}),terminalReason:Xe({...e,metadata:t})??null}}var gr=32,Pc=100,xh=["running","failed"];function Ch(t){return t==="running"?0:t==="failed"?1:2}function Lc(t,e){return t[0]!==e[0]?t[0]-e[0]:t[1]!==e[1]?t[1]===null?1:e[1]===null||t[1]<e[1]?-1:1:t[2]<e[2]?-1:t[2]>e[2]?1:0}function Dh(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function Ph(t){try{let e=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(Array.isArray(e)&&e.length===3&&Number.isInteger(e[0])&&e[0]>=0&&e[0]<=2&&(e[1]===null||typeof e[1]=="string")&&typeof e[2]=="string")return [e[0],e[1],e[2]]}catch{}throw new _("VALIDATION","Invalid descendant cursor")}function Mc(t,e,n){return t===void 0||!Number.isFinite(t)?e:Math.min(n,Math.max(1,Math.trunc(t)))}function bi(t){return {total:0,running:0,pending:0,paused:0,success:0,failed:0,stopped:0,runnerLost:0,checkedAt:t}}function Lh(t){switch(t){case "running":case "pending":case "paused":case "success":case "failed":case "stopped":return t;default:return}}function vi(t,e,n,r){let s=Lh(e);s&&(t[s]+=r,t.total+=r,s==="failed"&&n==="runner_lost"&&(t.runnerLost+=r));}var As=900,$c=20;function Hc(t,e){return (t?.origin??"direct")===e}function Uc(t,e){let n=new Date(e.updated_at).getTime()-new Date(t.updated_at).getTime();return n!==0?n:t.id.localeCompare(e.id)}var Nn=class extends _{reason;constructor(e,n=e){super("VALIDATION",n),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function bn(t){if(!t)return {};try{let e=JSON.parse(t);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Mh(t){let n=bn(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}}function qc(t,e,n){return t.get(drizzleOrm.sql`
349
368
  SELECT id
350
369
  FROM tasks INDEXED BY idx_tasks_thread_id
351
370
  WHERE thread_id = ${e}
352
371
  AND id <> ${n}
353
372
  LIMIT 1
354
- `)!==void 0}function Jg(t,e,n){let r=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e),s=t.select({pinned:T.pinned,metadata:T.metadata}).from(T).where(r).get();if(!s)return null;let o=s.pinned?0:1,i=Nn(s.metadata);if(o){let u=n?drizzleOrm.and(drizzleOrm.eq(T.pinned,1),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.pinned,1),d=t.select({metadata:T.metadata}).from(T).where(u).all(),c=null;for(let l of d){let p=Nn(l.metadata);typeof p.pinOrder=="number"&&(c===null||p.pinOrder<c)&&(c=p.pinOrder);}i.pinOrder=c===null?0:c-1;}else delete i.pinOrder;return t.update(T).set({pinned:o,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(r).run(),{pinned:!!o}}function Vg(t,e,n){for(let r=0;r<e.length;r++){let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e[r]),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e[r]),o=t.select({metadata:T.metadata}).from(T).where(s).get();if(!o)continue;let i=Nn(o.metadata);i.pinOrder=r+1,t.update(T).set({metadata:JSON.stringify(i)}).where(s).run();}}var ws=class extends Re{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=he.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=he.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}else if(!fs$1.existsSync(n))throw new _("NOT_FOUND","Database not found");let r=M(n);if(e)try{Pe(r.db,n);}catch(s){throw r.close(),s}return r}topLevelTaskPredicateSql(e="child",n){let r=n?`tasks parent INDEXED BY ${n}`:"tasks parent";return drizzleOrm.sql.raw(`NOT EXISTS (
373
+ `)!==void 0}function $h(t,e,n){let r=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e),s=t.select({pinned:T.pinned,metadata:T.metadata}).from(T).where(r).get();if(!s)return null;let o=s.pinned?0:1,i=bn(s.metadata);if(o){let u=n?drizzleOrm.and(drizzleOrm.eq(T.pinned,1),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.pinned,1),d=t.select({metadata:T.metadata}).from(T).where(u).all(),c=null;for(let l of d){let p=bn(l.metadata);typeof p.pinOrder=="number"&&(c===null||p.pinOrder<c)&&(c=p.pinOrder);}i.pinOrder=c===null?0:c-1;}else delete i.pinOrder;return t.update(T).set({pinned:o,metadata:Object.keys(i).length>0?JSON.stringify(i):null}).where(r).run(),{pinned:!!o}}function Hh(t,e,n){for(let r=0;r<e.length;r++){let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e[r]),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e[r]),o=t.select({metadata:T.metadata}).from(T).where(s).get();if(!o)continue;let i=bn(o.metadata);i.pinOrder=r+1,t.update(T).set({metadata:JSON.stringify(i)}).where(s).run();}}var Os=class extends Se{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=me.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(e){let s=me.dirname(n);Ru.existsSync(s)||Ru.mkdirSync(s,{recursive:true});}else if(!Ru.existsSync(n))throw new _("NOT_FOUND","Database not found");let r=M(n);if(e)try{Me(r.db,n);}catch(s){throw r.close(),s}return r}topLevelTaskPredicateSql(e="child",n){let r=n?`tasks parent INDEXED BY ${n}`:"tasks parent";return drizzleOrm.sql.raw(`NOT EXISTS (
355
374
  SELECT 1 FROM ${r}
356
375
  WHERE parent.id = ${e}.parent_task_id
357
376
  AND parent.thread_id = ${e}.thread_id
358
- )`)}workflowAnchorPredicateSql(e){let n=Et.map(r=>`OR ${e}.metadata LIKE '%"kind":"${r}"%'`).join(`
377
+ )`)}workflowAnchorPredicateSql(e){let n=It.map(r=>`OR ${e}.metadata LIKE '%"kind":"${r}"%'`).join(`
359
378
  `);return drizzleOrm.sql.raw(`COALESCE(
360
379
  ${e}.agent_id = 'workflow'
361
380
  ${n}
@@ -394,11 +413,11 @@ Message: ${n.message}
394
413
  )
395
414
  )`}findAllThreadsQuery(e,n){let r=[];e&&r.push(drizzleOrm.sql`workspace_id = ${e}`),n&&r.push(drizzleOrm.sql`created_by_kind = ${n}`);let s=r.length>0?drizzleOrm.sql` WHERE ${drizzleOrm.sql.join(r,drizzleOrm.sql` AND `)}`:drizzleOrm.sql``;return drizzleOrm.sql`SELECT * FROM threads${s} ORDER BY updated_at DESC`}findThreadIdsQuery(e){return e?drizzleOrm.sql`SELECT id FROM threads INDEXED BY idx_threads_ws_updated
396
415
  WHERE workspace_id = ${e}
397
- ORDER BY updated_at DESC`:drizzleOrm.sql`SELECT id FROM threads`}readThreadIds(e,n="Failed to find thread ids"){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!fs$1.existsSync(i))continue;let u=M(i);try{let d=u.db.all(this.findThreadIdsQuery(e));for(let c of d)s.has(c.id)||(s.add(c.id),o.push(c.id));}catch(d){throw new _("DB_ERROR",n,d)}finally{u.close();}}return o}findThreadSortKeysQuery(e){return drizzleOrm.sql`SELECT id, updated_at
416
+ ORDER BY updated_at DESC`:drizzleOrm.sql`SELECT id FROM threads`}readThreadIds(e,n="Failed to find thread ids"){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!Ru.existsSync(i))continue;let u=M(i);try{let d=u.db.all(this.findThreadIdsQuery(e));for(let c of d)s.has(c.id)||(s.add(c.id),o.push(c.id));}catch(d){throw new _("DB_ERROR",n,d)}finally{u.close();}}return o}findThreadSortKeysQuery(e){return drizzleOrm.sql`SELECT id, updated_at
398
417
  FROM threads INDEXED BY idx_threads_ws_updated
399
- WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!fs$1.existsSync(o))continue;let i=M(o);try{let u=i.db.all(this.findThreadSortKeysQuery(e));for(let d of u)r.has(d.id)||(r.add(d.id),s.push(d));}catch(u){throw new _("DB_ERROR","Failed to find recent direct threads",u)}finally{i.close();}}return s}readThreadRowsByIds(e,n,r="Failed to find threads by ids"){if(e.length===0)return [];let s=this.resolveDbPaths(),o=new Set,i=[];for(let u of s){if(!fs$1.existsSync(u))continue;let d=M(u);try{for(let c=0;c<e.length;c+=ys){let l=e.slice(c,c+ys),p=drizzleOrm.inArray(T.id,l),f=n?drizzleOrm.and(p,drizzleOrm.eq(T.workspace_id,n)):p,h=d.db.select().from(T).where(f).all();for(let m of h)o.has(m.id)||(o.add(m.id),i.push(m));}}catch(c){throw new _("DB_ERROR",r,c)}finally{d.close();}}return i}readThreadRows(e,n,r="Failed to find all threads"){let s=this.resolveDbPaths(),o=new Set,i=[];for(let u of s){if(!fs$1.existsSync(u))continue;let d=M(u);try{let c=d.db.all(this.findAllThreadsQuery(e,n));for(let l of c)o.has(l.id)||(o.add(l.id),i.push(l));}catch(c){throw new _("DB_ERROR",r,c)}finally{d.close();}}return i}findAllThreads(e,n){return this.readThreadRows(e,n)}explainFindAllThreadsPlan(e,n){let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=M(s);try{return o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findAllThreadsQuery(e,n)}`).map(u=>u.detail)}finally{o.close();}}return []}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!fs$1.existsSync(i))continue;let u=M(i);try{let d=drizzleOrm.or(drizzleOrm.inArray(T.id,e),drizzleOrm.inArray(T.title,e)),c=n?drizzleOrm.and(d,drizzleOrm.eq(T.workspace_id,n)):d,l=u.db.select().from(T).where(c).orderBy(drizzleOrm.desc(T.updated_at)).all();for(let p of l)s.has(p.id)||(s.add(p.id),o.push(p));}catch(d){throw new _("DB_ERROR","Failed to find threads by ids or titles",d)}finally{u.close();}}return o}findThreadById(e,n){let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=M(s);try{let i=drizzleOrm.eq(T.id,e),u=n?drizzleOrm.and(i,drizzleOrm.eq(T.workspace_id,n)):i,d=o.db.select().from(T).where(u).limit(1).get()??void 0;if(d)return d}catch(i){throw new _("DB_ERROR","Failed to find thread by id",i)}finally{o.close();}}}createAppLaunchThread(e){let n=this.openHandle(true);try{return n.db.transaction(r=>{if(!r.select({id:ne.id}).from(ne).where(drizzleOrm.eq(ne.id,e.workspaceId)).limit(1).get())throw new _("NOT_FOUND","Workspace not found");let o=r.select().from(T).where(drizzleOrm.eq(T.id,e.threadId)).limit(1).get();if(o){let l=Nn(o.metadata).appLaunch,p=l&&typeof l=="object"&&!Array.isArray(l)?l.appId:void 0,f=r.get(drizzleOrm.sql`
418
+ WHERE workspace_id = ${e}`}readThreadSortKeys(e){let n=this.resolveDbPaths(),r=new Set,s=[];for(let o of n){if(!Ru.existsSync(o))continue;let i=M(o);try{let u=i.db.all(this.findThreadSortKeysQuery(e));for(let d of u)r.has(d.id)||(r.add(d.id),s.push(d));}catch(u){throw new _("DB_ERROR","Failed to find recent direct threads",u)}finally{i.close();}}return s}readThreadRowsByIds(e,n,r="Failed to find threads by ids"){if(e.length===0)return [];let s=this.resolveDbPaths(),o=new Set,i=[];for(let u of s){if(!Ru.existsSync(u))continue;let d=M(u);try{for(let c=0;c<e.length;c+=As){let l=e.slice(c,c+As),p=drizzleOrm.inArray(T.id,l),f=n?drizzleOrm.and(p,drizzleOrm.eq(T.workspace_id,n)):p,h=d.db.select().from(T).where(f).all();for(let m of h)o.has(m.id)||(o.add(m.id),i.push(m));}}catch(c){throw new _("DB_ERROR",r,c)}finally{d.close();}}return i}readThreadRows(e,n,r="Failed to find all threads"){let s=this.resolveDbPaths(),o=new Set,i=[];for(let u of s){if(!Ru.existsSync(u))continue;let d=M(u);try{let c=d.db.all(this.findAllThreadsQuery(e,n));for(let l of c)o.has(l.id)||(o.add(l.id),i.push(l));}catch(c){throw new _("DB_ERROR",r,c)}finally{d.close();}}return i}findAllThreads(e,n){return this.readThreadRows(e,n)}explainFindAllThreadsPlan(e,n){let r=this.resolveDbPaths();for(let s of r){if(!Ru.existsSync(s))continue;let o=M(s);try{return o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findAllThreadsQuery(e,n)}`).map(u=>u.detail)}finally{o.close();}}return []}findThreadsByIdsOrTitles(e,n){if(e.length===0)return [];let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!Ru.existsSync(i))continue;let u=M(i);try{let d=drizzleOrm.or(drizzleOrm.inArray(T.id,e),drizzleOrm.inArray(T.title,e)),c=n?drizzleOrm.and(d,drizzleOrm.eq(T.workspace_id,n)):d,l=u.db.select().from(T).where(c).orderBy(drizzleOrm.desc(T.updated_at)).all();for(let p of l)s.has(p.id)||(s.add(p.id),o.push(p));}catch(d){throw new _("DB_ERROR","Failed to find threads by ids or titles",d)}finally{u.close();}}return o}findThreadById(e,n){let r=this.resolveDbPaths();for(let s of r){if(!Ru.existsSync(s))continue;let o=M(s);try{let i=drizzleOrm.eq(T.id,e),u=n?drizzleOrm.and(i,drizzleOrm.eq(T.workspace_id,n)):i,d=o.db.select().from(T).where(u).limit(1).get()??void 0;if(d)return d}catch(i){throw new _("DB_ERROR","Failed to find thread by id",i)}finally{o.close();}}}createAppLaunchThread(e){let n=this.openHandle(true);try{return n.db.transaction(r=>{if(!r.select({id:ne.id}).from(ne).where(drizzleOrm.eq(ne.id,e.workspaceId)).limit(1).get())throw new _("NOT_FOUND","Workspace not found");let o=r.select().from(T).where(drizzleOrm.eq(T.id,e.threadId)).limit(1).get();if(o){let l=bn(o.metadata).appLaunch,p=l&&typeof l=="object"&&!Array.isArray(l)?l.appId:void 0,f=r.get(drizzleOrm.sql`
400
419
  SELECT COUNT(*) AS count FROM tasks WHERE thread_id = ${e.threadId}
401
- `)?.count??0;return o.workspace_id===e.workspaceId&&p===e.appId&&o.message_count===0&&o.first_message===null&&o.last_message===null&&f===0?{status:"existing",thread:o}:{status:"conflict"}}let i=new Date().toISOString(),u=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(T).values({id:e.threadId,workspace_id:e.workspaceId,platform:e.platform,title:e.title,title_locked:1,created_by_kind:"human",created_by_id:e.createdById,created_by_task_id:null,message_count:0,first_message:null,last_message:null,metadata:u,created_at:i,updated_at:i}).run();let d=r.select().from(T).where(drizzleOrm.eq(T.id,e.threadId)).limit(1).get();if(!d)throw new _("DB_ERROR","App-launch thread could not be read after insert");return {status:"created",thread:d}},{behavior:"immediate"})}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to create App-launch thread",r)}finally{n.close();}}threadExists(e,n){let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=M(s);try{let i=drizzleOrm.eq(T.id,e),u=n?drizzleOrm.and(i,drizzleOrm.eq(T.workspace_id,n)):i;if(o.db.select({id:T.id}).from(T).where(u).limit(1).get())return !0}catch(i){throw new _("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),s=0,o=0,i=0,u=0,d=0,c=0,l=0,p=0,f=0,h=0,m=new Set;for(let k of r){if(!fs$1.existsSync(k))continue;let E=M(k);try{let v=E.db.get(drizzleOrm.sql`
420
+ `)?.count??0;return o.workspace_id===e.workspaceId&&p===e.appId&&o.message_count===0&&o.first_message===null&&o.last_message===null&&f===0?{status:"existing",thread:o}:{status:"conflict"}}let i=new Date().toISOString(),u=JSON.stringify({appLaunch:{appId:e.appId,...e.initialAgentId===void 0?{}:{initialAgentId:e.initialAgentId}}});r.insert(T).values({id:e.threadId,workspace_id:e.workspaceId,platform:e.platform,title:e.title,title_locked:1,created_by_kind:"human",created_by_id:e.createdById,created_by_task_id:null,message_count:0,first_message:null,last_message:null,metadata:u,created_at:i,updated_at:i}).run();let d=r.select().from(T).where(drizzleOrm.eq(T.id,e.threadId)).limit(1).get();if(!d)throw new _("DB_ERROR","App-launch thread could not be read after insert");return {status:"created",thread:d}},{behavior:"immediate"})}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to create App-launch thread",r)}finally{n.close();}}threadExists(e,n){let r=this.resolveDbPaths();for(let s of r){if(!Ru.existsSync(s))continue;let o=M(s);try{let i=drizzleOrm.eq(T.id,e),u=n?drizzleOrm.and(i,drizzleOrm.eq(T.workspace_id,n)):i;if(o.db.select({id:T.id}).from(T).where(u).limit(1).get())return !0}catch(i){throw new _("DB_ERROR","Failed to check thread existence",i)}finally{o.close();}}return false}aggregateTaskStats(e,n){let r=this.resolveDbPaths(),s=0,o=0,i=0,u=0,d=0,c=0,l=0,p=0,f=0,h=0,m=new Set;for(let k of r){if(!Ru.existsSync(k))continue;let E=M(k);try{let v=E.db.get(drizzleOrm.sql`
402
421
  SELECT count(*) AS cnt
403
422
  FROM tasks child INDEXED BY idx_tasks_thread_id
404
423
  WHERE child.thread_id = ${e}
@@ -428,7 +447,7 @@ Message: ${n.message}
428
447
  FROM descendants
429
448
  JOIN tasks child INDEXED BY idx_tasks_parent_task_id
430
449
  ON child.parent_task_id = descendants.task_id
431
- WHERE descendants.depth < ${pr}
450
+ WHERE descendants.depth < ${gr}
432
451
  ),
433
452
  delegated_ids(task_id) AS (
434
453
  SELECT DISTINCT descendants.task_id
@@ -454,13 +473,13 @@ Message: ${n.message}
454
473
  AND child.agent_id != 'workflow'
455
474
  AND ${this.topLevelTaskPredicateSql()}
456
475
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
457
- `);for(let O of I)m.add(O.agent_id);}catch(v){throw new _("DB_ERROR","Failed to aggregate task stats",v)}finally{E.close();}}return {taskCount:s,inputTokens:o,outputTokens:i,cachedInputTokens:u,costUsd:d,agentIds:Array.from(m),delegated:{taskCount:c,inputTokens:l,outputTokens:p,cachedInputTokens:f,costUsd:h}}}getDescendantSummaryByTaskId(e,n){let r=this.resolveDbPaths(),s={},o=new Date().toISOString();for(let i of r){if(!fs$1.existsSync(i))continue;let u=M(i);try{let d=drizzleOrm.sql`
476
+ `);for(let O of I)m.add(O.agent_id);}catch(v){throw new _("DB_ERROR","Failed to aggregate task stats",v)}finally{E.close();}}return {taskCount:s,inputTokens:o,outputTokens:i,cachedInputTokens:u,costUsd:d,agentIds:Array.from(m),delegated:{taskCount:c,inputTokens:l,outputTokens:p,cachedInputTokens:f,costUsd:h}}}getDescendantSummaryByTaskId(e,n){let r=this.resolveDbPaths(),s={},o=new Date().toISOString();for(let i of r){if(!Ru.existsSync(i))continue;let u=M(i);try{let d=drizzleOrm.sql`
458
477
  SELECT own.id
459
478
  FROM tasks own INDEXED BY idx_tasks_thread_id
460
479
  WHERE own.thread_id = ${e}
461
480
  ${n?drizzleOrm.sql`AND own.workspace_id = ${n}`:drizzleOrm.sql``}
462
481
  `,c=u.db.all(drizzleOrm.sql`
463
- ${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,pr)}
482
+ ${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,gr)}
464
483
  SELECT
465
484
  descendant_ids.root_task_id AS root_task_id,
466
485
  task.status AS status,
@@ -471,7 +490,7 @@ Message: ${n.message}
471
490
  JOIN tasks task ON task.id = descendant_ids.task_id
472
491
  WHERE NOT ${this.descendantSkippedSql("task")}
473
492
  GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
474
- `);for(let l of c){let p=s[l.root_task_id]??=yi(o);wi(p,xe(l),ze(l),l.task_count);}}catch(d){throw new _("DB_ERROR","Failed to aggregate task descendant summaries",d)}finally{u.close();}}return s}listUnreadReplyCandidates(e,n){let r=new Map,s=new Map;for(let{threadId:i,readThroughAt:u}of e)u!==null&&s.set(i,u);if(s.size===0)return r;let o=new Set;for(let i of this.resolveDbPaths()){if(!fs$1.existsSync(i))continue;let u=M(i);try{let d=u.db.all(this.unreadReplyCandidatesQuery(s,n));for(let c of d){if(o.has(c.id))continue;o.add(c.id);let l={id:c.id,threadId:c.thread_id,completedAt:c.completed_at,status:xe(c),result:c.result,error:c.error,metadata:c.metadata},p=r.get(c.thread_id);p?p.push(l):r.set(c.thread_id,[l]);}}catch(d){throw d instanceof _?d:new _("DB_ERROR","Failed to list unread reply candidates",d)}finally{u.close();}}return r}unreadReplyCandidatesQuery(e,n){let r=drizzleOrm.sql.join([...e].map(([o,i])=>drizzleOrm.sql`(${o}, ${i})`),drizzleOrm.sql`, `),s=drizzleOrm.sql.join(Zt.map(o=>drizzleOrm.sql`${o}`),drizzleOrm.sql`, `);return drizzleOrm.sql`
493
+ `);for(let l of c){let p=s[l.root_task_id]??=bi(o);vi(p,De(l),Xe(l),l.task_count);}}catch(d){throw new _("DB_ERROR","Failed to aggregate task descendant summaries",d)}finally{u.close();}}return s}listUnreadReplyCandidates(e,n){let r=new Map,s=new Map;for(let{threadId:i,readThroughAt:u}of e)u!==null&&s.set(i,u);if(s.size===0)return r;let o=new Set;for(let i of this.resolveDbPaths()){if(!Ru.existsSync(i))continue;let u=M(i);try{let d=u.db.all(this.unreadReplyCandidatesQuery(s,n));for(let c of d){if(o.has(c.id))continue;o.add(c.id);let l={id:c.id,threadId:c.thread_id,completedAt:c.completed_at,status:De(c),result:c.result,error:c.error,metadata:c.metadata},p=r.get(c.thread_id);p?p.push(l):r.set(c.thread_id,[l]);}}catch(d){throw d instanceof _?d:new _("DB_ERROR","Failed to list unread reply candidates",d)}finally{u.close();}}return r}unreadReplyCandidatesQuery(e,n){let r=drizzleOrm.sql.join([...e].map(([o,i])=>drizzleOrm.sql`(${o}, ${i})`),drizzleOrm.sql`, `),s=drizzleOrm.sql.join(en.map(o=>drizzleOrm.sql`${o}`),drizzleOrm.sql`, `);return drizzleOrm.sql`
475
494
  WITH watermarks(thread_id, read_through_at) AS (VALUES ${r})
476
495
  SELECT child.id, child.thread_id, child.completed_at, child.status,
477
496
  child.result, child.error, child.metadata
@@ -489,8 +508,8 @@ Message: ${n.message}
489
508
  FROM tasks own INDEXED BY idx_tasks_thread_id
490
509
  WHERE own.thread_id IN (${u})
491
510
  ${n?drizzleOrm.sql`AND own.workspace_id = ${n}`:drizzleOrm.sql``}
492
- `;for(let c of this.resolveDbPaths()){if(!fs$1.existsSync(c))continue;let l=M(c);try{let p=l.db.all(drizzleOrm.sql`
493
- ${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,pr)}
511
+ `;for(let c of this.resolveDbPaths()){if(!Ru.existsSync(c))continue;let l=M(c);try{let p=l.db.all(drizzleOrm.sql`
512
+ ${this.descendantTraversalSql(d,drizzleOrm.sql`SELECT own.task_id FROM own_tasks own`,gr)}
494
513
  SELECT
495
514
  descendant_ids.root_task_id AS root_task_id,
496
515
  task.status AS status,
@@ -501,7 +520,7 @@ Message: ${n.message}
501
520
  JOIN tasks task ON task.id = descendant_ids.task_id
502
521
  WHERE NOT ${this.descendantSkippedSql("task")}
503
522
  GROUP BY descendant_ids.root_task_id, task.status, task.error, task.metadata
504
- `);for(let f of p){let h=o[f.root_task_id]??=yi(i);wi(h,xe(f),ze(f),f.task_count);}}catch(p){throw p instanceof _?p:new _("DB_ERROR","Failed to batch summarize thread task statuses",p)}finally{l.close();}}return {tasksByThread:s,descendantSummaryByTaskId:o}}listDescendantsByTaskId(e,n,r={}){let s=new Set(r.states??Bg),o=hc(r.limit,_c,_c),i=hc(r.maxDepth,pr,pr),u=r.cursor?jg(r.cursor):void 0;for(let d of this.resolveDbPaths()){if(!fs$1.existsSync(d))continue;let c=M(d);try{if(!c.db.get(drizzleOrm.sql`
523
+ `);for(let f of p){let h=o[f.root_task_id]??=bi(i);vi(h,De(f),Xe(f),f.task_count);}}catch(p){throw p instanceof _?p:new _("DB_ERROR","Failed to batch summarize thread task statuses",p)}finally{l.close();}}return {tasksByThread:s,descendantSummaryByTaskId:o}}listDescendantsByTaskId(e,n,r={}){let s=new Set(r.states??xh),o=Mc(r.limit,Pc,Pc),i=Mc(r.maxDepth,gr,gr),u=r.cursor?Ph(r.cursor):void 0;for(let d of this.resolveDbPaths()){if(!Ru.existsSync(d))continue;let c=M(d);try{if(!c.db.get(drizzleOrm.sql`
505
524
  SELECT anchor.id FROM tasks anchor
506
525
  WHERE anchor.id = ${e} AND anchor.workspace_id = ${n}
507
526
  `))continue;let p=drizzleOrm.sql`
@@ -535,11 +554,11 @@ Message: ${n.message}
535
554
  FROM descendant_ids
536
555
  JOIN tasks task ON task.id = descendant_ids.task_id
537
556
  LEFT JOIN tasks parent ON parent.id = task.parent_task_id
538
- `),h=yi(new Date().toISOString()),m=!1,k=[];for(let O of f){if(O.has_deeper&&(m=!0),O.skipped)continue;let S=xe(O);wi(h,S,ze(O),1),s.has(S)&&k.push({row:O,key:[Wg(S),O.started_at?O.started_at:null,O.task_id]});}k.sort((O,S)=>gc(O.key,S.key));let E=u?k.filter(O=>gc(O.key,u)>0):k,v=E.slice(0,o),w=E.length>v.length?Gg(v[v.length-1].key):null,x=new Map;if(v.length>0){let O=c.db.select(re).from(a).where(drizzleOrm.inArray(a.id,v.map(S=>S.row.task_id))).all();for(let S of O)x.set(S.id,lr(S));}let I=[];for(let{row:O}of v){let S=x.get(O.task_id);!S||!O.parent_task_id||I.push({task:S,parentTaskId:O.parent_task_id,parentAgentId:O.parent_agent_id,depth:O.depth});}return {rows:I,summary:h,nextCursor:w,traversalTruncated:m}}catch(l){throw l instanceof _?l:new _("DB_ERROR","Failed to list task descendants",l)}finally{c.close();}}}findInterceptedRequests(e){let n=new Map;if(e.length===0)return n;for(let r of this.resolveDbPaths()){if(!fs$1.existsSync(r))continue;let s=M(r);try{let o=s.db.all(drizzleOrm.sql`
557
+ `),h=bi(new Date().toISOString()),m=!1,k=[];for(let O of f){if(O.has_deeper&&(m=!0),O.skipped)continue;let S=De(O);vi(h,S,Xe(O),1),s.has(S)&&k.push({row:O,key:[Ch(S),O.started_at?O.started_at:null,O.task_id]});}k.sort((O,S)=>Lc(O.key,S.key));let E=u?k.filter(O=>Lc(O.key,u)>0):k,v=E.slice(0,o),w=E.length>v.length?Dh(v[v.length-1].key):null,x=new Map;if(v.length>0){let O=c.db.select(re).from(a).where(drizzleOrm.inArray(a.id,v.map(S=>S.row.task_id))).all();for(let S of O)x.set(S.id,_r(S));}let I=[];for(let{row:O}of v){let S=x.get(O.task_id);!S||!O.parent_task_id||I.push({task:S,parentTaskId:O.parent_task_id,parentAgentId:O.parent_agent_id,depth:O.depth});}return {rows:I,summary:h,nextCursor:w,traversalTruncated:m}}catch(l){throw l instanceof _?l:new _("DB_ERROR","Failed to list task descendants",l)}finally{c.close();}}}findInterceptedRequests(e){let n=new Map;if(e.length===0)return n;for(let r of this.resolveDbPaths()){if(!Ru.existsSync(r))continue;let s=M(r);try{let o=s.db.all(drizzleOrm.sql`
539
558
  SELECT task_id, input FROM task_provider_inputs
540
559
  WHERE run_epoch = 0
541
560
  AND task_id IN (${drizzleOrm.sql.join(e.map(i=>drizzleOrm.sql`${i}`),drizzleOrm.sql`, `)})
542
- `);for(let i of o)n.set(i.task_id,i.input);}catch{}finally{s.close();}}return n}findTopLevelTasks(e,n,r,s){let o=this.resolveDbPaths(),i=s?drizzleOrm.sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${s})`:this.topLevelTaskPredicateSql(),u=new Set,d=[];for(let c of o){if(!fs$1.existsSync(c))continue;let l=M(c);try{let p;r!==void 0?p=l.db.all(drizzleOrm.sql`
561
+ `);for(let i of o)n.set(i.task_id,i.input);}catch{}finally{s.close();}}return n}findTopLevelTasks(e,n,r,s){let o=this.resolveDbPaths(),i=s?drizzleOrm.sql`(${this.topLevelTaskPredicateSql()} OR child.agent_id = ${s})`:this.topLevelTaskPredicateSql(),u=new Set,d=[];for(let c of o){if(!Ru.existsSync(c))continue;let l=M(c);try{let p;r!==void 0?p=l.db.all(drizzleOrm.sql`
543
562
  SELECT * FROM (
544
563
  SELECT child.*,
545
564
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -556,7 +575,7 @@ Message: ${n.message}
556
575
  AND ${i}
557
576
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
558
577
  ORDER BY child.started_at ASC
559
- `);for(let f of p)u.has(f.id)||(u.add(f.id),d.push(lr(f)));}catch(p){throw new _("DB_ERROR","Failed to find top-level tasks",p)}finally{l.close();}}if(r!==void 0&&o.length>1){let c=new Map;for(let l of d){let p=l.agent_id??"";c.has(p)||c.set(p,[]),c.get(p).push(l);}d=[];for(let l of c.values())l.sort((p,f)=>(f.started_at??"").localeCompare(p.started_at??"")),d.push(...l.slice(0,r));d.sort((l,p)=>(l.started_at??"").localeCompare(p.started_at??""));}return d}findAllTasks(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!fs$1.existsSync(i))continue;let u=M(i);try{let d=drizzleOrm.eq(a.thread_id,e),c=n?drizzleOrm.and(d,drizzleOrm.eq(a.workspace_id,n)):d,l=u.db.select(re).from(a).where(c).orderBy(drizzleOrm.asc(a.started_at)).all();for(let p of l)s.has(p.id)||(s.add(p.id),o.push(lr(p)));}catch(d){throw new _("DB_ERROR","Failed to find all tasks for thread",d)}finally{u.close();}}return o}findRespondedAgents(e,n){let r=this.resolveDbPaths(),s=new Map;for(let o of r){if(!fs$1.existsSync(o))continue;let i=M(o,{readOnly:true});try{let u=[drizzleOrm.eq(a.thread_id,e),drizzleOrm.sql`${a.completed_at} IS NOT NULL`,drizzleOrm.sql`length(trim(coalesce(${a.result}, ''))) > 0`];n&&u.push(drizzleOrm.eq(a.workspace_id,n));let d=i.db.select({agentId:a.agent_id,lastRepliedAt:drizzleOrm.sql`MAX(${a.completed_at})`}).from(a).where(drizzleOrm.and(...u)).groupBy(a.agent_id).all();for(let c of d){let l=s.get(c.agentId);c.lastRepliedAt&&(!l||c.lastRepliedAt>l)&&s.set(c.agentId,c.lastRepliedAt);}}catch(u){throw new _("DB_ERROR","Failed to find responded agents for thread",u)}finally{i.close();}}return [...s.entries()].map(([o,i])=>({agentId:o,lastRepliedAt:i})).sort((o,i)=>(o.lastRepliedAt===i.lastRepliedAt?0:o.lastRepliedAt>i.lastRepliedAt?-1:1)||(o.agentId===i.agentId?0:o.agentId<i.agentId?-1:1))}findTaskById(e,n,r){let s=this.resolveDbPaths();for(let o of s){if(!fs$1.existsSync(o))continue;let i=M(o);try{let u=drizzleOrm.and(drizzleOrm.eq(a.id,n),drizzleOrm.eq(a.thread_id,e)),d=r?drizzleOrm.and(u,drizzleOrm.eq(a.workspace_id,r)):u,c=i.db.select(re).from(a).where(d).limit(1).get();if(!c)continue;let l=i.db.select(re).from(a).where(drizzleOrm.eq(a.parent_task_id,c.id)).orderBy(drizzleOrm.asc(a.started_at)).all().map(lr);return {task:lr(c),children:l}}catch(u){throw new _("DB_ERROR","Failed to find task by id",u)}finally{i.close();}}}batchFetchTasksQuery(e,n){return drizzleOrm.sql`
578
+ `);for(let f of p)u.has(f.id)||(u.add(f.id),d.push(_r(f)));}catch(p){throw new _("DB_ERROR","Failed to find top-level tasks",p)}finally{l.close();}}if(r!==void 0&&o.length>1){let c=new Map;for(let l of d){let p=l.agent_id??"";c.has(p)||c.set(p,[]),c.get(p).push(l);}d=[];for(let l of c.values())l.sort((p,f)=>(f.started_at??"").localeCompare(p.started_at??"")),d.push(...l.slice(0,r));d.sort((l,p)=>(l.started_at??"").localeCompare(p.started_at??""));}return d}findAllTasks(e,n){let r=this.resolveDbPaths(),s=new Set,o=[];for(let i of r){if(!Ru.existsSync(i))continue;let u=M(i);try{let d=drizzleOrm.eq(a.thread_id,e),c=n?drizzleOrm.and(d,drizzleOrm.eq(a.workspace_id,n)):d,l=u.db.select(re).from(a).where(c).orderBy(drizzleOrm.asc(a.started_at)).all();for(let p of l)s.has(p.id)||(s.add(p.id),o.push(_r(p)));}catch(d){throw new _("DB_ERROR","Failed to find all tasks for thread",d)}finally{u.close();}}return o}findRespondedAgents(e,n){let r=this.resolveDbPaths(),s=new Map;for(let o of r){if(!Ru.existsSync(o))continue;let i=M(o,{readOnly:true});try{let u=[drizzleOrm.eq(a.thread_id,e),drizzleOrm.sql`${a.completed_at} IS NOT NULL`,drizzleOrm.sql`length(trim(coalesce(${a.result}, ''))) > 0`];n&&u.push(drizzleOrm.eq(a.workspace_id,n));let d=i.db.select({agentId:a.agent_id,lastRepliedAt:drizzleOrm.sql`MAX(${a.completed_at})`}).from(a).where(drizzleOrm.and(...u)).groupBy(a.agent_id).all();for(let c of d){let l=s.get(c.agentId);c.lastRepliedAt&&(!l||c.lastRepliedAt>l)&&s.set(c.agentId,c.lastRepliedAt);}}catch(u){throw new _("DB_ERROR","Failed to find responded agents for thread",u)}finally{i.close();}}return [...s.entries()].map(([o,i])=>({agentId:o,lastRepliedAt:i})).sort((o,i)=>(o.lastRepliedAt===i.lastRepliedAt?0:o.lastRepliedAt>i.lastRepliedAt?-1:1)||(o.agentId===i.agentId?0:o.agentId<i.agentId?-1:1))}findTaskById(e,n,r){let s=this.resolveDbPaths();for(let o of s){if(!Ru.existsSync(o))continue;let i=M(o);try{let u=drizzleOrm.and(drizzleOrm.eq(a.id,n),drizzleOrm.eq(a.thread_id,e)),d=r?drizzleOrm.and(u,drizzleOrm.eq(a.workspace_id,r)):u,c=i.db.select(re).from(a).where(d).limit(1).get();if(!c)continue;let l=i.db.select(re).from(a).where(drizzleOrm.eq(a.parent_task_id,c.id)).orderBy(drizzleOrm.asc(a.started_at)).all().map(_r);return {task:_r(c),children:l}}catch(u){throw new _("DB_ERROR","Failed to find task by id",u)}finally{i.close();}}}batchFetchTasksQuery(e,n){return drizzleOrm.sql`
560
579
  SELECT child.id, child.thread_id, child.agent_id, child.status,
561
580
  child.parent_task_id, child.started_at, child.completed_at,
562
581
  child.duration_ms, child.input_tokens, child.output_tokens,
@@ -566,7 +585,7 @@ Message: ${n.message}
566
585
  AND ${this.topLevelTaskPredicateSql()}
567
586
  ${n?drizzleOrm.sql`AND child.workspace_id = ${n}`:drizzleOrm.sql``}
568
587
  ORDER BY child.started_at ASC
569
- `}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!fs$1.existsSync(o))continue;let i=M(o);try{let u=i.db.all(this.batchFetchTasksQuery(e,n));for(let d of u){let c=d.thread_id;r.has(c)||r.set(c,[]),r.get(c).push(Fg(d));}}catch(u){throw new _("DB_ERROR","Failed to batch fetch tasks",u)}finally{i.close();}}return r}findThreadOriginsQuery(e,n){return drizzleOrm.sql`
588
+ `}batchFetchTasks(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!Ru.existsSync(o))continue;let i=M(o);try{let u=i.db.all(this.batchFetchTasksQuery(e,n));for(let d of u){let c=d.thread_id;r.has(c)||r.set(c,[]),r.get(c).push(vh(d));}}catch(u){throw new _("DB_ERROR","Failed to batch fetch tasks",u)}finally{i.close();}}return r}findThreadOriginsQuery(e,n){return drizzleOrm.sql`
570
589
  WITH root AS (
571
590
  SELECT child.thread_id, child.id, child.caller_agent_id, child.parent_task_id,
572
591
  CASE
@@ -618,7 +637,7 @@ Message: ${n.message}
618
637
  FROM tasks AS child
619
638
  LEFT JOIN tasks AS parent ON parent.id = child.parent_task_id
620
639
  WHERE child.id IN (${drizzleOrm.sql.join(e.map(n=>drizzleOrm.sql`${n}`),drizzleOrm.sql`, `)})
621
- `}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!fs$1.existsSync(o))continue;let i=M(o);try{for(let u=0;u<e.length;u+=ys){let d=e.slice(u,u+ys),l=i.db.all(this.findCreatorPointersQuery(d,n)).filter(w=>!r.has(w.thread_id)),p=l.filter(w=>w.creator_task_id!==null&&w.creator_pointer_unverified===0&&w.creator_actor_kind===null).map(w=>w.creator_task_id),f=p.length>0?i.db.all(this.findTaskOriginLineageQuery(p)):[],h=new Map(f.map(w=>[w.task_id,w])),m=new Map(l.map(w=>[w.thread_id,w])),k=d.filter(w=>{if(r.has(w))return !1;let x=m.get(w);return x?!(x.creator_task_id!==null&&x.creator_pointer_unverified===0)&&x.created_by_kind===null:!0}),E=k.length>0?i.db.all(this.findThreadOriginsQuery(k,n)):[],v=new Map(E.map(w=>[w.thread_id,w]));for(let w of l){if(r.has(w.thread_id))continue;let x=pc(w,w.created_by_task_id!==null?h.get(w.created_by_task_id):void 0,v.get(w.thread_id));x&&r.set(w.thread_id,x);}for(let w of E)r.has(w.thread_id)||m.has(w.thread_id)||r.set(w.thread_id,ks(w));}}catch(u){throw new _("DB_ERROR","Failed to fetch thread origins",u)}finally{i.close();}}return r}findThreadsByOrigin(e,n){let r=this.readThreadIds(n,"Failed to find threads by origin"),s=this.findThreadOrigins(r,n),o=r.filter(u=>kc(s.get(u),e));return this.readThreadRowsByIds(o,n,"Failed to find threads by origin").sort(Tc)}findRecentDirectThreads(e,n=5){if(typeof e!="string"||e.trim().length===0)throw new _("VALIDATION","workspaceId is required");if(!Number.isInteger(n)||n<=0)throw new _("VALIDATION","limit must be a positive integer");let r=this.readThreadSortKeys(e).sort(Tc),s=[],o=new Map;for(let c=0;c<r.length;c+=mc){let l=r.slice(c,c+mc),p=this.findThreadOrigins(l.map(f=>f.id),e);for(let[f,h]of p)o.set(f,h);for(let f of l)if(kc(p.get(f.id),"direct")&&(s.push(f.id),s.length===n))break;if(s.length===n)break}let i=new Map;if(s.length>0){let c=this.readThreadRowsByIds(s,e,"Failed to find recent direct threads");for(let l of c)i.set(l.id,l);}let u=[],d=new Map;for(let c of s){let l=i.get(c);if(!l)continue;u.push(l);let p=o.get(c);p&&d.set(c,p);}return {threads:u,originsByThread:d}}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=M(s);try{return o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(u=>u.detail)}finally{o.close();}}return []}explainFindThreadOriginsPlan(e,n){if(e.length===0)return [];let r=this.resolveDbPaths();for(let s of r){if(!fs$1.existsSync(s))continue;let o=M(s);try{let i=o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery(e,n)}`),u=o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery(e)}`),d=o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery(e,n)}`);return [...i,...u,...d].map(c=>c.detail)}finally{o.close();}}return []}explainFindThreadsByOriginPlan(e,n){let r=`__thread_origin_${e}_plan__`,s=this.resolveDbPaths();for(let o of s){if(!fs$1.existsSync(o))continue;let i=M(o);try{let u=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadIdsQuery(n)}`),d=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery([r],n)}`),c=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery([r])}`),l=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery([r],n)}`);return [...u,...d,...c,...l].map(p=>p.detail)}finally{i.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=drizzleOrm.eq(T.id,e),i=r?drizzleOrm.and(o,drizzleOrm.eq(T.workspace_id,r)):o;if(!s.db.select({id:T.id}).from(T).where(i).limit(1).get())return;s.db.update(T).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(T.id,e)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to update thread title",o)}finally{s.close();}}upsertThread(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>{let i=(n.workspaceId?s.select({id:ne.id}).from(ne).where(drizzleOrm.eq(ne.id,n.workspaceId)).limit(1).get():void 0)?n.workspaceId:null,u=new Date().toISOString(),d=s.select({id:T.id,message_count:T.message_count,created_by_task_id:T.created_by_task_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get();if(d){let c={updated_at:u};n.title!==void 0&&(c.title=n.title),n.titleLocked!==void 0&&(c.title_locked=n.titleLocked?1:0),d.created_by_task_id===null&&n.createdByTaskId!=null&&d.message_count===0&&!yc(s,e,n.createdByTaskId)&&(c.created_by_task_id=n.createdByTaskId),s.update(T).set(c).where(drizzleOrm.eq(T.id,e)).run();}else s.insert(T).values({id:e,platform:n.platform,workspace_id:i,created_by_kind:null,created_by_id:null,created_by_task_id:n.createdByTaskId??null,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:u,updated_at:u}).run();},{behavior:"immediate"});}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to upsert thread",s)}finally{r.close();}}ensureThread(e,n,r,s){let o=this.openHandle(true);try{o.db.transaction(i=>{let d=(r?i.select({id:ne.id}).from(ne).where(drizzleOrm.eq(ne.id,r)).limit(1).get():void 0)?r:null,c=i.select({id:T.id,platform:T.platform,workspace_id:T.workspace_id,message_count:T.message_count,created_by_task_id:T.created_by_task_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get();if(c){let p={};d&&!c.workspace_id&&(p.workspace_id=d),c.created_by_task_id===null&&s?.createdByTaskId!=null&&c.message_count===0&&!yc(i,e,s.createdByTaskId)&&(p.created_by_task_id=s.createdByTaskId),Object.keys(p).length>0&&i.update(T).set(p).where(drizzleOrm.eq(T.id,e)).run();return}let l=new Date().toISOString();i.insert(T).values({id:e,platform:n,workspace_id:d,created_by_kind:null,created_by_id:null,created_by_task_id:s?.createdByTaskId??null,message_count:0,created_at:l,updated_at:l}).run();},{behavior:"immediate"});}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to ensure thread",i)}finally{o.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let s=this.openHandle(true);try{let o=new Date().toISOString();return {firstMessage:s.db.transaction(u=>{let c=u.select({message_count:T.message_count}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get()?.message_count===0;return u.run(drizzleOrm.sql`
640
+ `}findThreadOrigins(e,n){let r=new Map;if(e.length===0)return r;let s=this.resolveDbPaths();for(let o of s){if(!Ru.existsSync(o))continue;let i=M(o);try{for(let u=0;u<e.length;u+=As){let d=e.slice(u,u+As),l=i.db.all(this.findCreatorPointersQuery(d,n)).filter(w=>!r.has(w.thread_id)),p=l.filter(w=>w.creator_task_id!==null&&w.creator_pointer_unverified===0&&w.creator_actor_kind===null).map(w=>w.creator_task_id),f=p.length>0?i.db.all(this.findTaskOriginLineageQuery(p)):[],h=new Map(f.map(w=>[w.task_id,w])),m=new Map(l.map(w=>[w.thread_id,w])),k=d.filter(w=>{if(r.has(w))return !1;let x=m.get(w);return x?!(x.creator_task_id!==null&&x.creator_pointer_unverified===0)&&x.created_by_kind===null:!0}),E=k.length>0?i.db.all(this.findThreadOriginsQuery(k,n)):[],v=new Map(E.map(w=>[w.thread_id,w]));for(let w of l){if(r.has(w.thread_id))continue;let x=Cc(w,w.created_by_task_id!==null?h.get(w.created_by_task_id):void 0,v.get(w.thread_id));x&&r.set(w.thread_id,x);}for(let w of E)r.has(w.thread_id)||m.has(w.thread_id)||r.set(w.thread_id,Ss(w));}}catch(u){throw new _("DB_ERROR","Failed to fetch thread origins",u)}finally{i.close();}}return r}findThreadsByOrigin(e,n){let r=this.readThreadIds(n,"Failed to find threads by origin"),s=this.findThreadOrigins(r,n),o=r.filter(u=>Hc(s.get(u),e));return this.readThreadRowsByIds(o,n,"Failed to find threads by origin").sort(Uc)}findRecentDirectThreads(e,n=5){if(typeof e!="string"||e.trim().length===0)throw new _("VALIDATION","workspaceId is required");if(!Number.isInteger(n)||n<=0)throw new _("VALIDATION","limit must be a positive integer");let r=this.readThreadSortKeys(e).sort(Uc),s=[],o=new Map;for(let c=0;c<r.length;c+=$c){let l=r.slice(c,c+$c),p=this.findThreadOrigins(l.map(f=>f.id),e);for(let[f,h]of p)o.set(f,h);for(let f of l)if(Hc(p.get(f.id),"direct")&&(s.push(f.id),s.length===n))break;if(s.length===n)break}let i=new Map;if(s.length>0){let c=this.readThreadRowsByIds(s,e,"Failed to find recent direct threads");for(let l of c)i.set(l.id,l);}let u=[],d=new Map;for(let c of s){let l=i.get(c);if(!l)continue;u.push(l);let p=o.get(c);p&&d.set(c,p);}return {threads:u,originsByThread:d}}explainBatchFetchTasksPlan(e,n){let r=this.resolveDbPaths();for(let s of r){if(!Ru.existsSync(s))continue;let o=M(s);try{return o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,n)}`).map(u=>u.detail)}finally{o.close();}}return []}explainFindThreadOriginsPlan(e,n){if(e.length===0)return [];let r=this.resolveDbPaths();for(let s of r){if(!Ru.existsSync(s))continue;let o=M(s);try{let i=o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery(e,n)}`),u=o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery(e)}`),d=o.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery(e,n)}`);return [...i,...u,...d].map(c=>c.detail)}finally{o.close();}}return []}explainFindThreadsByOriginPlan(e,n){let r=`__thread_origin_${e}_plan__`,s=this.resolveDbPaths();for(let o of s){if(!Ru.existsSync(o))continue;let i=M(o);try{let u=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadIdsQuery(n)}`),d=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findCreatorPointersQuery([r],n)}`),c=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findTaskOriginLineageQuery([r])}`),l=i.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.findThreadOriginsQuery([r],n)}`);return [...u,...d,...c,...l].map(p=>p.detail)}finally{i.close();}}return []}updateThreadTitle(e,n,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=drizzleOrm.eq(T.id,e),i=r?drizzleOrm.and(o,drizzleOrm.eq(T.workspace_id,r)):o;if(!s.db.select({id:T.id}).from(T).where(i).limit(1).get())return;s.db.update(T).set({title:n,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(T.id,e)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to update thread title",o)}finally{s.close();}}upsertThread(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>{let i=(n.workspaceId?s.select({id:ne.id}).from(ne).where(drizzleOrm.eq(ne.id,n.workspaceId)).limit(1).get():void 0)?n.workspaceId:null,u=new Date().toISOString(),d=s.select({id:T.id,message_count:T.message_count,created_by_task_id:T.created_by_task_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get();if(d){let c={updated_at:u};n.title!==void 0&&(c.title=n.title),n.titleLocked!==void 0&&(c.title_locked=n.titleLocked?1:0),d.created_by_task_id===null&&n.createdByTaskId!=null&&d.message_count===0&&!qc(s,e,n.createdByTaskId)&&(c.created_by_task_id=n.createdByTaskId),s.update(T).set(c).where(drizzleOrm.eq(T.id,e)).run();}else s.insert(T).values({id:e,platform:n.platform,workspace_id:i,created_by_kind:null,created_by_id:null,created_by_task_id:n.createdByTaskId??null,title:n.title??null,title_locked:n.titleLocked?1:0,message_count:0,created_at:u,updated_at:u}).run();},{behavior:"immediate"});}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to upsert thread",s)}finally{r.close();}}ensureThread(e,n,r,s){let o=this.openHandle(true);try{o.db.transaction(i=>{let d=(r?i.select({id:ne.id}).from(ne).where(drizzleOrm.eq(ne.id,r)).limit(1).get():void 0)?r:null,c=i.select({id:T.id,platform:T.platform,workspace_id:T.workspace_id,message_count:T.message_count,created_by_task_id:T.created_by_task_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get();if(c){let p={};d&&!c.workspace_id&&(p.workspace_id=d),c.created_by_task_id===null&&s?.createdByTaskId!=null&&c.message_count===0&&!qc(i,e,s.createdByTaskId)&&(p.created_by_task_id=s.createdByTaskId),Object.keys(p).length>0&&i.update(T).set(p).where(drizzleOrm.eq(T.id,e)).run();return}let l=new Date().toISOString();i.insert(T).values({id:e,platform:n,workspace_id:d,created_by_kind:null,created_by_id:null,created_by_task_id:s?.createdByTaskId??null,message_count:0,created_at:l,updated_at:l}).run();},{behavior:"immediate"});}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to ensure thread",i)}finally{o.close();}}saveUserMessage(e,n,r){if(!this.dbExists())return {firstMessage:false};let s=this.openHandle(true);try{let o=new Date().toISOString();return {firstMessage:s.db.transaction(u=>{let c=u.select({message_count:T.message_count}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get()?.message_count===0;return u.run(drizzleOrm.sql`
622
641
  UPDATE threads
623
642
  SET first_message = COALESCE(first_message, ${n}),
624
643
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${n}, 1, 60) ELSE title END,
@@ -626,11 +645,11 @@ Message: ${n.message}
626
645
  message_count = message_count + 1,
627
646
  updated_at = ${o}
628
647
  WHERE id = ${e}
629
- `),c},{behavior:"immediate"})}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save user message",o)}finally{s.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.update(T).set({last_message:n,updated_at:o}).where(drizzleOrm.eq(T.id,e)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save assistant message",o)}finally{s.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};n.title!==void 0&&(s.title=n.title,s.title_locked=1),n.titleLocked!==void 0&&(s.title_locked=n.titleLocked?1:0),r.db.update(T).set(s).where(drizzleOrm.eq(T.id,e)).run();}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to update thread",s)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let s=n;if(!s||typeof s!="object"||Array.isArray(s))return new On("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(d=>d!=="priority"&&d!=="state"))return new On("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=s;if(i.priority===void 0&&i.state===void 0)return new On("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [i.priority,i.state])if(d!=null&&(typeof d!="string"||d.length===0))return new On("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let u=this.openHandle(true);try{let d=r?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,r)):drizzleOrm.eq(T.id,e);return u.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(d).get();if(!l)return null;let p=Nn(l.metadata),f=p.threadTitle,h=f&&typeof f=="object"&&!Array.isArray(f)?{...f}:{};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?p.threadTitle=h:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,k=new Date().toISOString();c.update(T).set({metadata:m,updated_at:k}).where(d).run();let E=c.select({metadata:T.metadata}).from(T).where(d).get();if(!E)throw new _("DB_ERROR","Thread-title metadata update could not be read back");let v=zg(E.metadata);return {threadId:e,priority:v.priority,state:v.state}},{behavior:"immediate"})}catch(d){throw d instanceof _?d:new _("DB_ERROR","Failed to patch thread-title metadata",d)}finally{u.close();}}togglePin(e,n){let r=this.openHandle(true);try{return r.db.transaction(s=>Jg(s,e,n),{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to toggle pin",s)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>Vg(s,e,n),{behavior:"immediate"});}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to reorder pins",s)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e),o=r.db.select({starred:T.starred}).from(T).where(s).get();if(!o)return null;let i=o.starred?0:1;return r.db.update(T).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to toggle star",s)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,s){let i=this.openHandle(true);try{let u=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e);return i.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},f=p.overdrive??{},h=s?.defaultTurns??f.defaultTurns??3,m=s?.updatedBy??"ui",k=new Date().toISOString(),E,v,w,x;switch(r){case "enable-count":{let I=s?.turns??h,O=s?.consumeCurrent?Math.max(I-1,0):I;E=O>0?"count":"off",v=O,w=!0,x="count";break}case "enable-latch":{E="latch",v=0,w=!0,x="latch";break}case "disable":{E="off",v=0,w=!1;break}default:{let I=f.state??"off",O=typeof f.remaining=="number"?f.remaining:0;if(I==="count"&&O>0){let S=O-1;S<=0?(E="off",v=0):(E="count",v=S),w=!0,x="count";}else I==="latch"?(E="latch",v=0,w=!0,x="latch"):(E="off",v=0,w=!1);break}}return p.overdrive={state:E,remaining:v,defaultTurns:h,updatedAt:k,updatedBy:m},c.update(T).set({metadata:JSON.stringify(p),updated_at:k}).where(u).run(),{applied:w,appliedMode:x,state:E,remaining:v}},{behavior:"immediate"})}catch(u){throw u instanceof _?u:new _("DB_ERROR","Failed to resolve overdrive",u)}finally{i.close();}}};g();Tt();Dt();Pt();kt();g();var Ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Xg(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let s=e[r];s<248&&(n+=Ei[s%62]);}for(;n.length<t;)n+=Ei[crypto.randomBytes(1)[0]%62];return n}function fr(t){return `${t}_${Xg(8)}`}function Ec(t,e){let{createHash:n}=nn("crypto"),r=n("sha256").update(e).digest(),s=Buffer.alloc(8);for(let i=0;i<32;i++)s[i%8]^=r[i];let o="";for(let i of s)o+=Ei[i%62];return `${t}_${o}`}Wt();g();var Yg=["urgent","high","medium","low"],Qg=["investigating","in-progress","in-review","on-hold","done"],Rc="custom:";var Zg=new Set(Yg),eh=new Set(Qg);function Ri(t){return typeof t=="string"&&Zg.has(t)}function Si(t){if(typeof t!="string")return false;if(eh.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Rc))return false;let e=t.slice(Rc.length);return e.length>=1&&e.length<=20}function Sc(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 Ii(t){let e=Sc(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,s={};return Ri(r.priority)&&(s.priority=r.priority),Si(r.state)&&(s.state=r.state),s}function Ic(t,e){let n=Sc(t)??{},r={...Ii(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)}Zn();var oh="regeneration_replaced";var ih="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var ah="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",Ni=class extends _{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,s){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${s}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=s;}},yr=class extends Ni{},bi=class extends _{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(Ca),uh=new Set(xa),ch=new Set(Da),lh=new Set(Pa),ph=50,Oc=100,Nc=280,bc=40,fh=new Set(La),Es=["queued","running"];function Oi(t){return fh.has(t)}function K(t){throw new _("VALIDATION",t)}function Qe(t){throw new _("NOT_FOUND",t)}function $(t,e){(typeof t!="string"||t.trim().length===0)&&K(`${e} is required`);}function gr(t={}){let e=t.actor??t,n=e.actorType??"system";return dh.has(n)||K(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&K("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function _h(t){$(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&$(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&K("title must not be empty"),t.title.length>120&&K("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Ri(t.priority)&&K(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Si(t.state)&&K(`invalid state: ${String(t.state)}`);}function gh(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&K("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)&&K(`${n} must be a non-negative integer`);let e=t.limit??ph;return (!Number.isInteger(e)||e<1||e>Oc)&&K(`limit must be between 1 and ${Oc}`),e}function vi(t){typeof t!="string"&&K("text is required");let e=t.trim();return e.length===0&&K("text must not be empty"),e.length>Nc&&K(`text must be at most ${Nc} characters`),e}function gt(t,e){return $(t??"",e),t}function xi(t){lh.has(t)||K(`invalid highlight kind: ${String(t)}`);}function hh(t){ch.has(t)||K(`invalid highlight source: ${String(t)}`);}function mh(t){$(t.threadId,"threadId"),$(t.workspaceId,"workspaceId");let e=t.source??"manual";hh(e),xi(t.kind);let n=vi(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,s=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&s&&r===s?r:void 0),p=gt(l,"taskId");return (r!==p||s!==p)&&K("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let o=gt(r,"coversFromTaskId"),i=gt(s,"coversToTaskId"),u=t.sourceTaskId??o,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return gt(u??void 0,"sourceTaskId"),gt(d??void 0,"detectorVersion"),gt(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:o,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:u,detectorVersion:d,contentFingerprint:c}}function kh(t,e){(!t||typeof t!="object")&&K(`candidates[${e}] is required`),xi(t.kind);let n=vi(t.text),r=gt(t.anchorTaskId,`candidates[${e}].anchorTaskId`),s=gt(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),o=gt(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Ec("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o}));return $(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o,contentFingerprint:i}}function Th(t){Array.isArray(t)||K("candidates must be an array"),t.length>bc&&K(`candidates must contain at most ${bc} items`);let e=new Map;for(let[n,r]of t.entries()){let s=kh(r,n);e.set(s.contentFingerprint,s);}return [...e.values()]}function Tr(t){let e=Ii(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 yh(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&K("event payload must be a JSON object"),e}catch(e){throw new _("VALIDATION","event payload must be JSON serializable",e)}}function hr(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${W.seq}), 0)`}).from(W).where(drizzleOrm.eq(W.thread_id,e)).get()?.maxSeq??0}function mr(t,e){return !!t.select({id:W.id}).from(W).where(drizzleOrm.eq(W.thread_id,e)).limit(1).get()}function tn(t,e){uh.has(e.type)||K(`invalid thread event type: ${String(e.type)}`);let n=fr("the");t.insert(W).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:yh(e.payload),created_at:e.createdAt}).run();let r=t.select().from(W).where(drizzleOrm.eq(W.id,n)).get();if(!r)throw new _("DB_ERROR","Thread event insert did not return a row");return r}function kr(t,e,n,r,s){let o=Tr(e);tn(t,{threadId:e.id,seq:s,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:o.title,priority:o.priority,state:o.state}});}function Ss(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 Rs(t,e,n,r,s,o,i){let u=s==="thread.highlight.created"?Ss(e):{before:i?Ss({...e,...i,id:e.id}):void 0,after:Ss(e)};return tn(t,{threadId:e.thread_id,seq:o,type:s,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:u})}function wh(t,e,n,r,s,o){return tn(t,{threadId:e.thread_id,seq:s,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:Ss(e),...o??{}}})}var Is=class extends Re{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=he.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs$1.existsSync(n))throw new _("NOT_FOUND","Database not found");if(e){let s=he.dirname(n);fs$1.existsSync(s)||fs$1.mkdirSync(s,{recursive:true});}let r=M(n);if(e)try{Pe(r.db,n);}catch(s){throw r.close(),s}return r}findThread(e,n,r){let s=drizzleOrm.eq(T.id,n),o=r===void 0?s:r===null?drizzleOrm.and(s,drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(s,drizzleOrm.eq(T.workspace_id,r));return e.select().from(T).where(o).limit(1).get()}findRegenerationRun(e,n,r){let s=e.select().from(q).where(drizzleOrm.eq(q.id,n)).limit(1).get();if(s&&!(r!==void 0&&!this.findThread(e,s.thread_id,r)))return s}resolveWorkspaceId(e){if($(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:T.workspace_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if($(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,n);return s?Tr(s):null}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){_h(e);let n=gr(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||Qe(`Thread ${e.threadId} not found`);let u=Tr(i),d=e.title!==void 0,c=d&&e.title!==u.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==u.priority,f=e.state!==void 0&&e.state!==u.state,h=c||p||f;if(!h&&!l)return u;let m=i.metadata;(p||f)&&(m=Ic(i.metadata,{priority:e.priority,state:e.state}));let k={};if(h&&(k.metadata=m,k.updated_at=r),c&&(k.title=e.title),d&&(k.title_locked=1),o.update(T).set(k).where(e.workspaceId===void 0?drizzleOrm.eq(T.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.eq(T.workspace_id,e.workspaceId))).run(),!h){let w={...i,title_locked:1};return Tr(w)}let E=hr(o,i.id)+1;mr(o,i.id)||(kr(o,i,n,r,E),E+=1),c&&(tn(o,{threadId:i.id,seq:E,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),E+=1),p&&(tn(o,{threadId:i.id,seq:E,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),E+=1),f&&tn(o,{threadId:i.id,seq:E,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let v={...i,title:c?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return Tr(v)},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to update thread snapshot",o)}finally{s.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if($(e,"threadId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${W.seq}), 0)`}).from(W).where(drizzleOrm.eq(W.thread_id,e)).get()?.maxSeq??0:null}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read latest thread event sequence",s)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if($(e,"threadId"),$(n,"workspaceId"),!fs$1.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(drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...Zt]),drizzleOrm.or(drizzleOrm.isNull(a.parent_task_id),drizzleOrm.eq(a.parent_task_id,"")),drizzleOrm.sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.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(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read completed thread highlight turns",s)}finally{r.close();}}createHighlightRegenerationRun(e){$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.requestId,"requestId"),$(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&$(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findThread(s,e.threadId,e.workspaceId);o||Qe(`Thread ${e.threadId} not found`);let i=s.select().from(q).where(drizzleOrm.and(drizzleOrm.eq(q.thread_id,o.id),drizzleOrm.eq(q.request_id,e.requestId))).orderBy(drizzleOrm.desc(q.requested_at),drizzleOrm.desc(q.id)).limit(1).get();if(i)return {run:i,created:!1};let u=s.select().from(q).where(drizzleOrm.and(drizzleOrm.eq(q.thread_id,o.id),drizzleOrm.inArray(q.status,Es))).orderBy(drizzleOrm.asc(q.requested_at),drizzleOrm.asc(q.id)).limit(1).get();if(u)throw new bi(u);let d=e.runId??fr("thr");s.insert(q).values({id:d,thread_id:o.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let c=s.select().from(q).where(drizzleOrm.eq(q.id,d)).get();if(!c)throw new _("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to create highlight regeneration run",s)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if($(e,"runId"),n!==void 0&&$(n,"workspaceId"),!fs$1.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read highlight regeneration run",s)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if($(e,"threadId"),$(n,"workspaceId"),$(r,"requestId"),!fs$1.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{return this.findThread(s.db,e,n)?s.db.select().from(q).where(drizzleOrm.and(drizzleOrm.eq(q.thread_id,e),drizzleOrm.eq(q.request_id,r))).orderBy(drizzleOrm.desc(q.requested_at),drizzleOrm.desc(q.id)).limit(1).get()??null:null}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to read highlight regeneration request",o)}finally{s.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){$(e,"runId"),n!==void 0&&$(n,"workspaceId");let r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findRegenerationRun(o,e,n);if(i||Qe(`Highlight regeneration run ${e} not found`),Oi(i.status)||K(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;o.update(q).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(q.id,i.id),drizzleOrm.eq(q.status,"queued"))).run();let u=o.select().from(q).where(drizzleOrm.eq(q.id,i.id)).get();if(!u)throw new _("DB_ERROR","Highlight regeneration run start did not return a row");return u},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to start highlight regeneration run",o)}finally{s.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){$(e.runId,"runId"),$(e.errorCode,"errorCode"),e.workspaceId!==void 0&&$(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findRegenerationRun(s,e.runId,e.workspaceId);if(o||Qe(`Highlight regeneration run ${e.runId} not found`),Oi(o.status)||K(`invalid highlight regeneration status: ${o.status}`),o.status==="completed"||o.status==="failed")return o;s.update(q).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(q.id,o.id),drizzleOrm.inArray(q.status,Es))).run();let i=s.select().from(q).where(drizzleOrm.eq(q.id,o.id)).get();if(!i)throw new _("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to fail highlight regeneration run",s)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=ih){$(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update(q).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(q.status,Es)).run().changes,{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to recover interrupted highlight runs",s)}finally{r.close();}}completeHighlightRegenerationRun(e){$(e.runId,"runId"),$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.detectorVersion,"detectorVersion");let n=Th(e.candidates),r=gr(e),s=this.openHandle(true),o=false;try{return s.db.transaction(i=>{let u=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!u||u.thread_id!==e.threadId)&&Qe(`Highlight regeneration run ${e.runId} not found`),Oi(u.status)||K(`invalid highlight regeneration status: ${u.status}`),u.status==="failed")throw new _("CONFLICT","Highlight regeneration run has already failed");if(u.status==="completed")return {run:u,deletedCount:0,createdCount:0,previousAutoCount:u.previous_auto_count??0,newAutoCount:u.new_auto_count??0};o=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||Qe(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&K("detectorVersion does not match the regeneration run");let c=i.select().from(H).where(drizzleOrm.eq(H.thread_id,d.id)).orderBy(drizzleOrm.asc(H.created_at),drizzleOrm.asc(H.id)).all(),l=new Set(n.map(S=>S.contentFingerprint)),p=c.filter(S=>S.source==="auto"&&S.status==="active"&&S.revision===0&&!l.has(S.content_fingerprint??"")),f=c.filter(S=>S.source==="auto"&&S.status==="active").length,h=new Set(c.filter(S=>!p.includes(S)&&S.content_fingerprint).map(S=>S.content_fingerprint)),m=n.filter(S=>!h.has(S.contentFingerprint)),k=new Date().toISOString(),E=hr(i,d.id)+1;mr(i,d.id)||(kr(i,d,r,k,E),E+=1);for(let S of p)i.delete(H).where(drizzleOrm.eq(H.id,S.id)).run(),wh(i,S,r,k,E,{runId:e.runId,reason:oh}),E+=1;let v=0,w=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let S of m){let G=fr("thl");i.insert(H).values({id:G,thread_id:d.id,source:"auto",kind:S.kind,status:"active",text:S.text,covers_from_task_id:S.coversFromTaskId,covers_to_task_id:S.coversToTaskId,revision:0,created_at:k,updated_at:k,agent_id:w,source_task_id:S.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:S.contentFingerprint,dismissed_at:null}).run();let _e=i.select().from(H).where(drizzleOrm.eq(H.id,G)).get();if(!_e)throw new _("DB_ERROR","Regenerated highlight insert did not return a row");Rs(i,_e,r,k,"thread.highlight.created",E),E+=1,v+=1;}let I=i.select().from(H).where(drizzleOrm.eq(H.thread_id,d.id)).all().filter(S=>S.source==="auto"&&S.status==="active").length;tn(i,{threadId:d.id,seq:E,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:f,newAutoCount:I,deletedCount:p.length,createdCount:v}}),i.update(q).set({status:"completed",started_at:u.started_at??k,completed_at:k,error_code:null,previous_auto_count:f,new_auto_count:I}).where(drizzleOrm.and(drizzleOrm.eq(q.id,u.id),drizzleOrm.inArray(q.status,Es))).run();let O=i.select().from(q).where(drizzleOrm.eq(q.id,u.id)).get();if(!O)throw new _("DB_ERROR","Highlight regeneration completion did not return a row");return {run:O,deletedCount:p.length,createdCount:v,previousAutoCount:f,newAutoCount:I}},{behavior:"immediate"})}catch(i){if(o)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:ah});}catch{}throw i instanceof _?i:new _("DB_ERROR","Failed to complete highlight regeneration",i)}finally{s.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let s=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;$(s.threadId,"threadId"),$(s.workspaceId,"workspaceId");let o=gh(s);if(!fs$1.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,s.threadId,s.workspaceId))return null;let u=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${W.seq}), 0)`}).from(W).where(drizzleOrm.eq(W.thread_id,s.threadId)).get()?.maxSeq??0,d;s.beforeSeq!==void 0?d=i.db.select().from(W).where(drizzleOrm.and(drizzleOrm.eq(W.thread_id,s.threadId),drizzleOrm.lt(W.seq,s.beforeSeq))).orderBy(drizzleOrm.desc(W.seq)).limit(o+1).all().reverse():s.afterSeq!==void 0?d=i.db.select().from(W).where(drizzleOrm.and(drizzleOrm.eq(W.thread_id,s.threadId),drizzleOrm.sql`${W.seq} > ${s.afterSeq}`)).orderBy(drizzleOrm.asc(W.seq)).limit(o+1).all():d=i.db.select().from(W).where(drizzleOrm.eq(W.thread_id,s.threadId)).orderBy(drizzleOrm.desc(W.seq)).limit(o+1).all().reverse();let c=d.length>o,l=s.afterSeq!==void 0?d.slice(0,o):c?d.slice(1):d,p=!1,f=l[0];return f&&(p=!!i.db.select({id:W.id}).from(W).where(drizzleOrm.and(drizzleOrm.eq(W.thread_id,s.threadId),drizzleOrm.lt(W.seq,f.seq))).limit(1).get()),{items:l,latestSeq:u,hasMoreOlder:p}}catch(u){throw u instanceof _?u:new _("DB_ERROR","Failed to list thread timeline",u)}finally{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=mh(e),r=gr(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);if(u||Qe(`Thread ${e.threadId} not found`),n.source==="auto"){let f=i.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.thread_id,e.threadId),drizzleOrm.eq(H.source_task_id,n.sourceTaskId),drizzleOrm.eq(H.detector_version,n.detectorVersion),drizzleOrm.eq(H.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(H.created_at),drizzleOrm.asc(H.id)).limit(1).get();if(f)return f}let d=e.id??fr("thl"),c={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:s,updated_at:s,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(H).values(c).run();let l=i.select().from(H).where(drizzleOrm.eq(H.id,d)).get();if(!l)throw new _("DB_ERROR","Highlight insert did not return a row");let p=hr(i,u.id)+1;return mr(i,u.id)||(kr(i,u,r,s,p),p+=1),Rs(i,l,r,s,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to create thread highlight",i)}finally{o.close();}}updateHighlight(e){$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&K("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&K("highlight update requires at least one field"),e.kind!==void 0&&xi(e.kind);let n=e.text===void 0?void 0:vi(e.text),r=gr(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);u||Qe(`Thread ${e.threadId} not found`);let d=i.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.id,e.highlightId),drizzleOrm.eq(H.thread_id,u.id))).limit(1).get();if(d||Qe(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new yr(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new yr(u.id,d.id,e.expectedRevision,d.revision);let c=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,f=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||f.length===0)&&K("highlight projection is incomplete");let h=c!==d.kind||l!==d.text||p!==d.covers_from_task_id||f!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&h?"manual":d.source;if(!(h||m!==d.source))return d;let E=d.revision+1;i.update(H).set({source:m,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:f,revision:E,updated_at:s}).where(drizzleOrm.and(drizzleOrm.eq(H.id,d.id),drizzleOrm.eq(H.revision,d.revision))).run();let v=i.select().from(H).where(drizzleOrm.eq(H.id,d.id)).get();if(!v)throw new _("DB_ERROR","Highlight update did not return a row");let w=hr(i,u.id)+1;return mr(i,u.id)||(kr(i,u,r,s,w),w+=1),Rs(i,v,r,s,"thread.highlight.updated",w,d),v},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to update thread highlight",i)}finally{o.close();}}dismissHighlight(e){$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&K("expectedRevision must be a non-negative integer");let n=gr(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||Qe(`Thread ${e.threadId} not found`);let u=o.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.id,e.highlightId),drizzleOrm.eq(H.thread_id,i.id))).limit(1).get();if(u||Qe(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new yr(i.id,u.id,e.expectedRevision,u.revision);if(u.status==="dismissed")return u;let d=u.revision+1;o.update(H).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(H.id,u.id),drizzleOrm.eq(H.revision,u.revision))).run();let c=o.select().from(H).where(drizzleOrm.eq(H.id,u.id)).get();if(!c)throw new _("DB_ERROR","Highlight dismissal did not return a row");let l=hr(o,i.id)+1;return mr(o,i.id)||(kr(o,i,n,r,l),l+=1),Rs(o,c,n,r,"thread.highlight.deleted",l,u),c},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to dismiss thread highlight",o)}finally{s.close();}}listActiveHighlights(e,n,r={}){if($(e,"threadId"),$(n,"workspaceId"),r.taskId!==void 0&&$(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&$(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&$(r.coversToTaskId,"coversToTaskId"),!fs$1.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{if(!this.findThread(s.db,e,n))return null;let i=s.db.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.thread_id,e),drizzleOrm.eq(H.status,"active"))).orderBy(drizzleOrm.asc(H.created_at),drizzleOrm.asc(H.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let u=s.db.all(drizzleOrm.sql`
648
+ `),c},{behavior:"immediate"})}}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save user message",o)}finally{s.close();}}saveAssistantMessage(e,n,r){if(!this.dbExists())return;let s=this.openHandle(true);try{let o=new Date().toISOString();s.db.update(T).set({last_message:n,updated_at:o}).where(drizzleOrm.eq(T.id,e)).run();}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to save assistant message",o)}finally{s.close();}}updateThread(e,n){if(!this.dbExists())return;let r=this.openHandle(true);try{let s={updated_at:new Date().toISOString()};n.title!==void 0&&(s.title=n.title,s.title_locked=1),n.titleLocked!==void 0&&(s.title_locked=n.titleLocked?1:0),r.db.update(T).set(s).where(drizzleOrm.eq(T.id,e)).run();}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to update thread",s)}finally{r.close();}}patchThreadTitleMetadata(e,n,r){let s=n;if(!s||typeof s!="object"||Array.isArray(s))return new Nn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(s).some(d=>d!=="priority"&&d!=="state"))return new Nn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=s;if(i.priority===void 0&&i.state===void 0)return new Nn("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let d of [i.priority,i.state])if(d!=null&&(typeof d!="string"||d.length===0))return new Nn("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let u=this.openHandle(true);try{let d=r?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,r)):drizzleOrm.eq(T.id,e);return u.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(d).get();if(!l)return null;let p=bn(l.metadata),f=p.threadTitle,h=f&&typeof f=="object"&&!Array.isArray(f)?{...f}:{};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?p.threadTitle=h:delete p.threadTitle;let m=Object.keys(p).length>0?JSON.stringify(p):null,k=new Date().toISOString();c.update(T).set({metadata:m,updated_at:k}).where(d).run();let E=c.select({metadata:T.metadata}).from(T).where(d).get();if(!E)throw new _("DB_ERROR","Thread-title metadata update could not be read back");let v=Mh(E.metadata);return {threadId:e,priority:v.priority,state:v.state}},{behavior:"immediate"})}catch(d){throw d instanceof _?d:new _("DB_ERROR","Failed to patch thread-title metadata",d)}finally{u.close();}}togglePin(e,n){let r=this.openHandle(true);try{return r.db.transaction(s=>$h(s,e,n),{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to toggle pin",s)}finally{r.close();}}reorderPins(e,n){let r=this.openHandle(true);try{r.db.transaction(s=>Hh(s,e,n),{behavior:"immediate"});}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to reorder pins",s)}finally{r.close();}}toggleStar(e,n){let r=this.openHandle(true);try{let s=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e),o=r.db.select({starred:T.starred}).from(T).where(s).get();if(!o)return null;let i=o.starred?0:1;return r.db.update(T).set({starred:i}).where(s).run(),{starred:!!i}}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to toggle star",s)}finally{r.close();}}resolveOverdriveForRequest(e,n,r,s){let i=this.openHandle(true);try{let u=n?drizzleOrm.and(drizzleOrm.eq(T.id,e),drizzleOrm.eq(T.workspace_id,n)):drizzleOrm.eq(T.id,e);return i.db.transaction(c=>{let l=c.select({metadata:T.metadata}).from(T).where(u).get();if(!l)return null;let p=l.metadata?JSON.parse(l.metadata):{},f=p.overdrive??{},h=s?.defaultTurns??f.defaultTurns??3,m=s?.updatedBy??"ui",k=new Date().toISOString(),E,v,w,x;switch(r){case "enable-count":{let I=s?.turns??h,O=s?.consumeCurrent?Math.max(I-1,0):I;E=O>0?"count":"off",v=O,w=!0,x="count";break}case "enable-latch":{E="latch",v=0,w=!0,x="latch";break}case "disable":{E="off",v=0,w=!1;break}default:{let I=f.state??"off",O=typeof f.remaining=="number"?f.remaining:0;if(I==="count"&&O>0){let S=O-1;S<=0?(E="off",v=0):(E="count",v=S),w=!0,x="count";}else I==="latch"?(E="latch",v=0,w=!0,x="latch"):(E="off",v=0,w=!1);break}}return p.overdrive={state:E,remaining:v,defaultTurns:h,updatedAt:k,updatedBy:m},c.update(T).set({metadata:JSON.stringify(p),updated_at:k}).where(u).run(),{applied:w,appliedMode:x,state:E,remaining:v}},{behavior:"immediate"})}catch(u){throw u instanceof _?u:new _("DB_ERROR","Failed to resolve overdrive",u)}finally{i.close();}}};g();Et();$t();Ht();wt();g();var xi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Uh(t){let e=crypto.randomBytes(t*2),n="";for(let r=0;r<e.length&&n.length<t;r++){let s=e[r];s<248&&(n+=xi[s%62]);}for(;n.length<t;)n+=xi[crypto.randomBytes(1)[0]%62];return n}function hr(t){return `${t}_${Uh(8)}`}function Bc(t,e){let{createHash:n}=rn("crypto"),r=n("sha256").update(e).digest(),s=Buffer.alloc(8);for(let i=0;i<32;i++)s[i%8]^=r[i];let o="";for(let i of s)o+=xi[i%62];return `${t}_${o}`}zt();g();var qh=["urgent","high","medium","low"],Fh=["investigating","in-progress","in-review","on-hold","done"],Wc="custom:";var Bh=new Set(qh),Wh=new Set(Fh);function Ci(t){return typeof t=="string"&&Bh.has(t)}function Di(t){if(typeof t!="string")return false;if(Wh.has(t))return true;if(t.startsWith("c_"))return t.length>2;if(!t.startsWith(Wc))return false;let e=t.slice(Wc.length);return e.length>=1&&e.length<=20}function Gc(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 Pi(t){let e=Gc(t);if(!e)return {};let n=e.threadTitle;if(!n||typeof n!="object"||Array.isArray(n))return {};let r=n,s={};return Ci(r.priority)&&(s.priority=r.priority),Di(r.state)&&(s.state=r.state),s}function jc(t,e){let n=Gc(t)??{},r={...Pi(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)}nr();var Jh="regeneration_replaced";var Vh="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED";var Xh="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",$i=class extends _{threadId;highlightId;expectedRevision;currentRevision;constructor(e,n,r,s){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${s}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=n,this.expectedRevision=r,this.currentRevision=s;}},Rr=class extends $i{},Hi=class extends _{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},Yh=new Set(Fa),Qh=new Set(qa),Zh=new Set(Ba),em=new Set(Wa),tm=50,zc=100,Jc=280,Vc=40,nm=new Set(Ga),Ns=["queued","running"];function Mi(t){return nm.has(t)}function K(t){throw new _("VALIDATION",t)}function tt(t){throw new _("NOT_FOUND",t)}function $(t,e){(typeof t!="string"||t.trim().length===0)&&K(`${e} is required`);}function kr(t={}){let e=t.actor??t,n=e.actorType??"system";return Yh.has(n)||K(`invalid actorType: ${String(n)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&K("actorId must be a string or null"),{actorType:n,actorId:e.actorId??null}}function rm(t){$(t.threadId,"threadId"),t.workspaceId!==void 0&&t.workspaceId!==null&&$(t.workspaceId,"workspaceId"),t.title!==void 0&&t.title!==null&&((typeof t.title!="string"||t.title.trim().length===0)&&K("title must not be empty"),t.title.length>120&&K("title must be at most 120 characters")),t.priority!==void 0&&t.priority!==null&&!Ci(t.priority)&&K(`invalid priority: ${String(t.priority)}`),t.state!==void 0&&t.state!==null&&!Di(t.state)&&K(`invalid state: ${String(t.state)}`);}function sm(t){t.beforeSeq!==void 0&&t.afterSeq!==void 0&&K("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)&&K(`${n} must be a non-negative integer`);let e=t.limit??tm;return (!Number.isInteger(e)||e<1||e>zc)&&K(`limit must be between 1 and ${zc}`),e}function Ui(t){typeof t!="string"&&K("text is required");let e=t.trim();return e.length===0&&K("text must not be empty"),e.length>Jc&&K(`text must be at most ${Jc} characters`),e}function kt(t,e){return $(t??"",e),t}function qi(t){em.has(t)||K(`invalid highlight kind: ${String(t)}`);}function om(t){Zh.has(t)||K(`invalid highlight source: ${String(t)}`);}function im(t){$(t.threadId,"threadId"),$(t.workspaceId,"workspaceId");let e=t.source??"manual";om(e),qi(t.kind);let n=Ui(t.text),r=t.coversFromTaskId??t.fromTaskId??t.taskId,s=t.coversToTaskId??t.toTaskId??t.taskId;if(e==="manual"){let l=t.taskId??(r&&s&&r===s?r:void 0),p=kt(l,"taskId");return (r!==p||s!==p)&&K("manual highlights must cover exactly one task"),{source:e,kind:t.kind,text:n,coversFromTaskId:p,coversToTaskId:p,agentId:t.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let o=kt(r,"coversFromTaskId"),i=kt(s,"coversToTaskId"),u=t.sourceTaskId??o,d=t.detectorVersion??(t.idempotencyKey!==void 0?"default":null),c=t.contentFingerprint??t.idempotencyKey??null;return kt(u??void 0,"sourceTaskId"),kt(d??void 0,"detectorVersion"),kt(c??void 0,"contentFingerprint"),{source:e,kind:t.kind,text:n,coversFromTaskId:o,coversToTaskId:i,agentId:t.agentId??null,sourceTaskId:u,detectorVersion:d,contentFingerprint:c}}function am(t,e){(!t||typeof t!="object")&&K(`candidates[${e}] is required`),qi(t.kind);let n=Ui(t.text),r=kt(t.anchorTaskId,`candidates[${e}].anchorTaskId`),s=kt(t.coversFromTaskId,`candidates[${e}].coversFromTaskId`),o=kt(t.coversToTaskId,`candidates[${e}].coversToTaskId`),i=t.contentFingerprint?.trim()||Bc("thl",JSON.stringify({kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o}));return $(i,`candidates[${e}].contentFingerprint`),{kind:t.kind,text:n,anchorTaskId:r,coversFromTaskId:s,coversToTaskId:o,contentFingerprint:i}}function dm(t){Array.isArray(t)||K("candidates must be an array"),t.length>Vc&&K(`candidates must contain at most ${Vc} items`);let e=new Map;for(let[n,r]of t.entries()){let s=am(r,n);e.set(s.contentFingerprint,s);}return [...e.values()]}function Er(t){let e=Pi(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 um(t){try{let e=JSON.stringify(t);return (!e||e==="null"||e.startsWith("["))&&K("event payload must be a JSON object"),e}catch(e){throw new _("VALIDATION","event payload must be JSON serializable",e)}}function Tr(t,e){return t.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${G.seq}), 0)`}).from(G).where(drizzleOrm.eq(G.thread_id,e)).get()?.maxSeq??0}function yr(t,e){return !!t.select({id:G.id}).from(G).where(drizzleOrm.eq(G.thread_id,e)).limit(1).get()}function nn(t,e){Qh.has(e.type)||K(`invalid thread event type: ${String(e.type)}`);let n=hr("the");t.insert(G).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:um(e.payload),created_at:e.createdAt}).run();let r=t.select().from(G).where(drizzleOrm.eq(G.id,n)).get();if(!r)throw new _("DB_ERROR","Thread event insert did not return a row");return r}function wr(t,e,n,r,s){let o=Er(e);nn(t,{threadId:e.id,seq:s,type:"thread.snapshot.imported",actorType:n.actorType,actorId:n.actorId,createdAt:r,payload:{title:o.title,priority:o.priority,state:o.state}});}function vs(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 bs(t,e,n,r,s,o,i){let u=s==="thread.highlight.created"?vs(e):{before:i?vs({...e,...i,id:e.id}):void 0,after:vs(e)};return nn(t,{threadId:e.thread_id,seq:o,type:s,actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:u})}function cm(t,e,n,r,s,o){return nn(t,{threadId:e.thread_id,seq:s,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:vs(e),...o??{}}})}var xs=class extends Se{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=me.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!Ru.existsSync(n))throw new _("NOT_FOUND","Database not found");if(e){let s=me.dirname(n);Ru.existsSync(s)||Ru.mkdirSync(s,{recursive:true});}let r=M(n);if(e)try{Me(r.db,n);}catch(s){throw r.close(),s}return r}findThread(e,n,r){let s=drizzleOrm.eq(T.id,n),o=r===void 0?s:r===null?drizzleOrm.and(s,drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(s,drizzleOrm.eq(T.workspace_id,r));return e.select().from(T).where(o).limit(1).get()}findRegenerationRun(e,n,r){let s=e.select().from(F).where(drizzleOrm.eq(F.id,n)).limit(1).get();if(s&&!(r!==void 0&&!this.findThread(e,s.thread_id,r)))return s}resolveWorkspaceId(e){if($(e,"threadId"),!Ru.existsSync(this.resolveDbPath()))return null;let n=this.openHandle(false);try{return n.db.select({workspaceId:T.workspace_id}).from(T).where(drizzleOrm.eq(T.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof _?r:new _("DB_ERROR","Failed to resolve thread workspace",r)}finally{n.close();}}getSnapshot(e,n){if($(e,"threadId"),!Ru.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let s=this.findThread(r.db,e,n);return s?Er(s):null}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read thread snapshot",s)}finally{r.close();}}updateSnapshot(e){rm(e);let n=kr(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||tt(`Thread ${e.threadId} not found`);let u=Er(i),d=e.title!==void 0,c=d&&e.title!==u.title,l=d&&i.title_locked!==1,p=e.priority!==void 0&&e.priority!==u.priority,f=e.state!==void 0&&e.state!==u.state,h=c||p||f;if(!h&&!l)return u;let m=i.metadata;(p||f)&&(m=jc(i.metadata,{priority:e.priority,state:e.state}));let k={};if(h&&(k.metadata=m,k.updated_at=r),c&&(k.title=e.title),d&&(k.title_locked=1),o.update(T).set(k).where(e.workspaceId===void 0?drizzleOrm.eq(T.id,e.threadId):e.workspaceId===null?drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.isNull(T.workspace_id)):drizzleOrm.and(drizzleOrm.eq(T.id,e.threadId),drizzleOrm.eq(T.workspace_id,e.workspaceId))).run(),!h){let w={...i,title_locked:1};return Er(w)}let E=Tr(o,i.id)+1;yr(o,i.id)||(wr(o,i,n,r,E),E+=1),c&&(nn(o,{threadId:i.id,seq:E,type:"thread.title.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.title,after:e.title}}),E+=1),p&&(nn(o,{threadId:i.id,seq:E,type:"thread.priority.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.priority,after:e.priority}}),E+=1),f&&nn(o,{threadId:i.id,seq:E,type:"thread.state.changed",actorType:n.actorType,actorId:n.actorId,createdAt:r,taskId:e.taskId,payload:{before:u.state,after:e.state}});let v={...i,title:c?e.title:i.title,metadata:m,title_locked:d?1:i.title_locked,updated_at:r};return Er(v)},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to update thread snapshot",o)}finally{s.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,n){if($(e,"threadId"),!Ru.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,n)?r.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${G.seq}), 0)`}).from(G).where(drizzleOrm.eq(G.thread_id,e)).get()?.maxSeq??0:null}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read latest thread event sequence",s)}finally{r.close();}}listCompletedThreadHighlightTurns(e,n){if($(e,"threadId"),$(n,"workspaceId"),!Ru.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(drizzleOrm.and(drizzleOrm.eq(a.thread_id,e),drizzleOrm.eq(a.workspace_id,n),drizzleOrm.inArray(a.status,[...en]),drizzleOrm.or(drizzleOrm.isNull(a.parent_task_id),drizzleOrm.eq(a.parent_task_id,"")),drizzleOrm.sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(drizzleOrm.asc(a.started_at),drizzleOrm.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(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read completed thread highlight turns",s)}finally{r.close();}}createHighlightRegenerationRun(e){$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.requestId,"requestId"),$(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&$(e.runId,"runId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findThread(s,e.threadId,e.workspaceId);o||tt(`Thread ${e.threadId} not found`);let i=s.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.thread_id,o.id),drizzleOrm.eq(F.request_id,e.requestId))).orderBy(drizzleOrm.desc(F.requested_at),drizzleOrm.desc(F.id)).limit(1).get();if(i)return {run:i,created:!1};let u=s.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.thread_id,o.id),drizzleOrm.inArray(F.status,Ns))).orderBy(drizzleOrm.asc(F.requested_at),drizzleOrm.asc(F.id)).limit(1).get();if(u)throw new Hi(u);let d=e.runId??hr("thr");s.insert(F).values({id:d,thread_id:o.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:n,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let c=s.select().from(F).where(drizzleOrm.eq(F.id,d)).get();if(!c)throw new _("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:c,created:!0}},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to create highlight regeneration run",s)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,n){if($(e,"runId"),n!==void 0&&$(n,"workspaceId"),!Ru.existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,n)??null}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to read highlight regeneration run",s)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,n,r){if($(e,"threadId"),$(n,"workspaceId"),$(r,"requestId"),!Ru.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{return this.findThread(s.db,e,n)?s.db.select().from(F).where(drizzleOrm.and(drizzleOrm.eq(F.thread_id,e),drizzleOrm.eq(F.request_id,r))).orderBy(drizzleOrm.desc(F.requested_at),drizzleOrm.desc(F.id)).limit(1).get()??null:null}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to read highlight regeneration request",o)}finally{s.close();}}findHighlightRegenerationRun(e,n,r){return this.getHighlightRegenerationRunByRequest(e,n,r)}startHighlightRegenerationRun(e,n){$(e,"runId"),n!==void 0&&$(n,"workspaceId");let r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findRegenerationRun(o,e,n);if(i||tt(`Highlight regeneration run ${e} not found`),Mi(i.status)||K(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;o.update(F).set({status:"running",started_at:r}).where(drizzleOrm.and(drizzleOrm.eq(F.id,i.id),drizzleOrm.eq(F.status,"queued"))).run();let u=o.select().from(F).where(drizzleOrm.eq(F.id,i.id)).get();if(!u)throw new _("DB_ERROR","Highlight regeneration run start did not return a row");return u},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to start highlight regeneration run",o)}finally{s.close();}}startHighlightRegeneration(e,n){return this.startHighlightRegenerationRun(e,n)}failHighlightRegenerationRun(e){$(e.runId,"runId"),$(e.errorCode,"errorCode"),e.workspaceId!==void 0&&$(e.workspaceId,"workspaceId");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>{let o=this.findRegenerationRun(s,e.runId,e.workspaceId);if(o||tt(`Highlight regeneration run ${e.runId} not found`),Mi(o.status)||K(`invalid highlight regeneration status: ${o.status}`),o.status==="completed"||o.status==="failed")return o;s.update(F).set({status:"failed",completed_at:n,error_code:e.errorCode}).where(drizzleOrm.and(drizzleOrm.eq(F.id,o.id),drizzleOrm.inArray(F.status,Ns))).run();let i=s.select().from(F).where(drizzleOrm.eq(F.id,o.id)).get();if(!i)throw new _("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to fail highlight regeneration run",s)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=Vh){$(e,"errorCode");let n=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(s=>s.update(F).set({status:"failed",completed_at:n,error_code:e}).where(drizzleOrm.inArray(F.status,Ns)).run().changes,{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to recover interrupted highlight runs",s)}finally{r.close();}}completeHighlightRegenerationRun(e){$(e.runId,"runId"),$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.detectorVersion,"detectorVersion");let n=dm(e.candidates),r=kr(e),s=this.openHandle(true),o=false;try{return s.db.transaction(i=>{let u=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!u||u.thread_id!==e.threadId)&&tt(`Highlight regeneration run ${e.runId} not found`),Mi(u.status)||K(`invalid highlight regeneration status: ${u.status}`),u.status==="failed")throw new _("CONFLICT","Highlight regeneration run has already failed");if(u.status==="completed")return {run:u,deletedCount:0,createdCount:0,previousAutoCount:u.previous_auto_count??0,newAutoCount:u.new_auto_count??0};o=!0;let d=this.findThread(i,e.threadId,e.workspaceId);d||tt(`Thread ${e.threadId} not found`),u.detector_version!==e.detectorVersion&&K("detectorVersion does not match the regeneration run");let c=i.select().from(H).where(drizzleOrm.eq(H.thread_id,d.id)).orderBy(drizzleOrm.asc(H.created_at),drizzleOrm.asc(H.id)).all(),l=new Set(n.map(S=>S.contentFingerprint)),p=c.filter(S=>S.source==="auto"&&S.status==="active"&&S.revision===0&&!l.has(S.content_fingerprint??"")),f=c.filter(S=>S.source==="auto"&&S.status==="active").length,h=new Set(c.filter(S=>!p.includes(S)&&S.content_fingerprint).map(S=>S.content_fingerprint)),m=n.filter(S=>!h.has(S.contentFingerprint)),k=new Date().toISOString(),E=Tr(i,d.id)+1;yr(i,d.id)||(wr(i,d,r,k,E),E+=1);for(let S of p)i.delete(H).where(drizzleOrm.eq(H.id,S.id)).run(),cm(i,S,r,k,E,{runId:e.runId,reason:Jh}),E+=1;let v=0,w=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let S of m){let j=hr("thl");i.insert(H).values({id:j,thread_id:d.id,source:"auto",kind:S.kind,status:"active",text:S.text,covers_from_task_id:S.coversFromTaskId,covers_to_task_id:S.coversToTaskId,revision:0,created_at:k,updated_at:k,agent_id:w,source_task_id:S.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:S.contentFingerprint,dismissed_at:null}).run();let ge=i.select().from(H).where(drizzleOrm.eq(H.id,j)).get();if(!ge)throw new _("DB_ERROR","Regenerated highlight insert did not return a row");bs(i,ge,r,k,"thread.highlight.created",E),E+=1,v+=1;}let I=i.select().from(H).where(drizzleOrm.eq(H.thread_id,d.id)).all().filter(S=>S.source==="auto"&&S.status==="active").length;nn(i,{threadId:d.id,seq:E,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:k,payload:{runId:u.id,detectorVersion:e.detectorVersion,previousAutoCount:f,newAutoCount:I,deletedCount:p.length,createdCount:v}}),i.update(F).set({status:"completed",started_at:u.started_at??k,completed_at:k,error_code:null,previous_auto_count:f,new_auto_count:I}).where(drizzleOrm.and(drizzleOrm.eq(F.id,u.id),drizzleOrm.inArray(F.status,Ns))).run();let O=i.select().from(F).where(drizzleOrm.eq(F.id,u.id)).get();if(!O)throw new _("DB_ERROR","Highlight regeneration completion did not return a row");return {run:O,deletedCount:p.length,createdCount:v,previousAutoCount:f,newAutoCount:I}},{behavior:"immediate"})}catch(i){if(o)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Xh});}catch{}throw i instanceof _?i:new _("DB_ERROR","Failed to complete highlight regeneration",i)}finally{s.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,n,r={}){let s=typeof e=="string"?{...r,threadId:e,workspaceId:n}:e;$(s.threadId,"threadId"),$(s.workspaceId,"workspaceId");let o=sm(s);if(!Ru.existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,s.threadId,s.workspaceId))return null;let u=i.db.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${G.seq}), 0)`}).from(G).where(drizzleOrm.eq(G.thread_id,s.threadId)).get()?.maxSeq??0,d;s.beforeSeq!==void 0?d=i.db.select().from(G).where(drizzleOrm.and(drizzleOrm.eq(G.thread_id,s.threadId),drizzleOrm.lt(G.seq,s.beforeSeq))).orderBy(drizzleOrm.desc(G.seq)).limit(o+1).all().reverse():s.afterSeq!==void 0?d=i.db.select().from(G).where(drizzleOrm.and(drizzleOrm.eq(G.thread_id,s.threadId),drizzleOrm.sql`${G.seq} > ${s.afterSeq}`)).orderBy(drizzleOrm.asc(G.seq)).limit(o+1).all():d=i.db.select().from(G).where(drizzleOrm.eq(G.thread_id,s.threadId)).orderBy(drizzleOrm.desc(G.seq)).limit(o+1).all().reverse();let c=d.length>o,l=s.afterSeq!==void 0?d.slice(0,o):c?d.slice(1):d,p=!1,f=l[0];return f&&(p=!!i.db.select({id:G.id}).from(G).where(drizzleOrm.and(drizzleOrm.eq(G.thread_id,s.threadId),drizzleOrm.lt(G.seq,f.seq))).limit(1).get()),{items:l,latestSeq:u,hasMoreOlder:p}}catch(u){throw u instanceof _?u:new _("DB_ERROR","Failed to list thread timeline",u)}finally{i.close();}}listEvents(e,n,r){return this.listTimeline(e,n,r)}getTimeline(e,n,r){return this.listTimeline(e,n,r)}createHighlight(e){let n=im(e),r=kr(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);if(u||tt(`Thread ${e.threadId} not found`),n.source==="auto"){let f=i.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.thread_id,e.threadId),drizzleOrm.eq(H.source_task_id,n.sourceTaskId),drizzleOrm.eq(H.detector_version,n.detectorVersion),drizzleOrm.eq(H.content_fingerprint,n.contentFingerprint))).orderBy(drizzleOrm.asc(H.created_at),drizzleOrm.asc(H.id)).limit(1).get();if(f)return f}let d=e.id??hr("thl"),c={id:d,thread_id:e.threadId,source:n.source,kind:n.kind,status:"active",text:n.text,covers_from_task_id:n.coversFromTaskId,covers_to_task_id:n.coversToTaskId,revision:0,created_at:s,updated_at:s,agent_id:n.agentId,source_task_id:n.sourceTaskId,detector_version:n.detectorVersion,content_fingerprint:n.contentFingerprint,dismissed_at:null};i.insert(H).values(c).run();let l=i.select().from(H).where(drizzleOrm.eq(H.id,d)).get();if(!l)throw new _("DB_ERROR","Highlight insert did not return a row");let p=Tr(i,u.id)+1;return yr(i,u.id)||(wr(i,u,r,s,p),p+=1),bs(i,l,r,s,"thread.highlight.created",p),l},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to create thread highlight",i)}finally{o.close();}}updateHighlight(e){$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&K("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&K("highlight update requires at least one field"),e.kind!==void 0&&qi(e.kind);let n=e.text===void 0?void 0:Ui(e.text),r=kr(e),s=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(i=>{let u=this.findThread(i,e.threadId,e.workspaceId);u||tt(`Thread ${e.threadId} not found`);let d=i.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.id,e.highlightId),drizzleOrm.eq(H.thread_id,u.id))).limit(1).get();if(d||tt(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new Rr(u.id,d.id,e.expectedRevision,d.revision);if(d.status!=="active")throw new Rr(u.id,d.id,e.expectedRevision,d.revision);let c=e.kind??d.kind,l=n??d.text,p=e.coversFromTaskId??d.covers_from_task_id,f=e.coversToTaskId??d.covers_to_task_id;(!l||p.length===0||f.length===0)&&K("highlight projection is incomplete");let h=c!==d.kind||l!==d.text||p!==d.covers_from_task_id||f!==d.covers_to_task_id,m=r.actorType==="user"&&d.source==="auto"&&h?"manual":d.source;if(!(h||m!==d.source))return d;let E=d.revision+1;i.update(H).set({source:m,kind:c,text:l,covers_from_task_id:p,covers_to_task_id:f,revision:E,updated_at:s}).where(drizzleOrm.and(drizzleOrm.eq(H.id,d.id),drizzleOrm.eq(H.revision,d.revision))).run();let v=i.select().from(H).where(drizzleOrm.eq(H.id,d.id)).get();if(!v)throw new _("DB_ERROR","Highlight update did not return a row");let w=Tr(i,u.id)+1;return yr(i,u.id)||(wr(i,u,r,s,w),w+=1),bs(i,v,r,s,"thread.highlight.updated",w,d),v},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to update thread highlight",i)}finally{o.close();}}dismissHighlight(e){$(e.threadId,"threadId"),$(e.workspaceId,"workspaceId"),$(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&K("expectedRevision must be a non-negative integer");let n=kr(e),r=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(o=>{let i=this.findThread(o,e.threadId,e.workspaceId);i||tt(`Thread ${e.threadId} not found`);let u=o.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.id,e.highlightId),drizzleOrm.eq(H.thread_id,i.id))).limit(1).get();if(u||tt(`Highlight ${e.highlightId} not found`),u.revision!==e.expectedRevision)throw new Rr(i.id,u.id,e.expectedRevision,u.revision);if(u.status==="dismissed")return u;let d=u.revision+1;o.update(H).set({status:"dismissed",text:null,revision:d,updated_at:r,dismissed_at:r}).where(drizzleOrm.and(drizzleOrm.eq(H.id,u.id),drizzleOrm.eq(H.revision,u.revision))).run();let c=o.select().from(H).where(drizzleOrm.eq(H.id,u.id)).get();if(!c)throw new _("DB_ERROR","Highlight dismissal did not return a row");let l=Tr(o,i.id)+1;return yr(o,i.id)||(wr(o,i,n,r,l),l+=1),bs(o,c,n,r,"thread.highlight.deleted",l,u),c},{behavior:"immediate"})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to dismiss thread highlight",o)}finally{s.close();}}listActiveHighlights(e,n,r={}){if($(e,"threadId"),$(n,"workspaceId"),r.taskId!==void 0&&$(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&$(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&$(r.coversToTaskId,"coversToTaskId"),!Ru.existsSync(this.resolveDbPath()))return null;let s=this.openHandle(false);try{if(!this.findThread(s.db,e,n))return null;let i=s.db.select().from(H).where(drizzleOrm.and(drizzleOrm.eq(H.thread_id,e),drizzleOrm.eq(H.status,"active"))).orderBy(drizzleOrm.asc(H.created_at),drizzleOrm.asc(H.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let u=s.db.all(drizzleOrm.sql`
630
649
  SELECT id, started_at FROM tasks WHERE thread_id = ${e}
631
650
  ORDER BY started_at ASC, id ASC
632
- `),d=new Map(u.map((f,h)=>[f.id,h])),c=r.taskId===void 0?void 0:d.get(r.taskId),l=r.coversFromTaskId===void 0?void 0:d.get(r.coversFromTaskId),p=r.coversToTaskId===void 0?void 0:d.get(r.coversToTaskId);return i.filter(f=>{let h=d.get(f.covers_from_task_id),m=d.get(f.covers_to_task_id);if(h===void 0||m===void 0)return !1;let k=Math.min(h,m),E=Math.max(h,m);return !(c!==void 0&&(c<k||c>E)||l!==void 0&&E<l||p!==void 0&&k>p)})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to list active thread highlights",o)}finally{s.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};g();Tt();Dt();Pt();kt();Wt();Ks();var Q=class extends _{reason;constructor(e,n="VALIDATION",r=e,s){super(n,r,s),this.name="CommonCodeRepositoryError",this.reason=e;}},xc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function vh(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=xc[n%xc.length];return e.slice(0,12)}function Cc(){return `c_${vh()}`}function xh(t){return typeof t=="string"&&Gs.includes(t)}function Ch(t){return typeof t=="string"&&js.includes(t)}function Cn(t){if(!xh(t))throw new Q("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Dc(t){if(!Ch(t))throw new Q("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function Pc(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new Q("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function Dn(t){if(typeof t!="string"||t.trim().length===0)throw new Q("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function As(t){if(typeof t!="string"||t.trim().length===0)throw new Q("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function xt(t,e){return drizzleOrm.and(drizzleOrm.eq(C.code_group,t),drizzleOrm.or(drizzleOrm.isNull(C.workspace_id),drizzleOrm.eq(C.workspace_id,e)))}var Os=class extends Re{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=he.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!fs$1.existsSync(n))throw new _("NOT_FOUND","Database not found");e&&fs$1.mkdirSync(he.dirname(n),{recursive:true});let r=M(n);if(e)try{Pe(r.db,n);}catch(s){throw r.close(),s}return r}listSelectable(e,n){if(Cn(e),Dn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(C).where(drizzleOrm.and(xt(e,n),drizzleOrm.eq(C.is_archived,0))).orderBy(drizzleOrm.asc(C.sort_order),drizzleOrm.asc(C.code)).all()}catch(s){throw new _("DB_ERROR","Failed to list selectable common codes",s)}finally{r.close();}}listForHistory(e,n){if(Cn(e),Dn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(C).where(xt(e,n)).orderBy(drizzleOrm.asc(C.sort_order),drizzleOrm.asc(C.code)).all()}catch(s){throw new _("DB_ERROR","Failed to list common-code history",s)}finally{r.close();}}reorder(e){let n=e.group;if(Cn(n),Dn(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let s of e.codes)As(s);if(new Set(e.codes).size!==e.codes.length)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(C).where(xt(n,e.workspaceId)).all(),i=o.filter(h=>h.is_archived===0),u=new Set(o.map(h=>h.code)),d=new Set(i.map(h=>h.code)),c=e.codes.find(h=>!u.has(h));if(c)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(h=>!d.has(h)))throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let l=new Map(i.map(h=>[h.code,h])),p=e.codes.map(h=>{let m=l.get(h);if(!m)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${h}`);return m}),f;for(let[h,m]of p.entries())m.sort_order!==h&&(f??=new Date().toISOString(),s.update(C).set({sort_order:h,updated_at:f}).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,n),drizzleOrm.eq(C.code,m.code))).run());return s.select().from(C).where(xt(n,e.workspaceId)).orderBy(drizzleOrm.asc(C.sort_order),drizzleOrm.asc(C.code)).all()},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to reorder common codes",s)}finally{r.close();}}resolve(e,n){if(Cn(e),As(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).limit(1).get()??null}catch(s){throw new _("DB_ERROR","Failed to resolve common code",s)}finally{r.close();}}createThreadState(e){Dn(e.workspaceId);let n=Pc(e.name);Dc(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{if(s.select({code:C.code}).from(C).where(drizzleOrm.and(xt("THREAD_STATE",e.workspaceId),drizzleOrm.eq(C.is_archived,0),drizzleOrm.eq(C.code_name,n))).limit(1).get())throw new Q("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=s.select({maxSortOrder:drizzleOrm.sql`max(${C.sort_order})`}).from(C).where(xt("THREAD_STATE",e.workspaceId)).get(),u=new Date().toISOString(),d=Cc();for(;s.select({code:C.code}).from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,"THREAD_STATE"),drizzleOrm.eq(C.code,d))).limit(1).get();)d=Cc();s.insert(C).values({code_group:"THREAD_STATE",code:d,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:u,updated_at:u}).run();let c=s.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,"THREAD_STATE"),drizzleOrm.eq(C.code,d))).limit(1).get();if(!c)throw new _("DB_ERROR","Created common code could not be read back");return c},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to create thread state common code",s)}finally{r.close();}}updateDisplay(e){if(Cn(e.group),As(e.code),Dn(e.workspaceId),e.name===void 0&&e.color===void 0)throw new Q("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:Pc(e.name);e.color!==void 0&&Dc(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e.group),drizzleOrm.eq(C.code,e.code))).limit(1).get();if(!o)throw new Q("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(o,e.workspaceId),n===null&&o.is_builtin!==1)throw new Q("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&o.is_archived===0){let d=drizzleOrm.and(xt(e.group,e.workspaceId),drizzleOrm.eq(C.is_archived,0));if(s.select({code:C.code}).from(C).where(drizzleOrm.and(d,drizzleOrm.eq(C.code_name,n),drizzleOrm.sql`${C.code} <> ${e.code}`)).limit(1).get())throw new Q("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),s.update(C).set(i).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e.group),drizzleOrm.eq(C.code,e.code))).run();let u=s.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e.group),drizzleOrm.eq(C.code,e.code))).limit(1).get();if(!u)throw new _("DB_ERROR","Updated common code could not be read back");return u},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to update common-code display values",s)}finally{r.close();}}archive(e,n,r,s=true){if(Cn(e),As(n),Dn(r),typeof s!="boolean")throw new Q("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let o=this.openHandle(true);try{return o.db.transaction(i=>{let u=i.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).limit(1).get();if(!u)throw new Q("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(u.is_builtin===1)throw new Q("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(u,r),!s&&u.code_name!==null&&i.select({code:C.code}).from(C).where(drizzleOrm.and(xt(e,r),drizzleOrm.eq(C.is_archived,0),drizzleOrm.eq(C.code_name,u.code_name),drizzleOrm.ne(C.code,n))).limit(1).get())throw new Q("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${u.code_name}`);i.update(C).set({is_archived:s?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).run();let d=i.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).limit(1).get();if(!d)throw new _("DB_ERROR","Archived common code could not be read back");return d},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to archive common code",i)}finally{o.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new Q("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};pn();Zn();g();var Ze={threadContext:"crewx_thread_context",apps:"apps",appsGuidance:"apps_guidance",availableApps:"available_apps",crewxUiState:"crewx_ui_state"};function Lh(t){return t.replace(new RegExp(`<${Ze.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${Ze.threadContext}>`,"g"),"").replace(new RegExp(`<${Ze.apps}\\b[^>]*>[\\s\\S]*?<\\/${Ze.apps}>`,"g"),"").replace(new RegExp(`<${Ze.appsGuidance}\\b[^>]*>[\\s\\S]*?<\\/${Ze.appsGuidance}>`,"g"),"").replace(new RegExp(`<${Ze.availableApps}\\b[^>]*>[\\s\\S]*?<\\/${Ze.availableApps}>`,"g"),"").replace(new RegExp(`<${Ze.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${Ze.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
651
+ `),d=new Map(u.map((f,h)=>[f.id,h])),c=r.taskId===void 0?void 0:d.get(r.taskId),l=r.coversFromTaskId===void 0?void 0:d.get(r.coversFromTaskId),p=r.coversToTaskId===void 0?void 0:d.get(r.coversToTaskId);return i.filter(f=>{let h=d.get(f.covers_from_task_id),m=d.get(f.covers_to_task_id);if(h===void 0||m===void 0)return !1;let k=Math.min(h,m),E=Math.max(h,m);return !(c!==void 0&&(c<k||c>E)||l!==void 0&&E<l||p!==void 0&&k>p)})}catch(o){throw o instanceof _?o:new _("DB_ERROR","Failed to list active thread highlights",o)}finally{s.close();}}listHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}getActiveHighlights(e,n,r){return this.listActiveHighlights(e,n,r)}};g();Et();$t();Ht();wt();zt();Qs();var Q=class extends _{reason;constructor(e,n="VALIDATION",r=e,s){super(n,r,s),this.name="CommonCodeRepositoryError",this.reason=e;}},Yc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Tm(){let t=crypto.randomBytes(16),e="";for(let n of t)e+=Yc[n%Yc.length];return e.slice(0,12)}function Qc(){return `c_${Tm()}`}function ym(t){return typeof t=="string"&&Xs.includes(t)}function wm(t){return typeof t=="string"&&Ys.includes(t)}function Dn(t){if(!ym(t))throw new Q("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${t}`)}function Zc(t){if(!wm(t))throw new Q("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${t}`)}function el(t){let e=typeof t=="string"?t.trim():"",n=[...e].length;if(n<1||n>20)throw new Q("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function Pn(t){if(typeof t!="string"||t.trim().length===0)throw new Q("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Cs(t){if(typeof t!="string"||t.trim().length===0)throw new Q("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function Lt(t,e){return drizzleOrm.and(drizzleOrm.eq(C.code_group,t),drizzleOrm.or(drizzleOrm.isNull(C.workspace_id),drizzleOrm.eq(C.workspace_id,e)))}var Ds=class extends Se{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=me.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let n=this.resolveDbPath();if(!e&&!Ru.existsSync(n))throw new _("NOT_FOUND","Database not found");e&&Ru.mkdirSync(me.dirname(n),{recursive:true});let r=M(n);if(e)try{Me(r.db,n);}catch(s){throw r.close(),s}return r}listSelectable(e,n){if(Dn(e),Pn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(C).where(drizzleOrm.and(Lt(e,n),drizzleOrm.eq(C.is_archived,0))).orderBy(drizzleOrm.asc(C.sort_order),drizzleOrm.asc(C.code)).all()}catch(s){throw new _("DB_ERROR","Failed to list selectable common codes",s)}finally{r.close();}}listForHistory(e,n){if(Dn(e),Pn(n),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(C).where(Lt(e,n)).orderBy(drizzleOrm.asc(C.sort_order),drizzleOrm.asc(C.code)).all()}catch(s){throw new _("DB_ERROR","Failed to list common-code history",s)}finally{r.close();}}reorder(e){let n=e.group;if(Dn(n),Pn(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let s of e.codes)Cs(s);if(new Set(e.codes).size!==e.codes.length)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(C).where(Lt(n,e.workspaceId)).all(),i=o.filter(h=>h.is_archived===0),u=new Set(o.map(h=>h.code)),d=new Set(i.map(h=>h.code)),c=e.codes.find(h=>!u.has(h));if(c)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${n}/${c}`);if(e.codes.length!==i.length||e.codes.some(h=>!d.has(h)))throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let l=new Map(i.map(h=>[h.code,h])),p=e.codes.map(h=>{let m=l.get(h);if(!m)throw new Q("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${n}/${h}`);return m}),f;for(let[h,m]of p.entries())m.sort_order!==h&&(f??=new Date().toISOString(),s.update(C).set({sort_order:h,updated_at:f}).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,n),drizzleOrm.eq(C.code,m.code))).run());return s.select().from(C).where(Lt(n,e.workspaceId)).orderBy(drizzleOrm.asc(C.sort_order),drizzleOrm.asc(C.code)).all()},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to reorder common codes",s)}finally{r.close();}}resolve(e,n){if(Dn(e),Cs(n),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).limit(1).get()??null}catch(s){throw new _("DB_ERROR","Failed to resolve common code",s)}finally{r.close();}}createThreadState(e){Pn(e.workspaceId);let n=el(e.name);Zc(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{if(s.select({code:C.code}).from(C).where(drizzleOrm.and(Lt("THREAD_STATE",e.workspaceId),drizzleOrm.eq(C.is_archived,0),drizzleOrm.eq(C.code_name,n))).limit(1).get())throw new Q("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${n}`);let i=s.select({maxSortOrder:drizzleOrm.sql`max(${C.sort_order})`}).from(C).where(Lt("THREAD_STATE",e.workspaceId)).get(),u=new Date().toISOString(),d=Qc();for(;s.select({code:C.code}).from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,"THREAD_STATE"),drizzleOrm.eq(C.code,d))).limit(1).get();)d=Qc();s.insert(C).values({code_group:"THREAD_STATE",code:d,code_name:n,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:u,updated_at:u}).run();let c=s.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,"THREAD_STATE"),drizzleOrm.eq(C.code,d))).limit(1).get();if(!c)throw new _("DB_ERROR","Created common code could not be read back");return c},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to create thread state common code",s)}finally{r.close();}}updateDisplay(e){if(Dn(e.group),Cs(e.code),Pn(e.workspaceId),e.name===void 0&&e.color===void 0)throw new Q("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let n=e.name===void 0||e.name===null?e.name:el(e.name);e.color!==void 0&&Zc(e.color);let r=this.openHandle(true);try{return r.db.transaction(s=>{let o=s.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e.group),drizzleOrm.eq(C.code,e.code))).limit(1).get();if(!o)throw new Q("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(o,e.workspaceId),n===null&&o.is_builtin!==1)throw new Q("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof n=="string"&&o.is_archived===0){let d=drizzleOrm.and(Lt(e.group,e.workspaceId),drizzleOrm.eq(C.is_archived,0));if(s.select({code:C.code}).from(C).where(drizzleOrm.and(d,drizzleOrm.eq(C.code_name,n),drizzleOrm.sql`${C.code} <> ${e.code}`)).limit(1).get())throw new Q("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),s.update(C).set(i).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e.group),drizzleOrm.eq(C.code,e.code))).run();let u=s.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e.group),drizzleOrm.eq(C.code,e.code))).limit(1).get();if(!u)throw new _("DB_ERROR","Updated common code could not be read back");return u},{behavior:"immediate"})}catch(s){throw s instanceof _?s:new _("DB_ERROR","Failed to update common-code display values",s)}finally{r.close();}}archive(e,n,r,s=true){if(Dn(e),Cs(n),Pn(r),typeof s!="boolean")throw new Q("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let o=this.openHandle(true);try{return o.db.transaction(i=>{let u=i.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).limit(1).get();if(!u)throw new Q("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${n}`);if(u.is_builtin===1)throw new Q("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(u,r),!s&&u.code_name!==null&&i.select({code:C.code}).from(C).where(drizzleOrm.and(Lt(e,r),drizzleOrm.eq(C.is_archived,0),drizzleOrm.eq(C.code_name,u.code_name),drizzleOrm.ne(C.code,n))).limit(1).get())throw new Q("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${u.code_name}`);i.update(C).set({is_archived:s?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).run();let d=i.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.code_group,e),drizzleOrm.eq(C.code,n))).limit(1).get();if(!d)throw new _("DB_ERROR","Archived common code could not be read back");return d},{behavior:"immediate"})}catch(i){throw i instanceof _?i:new _("DB_ERROR","Failed to archive common code",i)}finally{o.close();}}assertOwnership(e,n){if(e.workspace_id!==null&&e.workspace_id!==n)throw new Q("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};fn();nr();g();var nt={threadContext:"crewx_thread_context",apps:"apps",appsGuidance:"apps_guidance",availableApps:"available_apps",crewxUiState:"crewx_ui_state"};function Sm(t){return t.replace(new RegExp(`<${nt.threadContext}\\b[^>]*>[\\s\\S]*?<\\/${nt.threadContext}>`,"g"),"").replace(new RegExp(`<${nt.apps}\\b[^>]*>[\\s\\S]*?<\\/${nt.apps}>`,"g"),"").replace(new RegExp(`<${nt.appsGuidance}\\b[^>]*>[\\s\\S]*?<\\/${nt.appsGuidance}>`,"g"),"").replace(new RegExp(`<${nt.availableApps}\\b[^>]*>[\\s\\S]*?<\\/${nt.availableApps}>`,"g"),"").replace(new RegExp(`<${nt.crewxUiState}\\b[^>]*>[\\s\\S]*?<\\/${nt.crewxUiState}>`,"g"),"").replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
633
652
  `).filter(s=>!(s.startsWith("Loaded ")&&s.includes("layouts from")||s.includes("[dotenv@")||s.includes("[Nest]")&&s.includes("DEBUG")||s.startsWith("Registered custom layout:")||s.startsWith("Updated custom layout:"))).join(`
634
- `).trim()}function Mh(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.provider;return typeof n=="string"?n:void 0}catch{return}}function $h(t,e,n){if(!t||e&&at(t,n))return "";let r=t;try{let s=JSON.parse(r);Array.isArray(s)?r=s.filter(o=>o?.type==="text"&&o?.text).map(o=>o.text).join(`
635
- `):s&&typeof s=="object"&&s.result!==void 0&&(r=s.result||"");}catch{r=Lh(r);}return r}var Hh=new Set(["success","failed","stopped","running"]),Uh=new Set(["failed","stopped"]),qh={user_stop:"stopped by the user before it finished",runner_lost:"end of run not observed \u2014 it may have done part of the work or may still be running",launch_failed:"the runner never started this run"},Ns=200;function Lc(t){if(t.length<=Ns)return t;let e=t.charCodeAt(Ns-1),n=e>=55296&&e<=56319?Ns-1:Ns;return t.slice(0,n)}function Fh(t){let e=ze(t),n=typeof t.error=="string"?t.error.split(`
636
- `)[0]??"":"";if(e){let r=qh[e];return Lc(n?`${r}; ${n}`:r)}return n?Lc(n):void 0}var bs=class{dbPath;constructor(e){this.dbPath=e??he.join(ji.homedir(),".crewx","crewx.db");}getThreadRepo(){return new ws({dbPath:this.dbPath})}getThreadHistoryRepo(){return new Is({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r,s){let o=this.getThreadRepo(),i=o.findThreadById(e);if(i){if(i.platform!==n)throw new Error(`Thread '${e}' already exists with platform '${i.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return o.ensureThread(e,n,r,s),{created:false}}return o.ensureThread(e,n,r,s),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,s=this.getThreadRepo(),o=s.findThreadById(e),i=s.findTopLevelTasks(e,void 0,r,n?.agentId||void 0),u=new Set(["queued","cancelled"]),d=n?.currentTraceId;i=i.filter(h=>(!h.status||!u.has(h.status))&&(!d||h.trace_id!==d&&h.id!==d));let c=s.findInterceptedRequests(i.map(h=>h.id));c.size>0&&(i=i.map(h=>c.has(h.id)?{...h,prompt:c.get(h.id)}:h));let l=o?.platform??"cli",p=this.rowsToMessages(i),f=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,o?.workspace_id??null);return {threadId:e,platform:l,messages:p,...f?{highlights:f}:{},metadata:{title:o?.title??void 0,firstMessage:o?.first_message??void 0,lastMessage:o?.last_message??void 0,messageCount:o?.message_count??0,updatedAt:o?.updated_at?new Date(o.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new Os({dbPath:this.dbPath}),s=(o,i)=>{try{return r.resolve(o,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:s("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:s("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,s){let{firstMessage:o}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:o}}async saveAssistantMessage(e,n,r,s){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(s=>typeof s.text=="string"&&s.text.length>0).map(s=>({id:s.id,text:s.text,kind:s.kind,source:s.source,coversFromTaskId:s.covers_from_task_id,coversToTaskId:s.covers_to_task_id,createdAt:s.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let s={status:r.status??"",error:r.error,metadata:r.metadata},o=r.status?xe(s):void 0,i=Mh(r.metadata),u=$h(r.result,o!==void 0&&Uh.has(o),i);if(u||o!==void 0&&Hh.has(o)){let d={agent_id:r.agent_id,task_id:r.id};if(o&&o!=="success"){d.status=o;let c=Fh(s);c&&(d.reason=c);}n.push({id:`${r.id}-assistant`,text:u,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:d});}}return n}};var Ci=class extends mt{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new bs(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,n,r,s){}async afterAssistantMessage(e,n,r){}attach(e){this.unsubStart=e.on("task:start",async n=>{if(!n.threadId)return;let r=n.platform??"cli";try{let s=await this._provider.ensureThread(n.threadId,r,n.workspaceId,{createdByTaskId:n.traceId}),o=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,o.id,s.created||o.firstMessage,n);}catch{}}),this.unsubEnd=e.on("task:end",async n=>{if(!n.result)return;let r=n.metadata?.threadId;if(!r)return;let s=n.agentRef?.replace(/^@/,"")??"";try{let{id:o}=await this._provider.saveAssistantMessage(r,n.result,s);await this.afterAssistantMessage(r,o,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=Ci;exports.FileLoggerPlugin=xs;exports.SqliteTracingPlugin=Ti;
653
+ `).trim()}function Im(t){if(t)try{let e=JSON.parse(t);if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e.provider;return typeof n=="string"?n:void 0}catch{return}}function Am(t,e,n){if(!t||e&&ct(t,n))return "";let r=t;try{let s=JSON.parse(r);Array.isArray(s)?r=s.filter(o=>o?.type==="text"&&o?.text).map(o=>o.text).join(`
654
+ `):s&&typeof s=="object"&&s.result!==void 0&&(r=s.result||"");}catch{r=Sm(r);}return r}var Om=new Set(["success","failed","stopped","running"]),Nm=new Set(["failed","stopped"]),bm={user_stop:"stopped by the user before it finished",runner_lost:"end of run not observed \u2014 it may have done part of the work or may still be running",launch_failed:"the runner never started this run"},Ps=200;function tl(t){if(t.length<=Ps)return t;let e=t.charCodeAt(Ps-1),n=e>=55296&&e<=56319?Ps-1:Ps;return t.slice(0,n)}function vm(t){let e=Xe(t),n=typeof t.error=="string"?t.error.split(`
655
+ `)[0]??"":"";if(e){let r=bm[e];return tl(n?`${r}; ${n}`:r)}return n?tl(n):void 0}var Ls=class{dbPath;constructor(e){this.dbPath=e??me.join(ea.homedir(),".crewx","crewx.db");}getThreadRepo(){return new Os({dbPath:this.dbPath})}getThreadHistoryRepo(){return new xs({dbPath:this.dbPath})}updateThread(e,n){this.getThreadRepo().updateThread(e,{title:n.title});}async ensureThread(e,n,r,s){let o=this.getThreadRepo(),i=o.findThreadById(e);if(i){if(i.platform!==n)throw new Error(`Thread '${e}' already exists with platform '${i.platform}' \u2014 cannot change to '${n}' (platform is immutable)`);return o.ensureThread(e,n,r,s),{created:false}}return o.ensureThread(e,n,r,s),{created:true}}async fetchHistory(e,n){let r=n?.limit??100,s=this.getThreadRepo(),o=s.findThreadById(e),i=s.findTopLevelTasks(e,void 0,r,n?.agentId||void 0),u=new Set(["queued","cancelled"]),d=n?.currentTraceId;i=i.filter(h=>(!h.status||!u.has(h.status))&&(!d||h.trace_id!==d&&h.id!==d));let c=s.findInterceptedRequests(i.map(h=>h.id));c.size>0&&(i=i.map(h=>c.has(h.id)?{...h,prompt:c.get(h.id)}:h));let l=o?.platform??"cli",p=this.rowsToMessages(i),f=n?.includeHighlights===false?void 0:this.readActiveHighlights(e,o?.workspace_id??null);return {threadId:e,platform:l,messages:p,...f?{highlights:f}:{},metadata:{title:o?.title??void 0,firstMessage:o?.first_message??void 0,lastMessage:o?.last_message??void 0,messageCount:o?.message_count??0,updatedAt:o?.updated_at?new Date(o.updated_at).getTime():void 0}}}async fetchThreadState(e){try{let n=this.getThreadHistoryRepo().getSnapshot(e);if(!n)return;let r=new Ds({dbPath:this.dbPath}),s=(o,i)=>{try{return r.resolve(o,i)?.code_name||i}catch{return i}};return {...n.title?{title:n.title}:{},...n.priority?{priority:{code:n.priority,name:s("THREAD_PRIORITY",n.priority)}}:{},...n.state?{state:{code:n.state,name:s("THREAD_STATE",n.state)}}:{}}}catch{return}}async fetchHighlights(e){let n=this.getThreadRepo().findThreadById(e);return this.readActiveHighlights(e,n?.workspace_id??null)}async saveUserMessage(e,n,r,s){let{firstMessage:o}=this.getThreadRepo().saveUserMessage(e,n);return {id:e,firstMessage:o}}async saveAssistantMessage(e,n,r,s){return this.getThreadRepo().saveAssistantMessage(e,n),{id:e}}close(){}readActiveHighlights(e,n){if(!n)return [];try{return (this.getThreadHistoryRepo().listActiveHighlights(e,n)??[]).filter(s=>typeof s.text=="string"&&s.text.length>0).map(s=>({id:s.id,text:s.text,kind:s.kind,source:s.source,coversFromTaskId:s.covers_from_task_id,coversToTaskId:s.covers_to_task_id,createdAt:s.created_at}))}catch{return}}rowsToMessages(e){let n=[];for(let r of e){r.prompt&&n.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:{caller_agent_id:r.caller_agent_id,task_id:r.id}});let s={status:r.status??"",error:r.error,metadata:r.metadata},o=r.status?De(s):void 0,i=Im(r.metadata),u=Am(r.result,o!==void 0&&Nm.has(o),i);if(u||o!==void 0&&Om.has(o)){let d={agent_id:r.agent_id,task_id:r.id};if(o&&o!=="success"){d.status=o;let c=vm(s);c&&(d.reason=c);}n.push({id:`${r.id}-assistant`,text:u,isAssistant:true,timestamp:new Date(r.started_at).getTime(),taskId:r.id,metadata:d});}}return n}};var Fi=class extends yt{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Ls(e?.dbPath);}get conversationProvider(){return this._provider}async afterUserMessage(e,n,r,s){}async afterAssistantMessage(e,n,r){}attach(e){this.unsubStart=e.on("task:start",async n=>{if(!n.threadId)return;let r=n.platform??"cli";try{let s=await this._provider.ensureThread(n.threadId,r,n.workspaceId,{createdByTaskId:n.traceId}),o=await this._provider.saveUserMessage(n.threadId,n.message??"");await this.afterUserMessage(n.threadId,o.id,s.created||o.firstMessage,n);}catch{}}),this.unsubEnd=e.on("task:end",async n=>{if(!n.result)return;let r=n.metadata?.threadId;if(!r)return;let s=n.agentRef?.replace(/^@/,"")??"";try{let{id:o}=await this._provider.saveAssistantMessage(r,n.result,s);await this.afterAssistantMessage(r,o,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};exports.ConversationPlugin=Fi;exports.FileLoggerPlugin=$s;exports.SqliteTracingPlugin=Ni;